- Предопределенные константы в PHP
- Некоторые предопределенные константы
- Магические константы
- Using DIRECTORY_SEPARATOR in file_exists() on Windows
- Do you need to use the PHP DIRECTORY_SEPARATOR constant?
- Take your skills to the next level ⚡️
- About
- Search
- When to use DIRECTORY_SEPARATOR in PHP code?
- 4 Answers 4
Предопределенные константы в PHP
В РНР есть ряд предопределенных констант. Например, PHP_VERSION и PHP_0S содержат соответственно версию РНР и название операционной системы, на которую установлен сервер.
Предопределенная константа DIRECTORY_SEPARATOR содержит разделитель пути. Для Windows это «\», для Linux и остальных — «/». Так как Windows понимает оба разделителя, достаточно использовать в коде разделитель Linux вместо константы.
Тем не менее, DIRECTORY_SEPARATOR полезен. Все функции, отдающие путь (вроде realpath ), отдают его с специфичными для ОС разделителями. Чтобы разбить такой путь на составляющие как раз удобно использовать константу:
$segments = explode(DIRECTORY_SEPARATOR, realpath(__FILE__));
Существуют так же несколько «магических» констант. Они могут менять свое значение в зависимости от их использования. Например, константы __LINE__ и __FILE__ содержат в себе соответственно номер строки и имя файла сценария.
Некоторые предопределенные константы
- PHP_OS — Операционная система, под которую собирался PHP
- PHP_VERSION — Текущая версия PHP
- PHP_EOL — Символ конца строки, используемый на данной платформе
- DIRECTORY_SEPARATOR — Разделитель пути
Магические константы
- __LINE__ — Текущий номер строки в файле
- __FILE__ — Полный путь и имя текущего файла
- __DIR__ — Директория файла, эквивалентно вызову dirname(__FILE__)
- __FUNCTION__ — Имя функции
- __CLASS__ — Имя класса, содержит название пространства имен, в котором класс был объявлен
- __TRAIT__ — Имя трейта, имя содержит название пространства имен, в котором трейт был объявлен
- __METHOD__ — Имя метода класса
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
- 1С:Предприятие (31)
- API (29)
- Bash (43)
- CLI (100)
- CMS (139)
- CSS (50)
- Frontend (75)
- HTML (66)
- JavaScript (150)
- Laravel (72)
- Linux (147)
- MySQL (76)
- PHP (125)
- React.js (66)
- SSH (27)
- Ubuntu (68)
- Web-разработка (509)
- WordPress (73)
- Yii2 (69)
- БазаДанных (95)
- Битрикс (66)
- Блог (29)
- Верстка (43)
- ИнтернетМагаз… (84)
- КаталогТоваров (87)
- Класс (30)
- Клиент (27)
- Ключ (28)
- Команда (69)
- Компонент (60)
- Конфигурация (62)
- Корзина (32)
- ЛокальнаяСеть (28)
- Модуль (34)
- Навигация (31)
- Настройка (140)
- ПанельУправле… (29)
- Плагин (33)
- Пользователь (26)
- Практика (99)
- Сервер (74)
- Событие (27)
- Теория (105)
- Установка (66)
- Файл (47)
- Форма (58)
- Фреймворк (192)
- Функция (36)
- ШаблонСайта (68)
Using DIRECTORY_SEPARATOR in file_exists() on Windows
DIRECTORY_SEPARATOR equals to «/» (Unix) or «\» (Windows) depending on the platform.
Why above case is false with DIRECTORY_SEPARATOR?
Because in double-quoted strings «\123» translates to «Q» (more details in PHP Manual).
When construction Windows paths, you should escape backslash: «C:\\1212.txt» or use single-quoted strings: ‘C:\1212.txt’ .
Even better and cleaner way would be to use Unix directory separator «/» hard-coded directly in path string (without any constants), it works just fine under Windows: «C:/1212.txt» .
according to stackoverflow.com/questions/625332/… the DIRECTORY_SEPARATOR would be needed because there ARE other OS’s which do NOT use / and \ see also edward.de.leau.net/…
When nit comes to PS — Path Separators here’s a tip for you:
so my advice would be to make everything /
If your building your application to be cross platformt hen think about doing this.
define('DS','/'); define('BASE_ROOT',str_replace('\\',DS,dirname(__FILE__))); require_once BASE_ROOT . DS . 'includes' . DS . 'init.php';
Then it should work nice on both platforms.
var_dump(file_exists("C:\\1212.txt"));
The backslash is the escape character to to add one to a string you need to follow it with another.
That will allow your script to work on Windows. If you would like your script to be portable, check out RobertPitts answer and remember to use case sensitive file paths.
Most unix distros are case-sensitive where as NTFS based data is optional, my advice on this would be to keep EVERYTHING lowercase, to support both systems.
DIRECTORY_SEPARATOR returns / on Unix systems and \ on Win.
DIRECTORY_SEPARATOR is a PHP constant, helping programmers to write script that works across different operating systems.
Assuming you’re on a Windows machine, it looks like yours is misconfigured.
I have seen some mistakes on blogs, and other places concerning Windows being «just fine» with forward slashes, and there isn’t a need for *Directory Separator constants which provide \ or / characters depending on if you are running Windows, Nix, etc .
These constants are /very/ necessary because forward slash support in Windows is only /partially/ implemented.
Most Windows Command Line Utilities have switches that are accessed using /, forward slash, rather than hyphens, -, which is unix style. This is why the directory separator constants are important in scripts.
Broken Example:
Error Message: Invalid switch — «Temp».
Do you need to use the PHP DIRECTORY_SEPARATOR constant?
The PHP DIRECTORY_SEPARATOR constant is used as a placeholder for the directory separator symbol for the operating system that runs the PHP script.
In macOS and other UNIX-based OS, the directory separator is a slash ( path/to/file )
In Windows, both slash and backslash symbols can be used as the directory separator ( path/to/file or path\to\file )
Because these three are the only popular operating systems used worldwide, you don’t really need the DIRECTORY_SEPARATOR constant when defining a file location.
You can replace the DIRECTORY_SEPARATOR constant with the forward slash symbol and it should run without issues in Windows, macOS, and Linux:
Even if a different operating system may be used in the future, most likely it will also adhere to the standard of using a slash as the directory separator symbol.
But if you feel that you need to use the DIRECTORY_SEPARATOR constant, then the best way to construct a path is to use the join() function.
Here’s an example of constructing a path with the DIRECTORY_SEPARATOR constant:
Using the join() function will save you from having to type DIRECTORY_SEPARATOR many times.
The DIRECTORY_SEPARATOR constant grants you a future-proof syntax if somehow the directory separator symbol gets changed (although it’s not likely going to happen)
Take your skills to the next level ⚡️
I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.
Search
Type the keyword below and hit enter
When to use DIRECTORY_SEPARATOR in PHP code?
The above code is from a plugin from the WordPress. I don’t understand why half of it uses DIRECTORY_SEPARATOR , but the other half uses «/» ?
«DIRECTORY_SEPARATOR is not necessarily needed, PHP always converts / to the appropriate character in its file functions.»
windows understands the use of ‘/’ as the directory separator. I run PHP code on both linux and windows without any change. I use ‘/’ always in file paths etc. The main issue is that windows is not case sensitive as regards filenames so it is important to always use correct lettercase on windows otherwise it will not work when moved to linux ,
This is only important when you want to run your code on different operating systems who use a filesystem where the directory separator is not the same, like Windows or Linux. I am only running on Apache on Linux (even under Windows 10 you may use Apache with Ubuntu Subsystem). So I encode everything with the forward slash.
4 Answers 4
Because in different OS there is different directory separator. In Windows it’s \ in Linux it’s / . DIRECTORY_SEPARATOR is constant with that OS directory separator. Use it every time in paths.
In you code snippet we clearly see bad practice code. If framework/cms are widely used it doesn’t mean that it’s using best practice code.
Yeah that’s what the OP intends to know whether it is just a bad practice or does it serve any purpose to have both in the same line? And your comment is actually one possible answer to the question.
I don’t think it’s necessary to use the constant. I’ve always used a / in my paths and they work on both Windows and Unix. I think PHP is smart enough to do the conversion.
there’s not much point in using DIRECTORY_SEPARATOR in WordPress code though, because WordPress’ built-in functions don’t use it, they just use forward slashes (a little inconsistently, like in the code being discussed). In WordPress, you just need to expect a mix of forward and backslashes used as directory separators. But for PHP outside a framework, or at least outside WordPress, I think you’re right, DIRECTORY_SEPARATOR is best. See cmljnelson.wordpress.com/2018/07/26/…
All of the io functions will internally convert slashes based on the OS being used. There is no need to use DIRECTORY_SEPARATOR (except in the scenario where you are passing filepaths to non-PHP code). In fact, it can even cause unexpected side effects in URLs as pointed out by Julian in dev.to/c33s/always-use—as-directory-seperator-in-php-43l7
All of the PHP IO functions will internally convert slashes to the appropriate character, so it’s not a huge deal which method you use. Below are some things to consider.
- It can look ugly and confusing when you print out your file paths and there is a mix of \ and / . This won’t ever happen if DIRECTORY_SEPARATOR is used
- Using something such as $generated_css = DIRECTORY_SEPARATOR.’minified.css’; will work all fine and dandy for file IO, but if a developer unknowingly references it in a URL such as echo «$generated_css‘>»; , a bug was just created. Did you catch it? While this will work on Windows, for everyone else a forward slash, instead of a backslash, will be in $generated_css , resulting in the percent encoded, non-existant, URL https://example.com%5cgenerated_css! When using a DIRECTORY_SEPARATOR you have to take special care to make sure your filepath variables never end up in a URL.
- And lastly, in the unlikely scenario your filepath is used by non-PHP code — for example, in a shell_exec call — you won’t be able to mix slashes and will need to either construct the filepath with DIRECTORY_SEPARATOR or use realpath.
I think you have that in reverse for your URL example: on Windows, a back slash would be created which could being encoded to %5c
My URL example is for everything except Windows. «While this will work on Windows, for everyone else. «
This should be the accepted answer. Mostly because it’s more readble to avoid using DIRECTORY_SEPERATOR and secondly because there’re some pitfails everyone should know about.
I learned from distributing code that the best way for your application to run on both Linux and Windows is to never use DIRECTORY_SEPARATOR, or backslashes \\ , and to ONLY use forward slashes / .
Why? Because a backslash directory separator ONLY works on Windows. And forward slashes works on ALL (Linux, Windows, Mac altogether).
Using the constant DIRECTORY_SEPARATOR or escaping your backslashes \\ quickly becomes messy. I mean look at it:
$file = 'path' . DIRECTORY_SEPARATOR . 'to' . DIRECTORY_SEPARATOR . 'file'; $file = str_replace('/', DIRECTORY_SEPARATOR, 'path/to/file'; $file = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? 'path\\to\\file' : 'path/to/file';
When you can just do this:
The only downside is that on Windows; PHP will return backslashes for all file references from functions like realpath() , glob() , and magic constants like __FILE__ and __DIR__ . So you might need to str_replace() them into forward slashes to keep it consistant.
$dir = str_replace('\\', '/', realpath('../'));
I wish there was a php.ini setting to always return forward slashes.