开发者

PHP is including relative to the URL path and not the file path, how do you change this?

开发者 https://www.devze.com 2023-02-01 14:39 出处:网络
I have a PHP file /a/b/file.php with the line require(\"../connect.php\"); In connect.php there is a line

I have a PHP file /a/b/file.php with the line

require("../connect.php");

In connect.php there is a line

require("../config.inc.php");

This all works fine on my local server. There are a bunch of files using connect.php and they all work fine too.

However on the hosting site /a/b/file.php throws an error:

Fatal error: require() [function.require]: Failed opening required 
'../config.inc.php' (include_path='.:/usr/local/php5/lib/php') in
/******/connect.php on line 3

I suspect that even though connect.php is in 开发者_开发知识库another folder, it's looking for it relative to /a/b. Is there a php.ini setting to change this?


Why dont you use something like:

require( dirname(__FILE__).DIRECTORY_SEPARATOR."..".DIRECTORY_SEPARATOR."connect.php");

This way you will avoid problems like when you develop an app on a Unix-Like system and deploy it on a Windows systems, or viceversa.


I don't know if there's a php.ini setting, but usually I use $_SERVER['DOCUMENT_ROOT'] for my included files.

require $_SERVER['DOCUMENT_ROOT']."/path/relative/to/document_root/file.php";

There are some cases where a relative path is better, but most of the time the files you want to include will stay in the same dir.


Usually I personally make a file called global.php (which is in the root directory of the project) where I define() a constant, include libs and so on.

<?php
// ...
define('APP_INCLUDE_DIR', dirname(__FILE__) .'/');
// ...
?>

Afterwards I include that file in all other files located in the same directory (e.g. index.php with require('global.php'). Now that everything is executed at that directory level you can use the constant APP_INCLUDE_DIR in every file which gets included.

<?php
require('global.php');

// ...
require_once(APP_INCLUDE_DIR .'a/b/c/connect.php');
?>

And in a/b/c/connect.php you could write for example

<?php
// ...
require_once(APP_INCLUDE_DIR .'a/b/config.inc.php');
?>


Check your include_path in your PHP.ini file. http://php.net/manual/en/function.set-include-path.php

For example, on my local server (XAMPP) it looks like this: `include_path .;C:\xampp\php\PEAR

You can do a phpinfo() to find out also.

0

精彩评论

暂无评论...
验证码 换一张
取 消