Proper way to set PHP include path for *Nix and Windows

Jeff picture Jeff · Dec 24, 2009 · Viewed 9.7k times · Source

Is this the proper way to define an include path for both *nix and Windows?

define( 'INCPATH', realpath( dirname( __FILE__ ) ) . '/' );

Note the trailing forward-slash I included above. Is the forward-slash for includes/requires the same for both OS's, as well?

EDIT (UPDATED WITH ANSWER):

From what I can gather, my code below is the proper way to universally define an include/require path for both *nix and Windows OS's. Feel free to correct anything in the comments below.

The thing that confused me were the many examples I saw showing replacement of back-slashes (\) into forward-slashes(/). Based on some of the answers below, this is unnecessary.

So the final correct code (for the purist) is:

define( 'INCPATH', realpath( dirname( __FILE__ ) ) . DIRECTORY_SEPARATOR );

That code produces the following results:

*nix: /path/to/the/file/

Windows: C:\Path To\the\file\

A brief explanation, working our way from the inside (__FILE__) out (realpath()):

FILE The full path and filename of the file. Always contains an absolute path with symlinks resolved.

dirname() The returned string is path with any trailing /component removed. Responsible for removing the filename.

realpath() Returns the canonicalized (normalized/standardized) absolute pathname on success. The resulting path will have no symbolic link, '/./' or '/../' components. I assume this is included for thoroughness because __FILE__ already resolves symlinks. Or maybe it's included to resolve relative paths? Either way, it seems to solidify our goal.

Answer

Derek Illchuk picture Derek Illchuk · Dec 24, 2009

Forward slashes will work for both OS's, and it's the way to go.

I couldn't find an absolute reference to this, but it's indicated in several places in the PHP manual, like here and here. And, it works for me, a Windows & Linux user.

Lastly, you may end up specifying mixed-paths on Windows, like c:\\apache\\htdocs\\myapp/index.php, and that all works fine.