Reputation: 12881
In PHP how do you refer to files in an OS friendly manner? I'm looking at some code like
<?php
require_once(dirname(dirname(__FILE__)).'/common/config.inc.php');
...
that I have to run on a Windows machine, but it doesn't parse the path right:
PHP Warning: require_once(C:\workspace/common/config.inc.php): failed to open stream: No such file or directory in C:\workspace\somescript.php on line 2
PHP Fatal error: require_once(): Failed opening required 'C:\workspace/common/config.inc.php' (include_path='.;C:\php5\pear') in C:\workspace\somescript.php on line 2
It looks like it's trying to open with the forward-slashes which windows doesn't like. The file C:\workspace\commonconfig.inc.php exists. The script is just not finding it because it has the forward-slashes right?
In the require_once statement, shouldn't I be expressing the last part of the path in some os-friendly way? How do you do that?
In PHP, is there something similar to Python's os.path.normpath(path) ? ..which takes a path-like string and returns the path appropriate to the running OS...
Upvotes: 1
Views: 447
Reputation: 625387
I do this:
$dir = str_replace("\\", '/', dirname(dirname(__FILE__));
require_once $dir . '/common/config.inc.php';
Works on both Windows and Linux. Although in this case, why not just do:
require_once '../common/config.inc.php';
?
Upvotes: 2
Reputation: 161
require_once(realpath(dirname(__FILE__) . "/the/rest/of/yr/path/and/file.php"));
Upvotes: 2
Reputation: 546463
There are a few things you could use.
Instead of hardcoding the slashes, use the built-in constant DIRECTORY_SEPARATOR
, or as I prefer, make your own:
define('DS', DIRECTORY_SEPARATOR);
..it makes your code a bit more compact.
Alternatively, use realpath()
and express all your paths with unix-style forward slashes, since:
On windows realpath() will change unix style paths to windows style.
<?php echo realpath('/windows/system32'); ?>
The above example will output:
C:\WINDOWS\System32
Upvotes: 8