I am having problems keeping file paths straight. I have some PHP code
that I need to work in two environments. One is locally, on a Windows
machine. The other is on a "real" server.
Locally, my file structure looks like this (simplified):
C:\htdocs\common.php
C:\htdocs\a.php
C:\htdocs\1.csv
C:\htdocs\b\b.php
C:\htdocs\b\2.csv
And, in both Apache (httpd.conf) and PHP (php.ini), the doc_root is set
to:
"C:\htdocs"
Now, the "common.php" code is intended to be used by everyone. So both
"a.php" and "b.php" begin with this:
<?php
require ("common.php");
?>
At first, that didn't work because b.php couldn't find the file. So I
also added "C:\htdocs" to the include_path in php.ini. Now the above
require() directive works for both a.php and b.php.
However, the code in common.php needs to do the following:
<?php
// Read data files
$file_1_data = file ("1.csv", FILE_TEXT);
$file_2_data = file ("b/2.csv", FILE_TEXT);
?>
What happens is that both csv files will be loaded correctly by a.php ,
but both will fail to load in b.php, because it runs from the "b"
directory. I can't use relative paths (e.g. "../1.csv") because the
relative path is different depending on which file is actually being
run.
I tried using somewhat more absolute paths, like "/1.csv" and
"/b/2.csv", hoping that "/" would be resolve to doc_root (or
include_path), but that didn't work at all. Neither file loaded. I've
also tried replacing the forward slashes with backslashes and it made no
difference.
I also can't use "fully" absolute paths, such as "C:\htdocs\1.csv",
because "C:\htdocs" is only valid on my local machine. Once everything
is tested locally, it must be uploaded to a remote server, where the
paths will be something more like:
/home/content/username/html/mysite.com/common.php
/home/content/username/html/mysite.com/a.php
/home/content/username/html/mysite.com/1.csv
/home/content/username/html/mysite.com/b/b.php
/home/content/username/html/mysite.com/b/2.csv
So how do I specify these paths, both in require() directives and as
arguments to functions like file(), so that they are always found
correctly relative to doc_root?
Thanks in advance for any help.
// Perform all file operations from doc_root
chdir ($_SERVER['DOCUMENT_ROOT']);
So, any file that includes common.php will access other files relative to
the root directory, regardless of where the including file is located, and
the details of the server's filesystem are not an issue (as long as the
server provides 'DOCUMENT_ROOT').
in my opinion, we can use the absolute path.
define the root directory, and code like this:
define('ROOT', dirname(__FILE__) . "\\");
$file_1_data = file (ROOT . "1.csv", FILE_TEXT);
$file_2_data = file (ROOT . "b/2.csv", FILE_TEXT);