Section 21.3. Cross-Platform Code 3: Path and Line Separators


21.3. 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 dovery 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 variableyou 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.

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 \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. If you want the files to be portable, always use a consistent newline character. If you're not sure what newline type a file is using, try Sean Burke's "whatnewline" utility from http://interglacial.com/~sburke/pub/whatnewline.




PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net