简体   繁体   中英

php include doesn't find file, but path seems accurate

I save a root directory in a variable $root . Then I append the rest of the file's address for an include.

error_reporting(E_ALL);//gives me nothing btw

$root = "http://myhomedirectory.int/tools";
include ("{$root}/resources/php/includes/authenticate.php");
echo     "{$root}/resources/php/includes/authenticate.php";

For some reason the include fails, but when I copy/paste what the echo statement produces, I am taken to authenticate.php . I have set permissions on that file to 777. Why would this be?

include() is used to read file contents of local php files. It starts to search in the include directory, defined in php.ini, and finally ends up with trying to interprete the argument as a relative path.

When you provide an absolute path (like http:// ...), the remote server will never return a php-script, but plain html. (Even if it is your LOCAL server, the call using the external adress will not return ANY PHP-Code because the server will parse the file content and return the generated html )

So, to include a php-file on your server, use a relative path or place it into the include directory defined.


Sidenode: If you want to include various files from each ohter, you always* have to define the path relative to the executed script. Assuming the layout:

/index.php
/folder1/file1.php
/folder1/folder2/file2.php

And you want to include file2 in file1 and file1 in index.php (this is the executed script), PHP will perform the following steps:

index.php is the executed script, so using include("folder1/file1.php") will perform the desired action. But if you now want to also include file2 in file1 , you have to imagine that file1 has been elevated to the root directory / , so the include from within file1 will only work, if you have defined the path relative to the root: include("folder1/folder2/file2.php") - EVEN if file1 is actualy located in folder1 .

Calling file1 directly will now fail, because php would search for folder1/folder1/folder2/file2.php - That's the reason why putting files into the "global" include path should be preferred over relative references. ( if and only if you are also calling subfolder'd files directly*)

Generally you want to use index.php for all requests - and then all subfolder'd files are relative from the root directory of your website, which allows you to omit the global include directory and working with relative paths in order to split up multiple projects on the same server.

(*AJAX will blow this principle, cause a php-file called by ajax will be executed in it's actual directory and not from the directory containing the file containing the ajax call!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM