I have PHP code that requires other php files by address $_SERVER['DOCUMENT_ROOT'].'/subdir/file.php';
First of all -- is this the best proper way to include things? Obviously I don't want to use path like '../../subdir/file.php';
because moving the file would break it.
But another interesting issue is that if I run this file through command line then $_SERVER
is not created. I can fake it via $_SERVER['DOCUMENT_ROOT'] = '.';
but I'm curious to开发者_如何学运维 if this is the best practice. Seems like not.
Edit: Obviously there are many ways to skin this cat, although I think the best practice is to define a variable (or a constant) responsible for the include directory. Such as:
define('INC_DIR', $_SERVER['DOCUMENT_ROOT'].'/../includes');
or
if (PHP_SAPI == 'cli') {
$_includes = '../includes';
} else {
$_includes = $_SERVER['DOCUMENT_ROOT'].'/../includes/');
}
And use the aforementioned variable or constant throughout the code.
I prefer to use a folder definition system in my architectures. Something like this:
define( 'DIR_ROOT',dirname(__FILE__) );
That works both in command line and web mode. Use that in your application entry point (index.php in most cases) and then load the rest of your framework from that file outward. All inbound calls to your application should be routed via .htaccess or other method so that they call index.php?foo=bar etc.
I also hate typing DIRECTORY_SEPARATOR all the time so I usually make the first definition:
define( 'DS' , DIRECTORY_SEPARATOR );
This enables you later to do something like this:
require_once( DIR_ROOT.DS.'myfolder'.DS.'myfile.class.php' );
Alternatively if you don't want or need to modify your php files and you just need a page to be executed normally you could use curl
. Most Linux and Unix systems have it installed.
$ curl http://www.example.com/myscript.php &> /dev/null
The &> /dev/null
part sends the output into a black hole in the system so you don't have to see the HTML which was returned by the request.
if(PHP_SAPI == 'cli')
{
$_SERVER['DOCUMENT_ROOT'] = '/path/to/webroot';
}
精彩评论