Cross-Platform Code 3: Path and Line Separators

Each OS has a different way of representing path and line separators for files. Unix and modern Mac OS versions use / as a path separator and \n as a line separator, whereas Windows uses \ or / as a path separator and \r\n as a line separator. Just to make things even more confusing, some old Mac OS versions use \r as a line separator and : as a path separator, so all three are different!

You can make your life easier by using forward slashes (/) everywhere, because Windows accepts both \ and / as path separators. If you are able to refrain from using OS-specific path names like c:/home/website/index.php, then do—very often, just /home/website/index.php will work just fine everywhere.

Line separators are slightly trickier and, if you don't have PHP 5.0.2 or higher, the easiest way to handle them is to put a few lines of code into your shared code library that checks the OS and stores the appropriate line end character in a variable—you can then reuse that variable throughout your other scripts. If you do have PHP 5.0.2 or higher, the constant PHP_EOL is available to you and represents the appropriate newline character for the current OS.

Warning

Using the OS-specific newline character, e.g., \r\n on Windows, is not a smart move if you want the generated files to be portable to other platforms. This is because a script running on Windows will load and save files with \r\n as line ends, whereas the same script on Unix will use just ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.