I'm at a loss as to why I'm having this problem. I'm running IIS on Windows 7 for development but have a Linux server for web hosting.
The problem is whenever I use a PHP system function, like file_exists()
or move_uploaded_file()
, using a path like /support/images/flags/countries/
always fails. The support directory is under the root directory of the site. All the documentation I have read seems to state that the path should work. Is this because I use Windows? Even the posts on SO seem to say it should work.
In order to get it to work correctly I have to use a path like {$_SERVER['DOCUMENT_ROOT']}/support/images/flags/countries
Can anyone explain why my thinking is wrong?
Using $_SERVER['DOCUMENT_ROOT']
is not a good idea, especially if you're planning to use CLI in your application, where server variables are not available. You should try something like
dirname(__FILE__)
in your script instead, or consider introducing a custom constant which would contain the full system path to your root folder - e.g,
define('MY_APP_ROOT', '/my/full/path/');
Much easier than relying on Apache or IIS in this.
You should use the DIRECTORY_SEPARATOR
constant in PHP. Files and folders work somewhat different in Linux. Using this will retain compatibility in Windows and Linux.
Here is a small function I've been using to build paths:
function buildPath(...$segments){
return join(DIRECTORY_SEPARATOR, $segments);
}
echo buildPath('path', 'to', 'folder');
Also another compatibility know-how is that Linux is case sensitive, also in databases when selecting a "TabLe". In Windows it will work no-matter how you write it, on Linux it must be exactly the same.
Creating a link in the browser using forward slashes is the way to go, like for example linking people to /var/wwww/css/index.css
(most likely just ./css/index.css
) but for internal operations a backslash is required in Linux.