问题
I am developing a website on php, I have installed wamp on my personal computer and my website files are in the www folder of wamp.
now considering www as my root folder i have a template folder in the root folder and header.inc.html file in the template folder. when I try to include this header.inc.html file in any other php file using an absolute path include('/template/header.inc.html');
it gives me error "Failed to open stream: No such file or directory", but when I create a simple html link using the same absolute path it perfectly and opens the file. below is my test code
<?php
echo '<a href="/template/header.inc.html">headerfile</a>';
include('/template/header.inc.html');
?>
if I give the full path for example C:/wamp/www/template/header.inc.html
to the include function it works fine.
I am confused that this problem is occurring on my wamp server only and it would work perfectly on any webhost server, or maybe the same problem will exist on a webhost
I would appreciate any help that would clarify my confusion, Thanks.
回答1:
Absolute paths on the server start from the server's hard disk (C:\
).
Absolute paths on the client start from the root of the website (http://example.com/
).
回答2:
You can make use of __DIR__ to make some file on disk relative to the php-file on disk itself:
include(__DIR__.'/template/header.inc.html');
This should solve your issue.
The difference is not that easy to explain because both types of paths - even related - are two pair of shoes. I suggest you start with a very basic HTML website tutorial that explains how to link on your website and where files are located and how that is related to the webserver configuration.
回答3:
HTML pages live in the client's browser that know nothing about your server's folder structure, and they're relative to the domain name eg. http://example.com/.
PHP programs run on the server side and they deal with the server folders. You shouldn't hardcode full paths in your php programs, because it will cause problems whenever you'll move them between the development server and the live host (just to name an example). Therefore in php files you should either use relative paths to your file, or use the __DIR__
magic constant that gets substituted with the directory where the php file is.
1.) First approach: include('template/header.inc.html');
2.) Second approach: include(__DIR__ .'/template/header.inc.html');
In your case (working on a development machine) both the client and the server is the same box, that might be confusing you.
来源:https://stackoverflow.com/questions/10931355/what-is-the-difference-of-absolute-path-in-html-and-php