开发者

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

开发者 https://www.devze.com 2023-02-17 18:10 出处:网络
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 fold开发者_如何学运维ers, making sure that these files are loaded from a

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 fold开发者_如何学运维ers, making sure that these files are loaded from a folder starting from the root path down wards:

e.g. /images/photo.jpg

e.g. /scripts/script.js e.g./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 (i.e. /), 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, i.e. 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.)

0

精彩评论

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

关注公众号