PHP解析HTML img标签src路径无法正常工作
i have some code in HTML that gets parsed by PHP, and i want the image tags to be relative, because the code needs to work on multiple servers.
I have index.php
in the directory as the folder icons
, and in icons
, there is an image called logo.png
. The code is index.php
is like this:
echo '<img src="icons/logo.png">';
But does not work. However, if i change it to this kind of path (http://mydomain...
) it does work.
On one of the servers, both index.php
and icons
are in a subdomain directory, and on the other server they are in the root. In both cases the relative path does not work.
How can i fix this?
Thanks.
EDIT: In my HTML inspector, i can see that the URL to the image is correctly being parsed.
All right, i found the problem! There is no need for complicated solutions, as the problem is this:
icons/
When going to http://mydomain.com/icons
, i find myself in some apache folder containing apache icons.
So i guess it takes me to the very root of the domain, and into some icons folder.
When changing icons/
to for example images/
, it works perfectly!
If your files are in the root directory public_html/ then you dont need to do anything just access it using /icons/logo.png
. However if you have subdirectory that you want it to be the root directory for itself then do the following:
You need to set up Virtual Host
for apache if you have access to httpd-vhosts
and link it to the subdirectory to be the root directory for all files/folder under it.
Then you would just use "/icons/logo.png"
If you dont have access to VHosts
or apache files and you are hosting on shared hosting then you need to read up on .htaccess to catch requests and check if img exists in root if not check if it exists in subdirectory.
Another way is to just have a global variable of site URL like:
define('SITE_URL', 'http://mysite.com/');
and link to your image like: <?=SITE_URL?>icons/logo.png
For each server you would then just modify SITE_URL
you need to know what is your path in server or in wamp server c:/wamp/www/ so u can put this
echo '<'img src="/icons/biglogo.png >
else you need to change your path or put full path
echo '<'img src="/mysite/img/icons/biglogo.png" >';