19.7.5 Cross-platform code 3: Path and line separatorsThis is NOT the latest copy of this book; click here for the latest version.
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 see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|