简体   繁体   中英

PHP include when a “root forward slash” precedes the included path like: “/folder/file.php”

For loading files like css or javascript of images, I have learned to add some extra safety and add an extra / in front of the folders, making sure that these files are loaded from a folder starting from the root path down wards:

eg /images/photo.jpg
eg /scripts/script.js eg /layout/css.css`

Now, when I do the same trick in PHP, the file doesnt seem to load then the forward slash is added!

<? include ("/folder/file.php"); ?>     // include this file

When I however remove that / in the front of the path, it all works, but then dreamweaver says it cannot find the file! When I add the / then dreamweaver CAN find the remote assets/file but when running the site the files doesnt include well.

PHP's file-oriented functions (include, require, fopen, opendir, etc...) all generally expect to be dealing with a filesystem path. That is, a path on the local server, without being mediated through a web server.

That's not to say you can't provide a full absolute URL to the functions, but in general, if you don't have something that looks like a url (protocol://host/path?query#fragment), it'll be interepreted as something in the local file system.

So when you stick a / in front of your include path, it's viewed as an absolute local path, starting at the top of the local file system.

Without a leading / , it's viewed as a relative path, and PHP will iterate through its include path to try and find the file based on include_path + file_to_include .

A path starting with / is usually interpreted as an absolute path (relative to the environment). So Dreamweaver might interpret the root (ie / ), as the project's root path, while a unix server (and as such php that runs on it) interprets the path as the root in the directory system. And on HTTP, it usually refers to the document root of the current domain.

The best solution would be to simply use relative paths, ie paths starting with . , like ../../folder/file.php .

If you want to include a file with what we think of the "local url path", the common idiom for that is:

 include("$_SERVER[DOCUMENT_ROOT]/folder/file.php");

(That's perfectly valid PHP3-style syntax. But nowadays "{$_SERVER['DOCUMENT_ROOT']}" is more commonly read. But makes no difference.)

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