Cross-platform code 3: Path and line separators

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

You can make your life easier by using forward slashes / across the board, because Windows accepts both \ and / as path separator. 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 make the world of difference.

Line separators are slightly trickier, and, if you don't have PHP 5.0.2 or higher, the easiest way to handle it 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 re-use 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 new-line character for the current OS.

Author's Note: Using the OS-specific new-line character, eg \r\n on Windows, is not a smart move if you want the generated files to be portable to other platforms. The reason for 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 \n. So, if you run a script on Windows that saves a file, it will use \r\n as line ends, but if you try to load that using a Unix machine, it will just look for \n - d'oh! If you want the files to be portable, always use a consistent new-line character.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Cross-platform code 4: Coping with php.ini differences >>

Previous chapter: Cross-platform code 2: Using extensions

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.