Hi,

I'm using a simple .htaccess file to use a custom 404 error page:

ErrorDocument 404 /errors/404.php

Inside this 'errors' folder, there is the 404.php file, and an image, which I want to include in the 404 page.

Anyway, when I request a non-existing page from the root folder, everything works fine. When I request something like adfag/sdgsdg/sdg/sdg the image at the error page is not showing. I'm using the relative URL in the <img> tag (so, the filename itself, because the 404 page and the image are both in the same directory) but it seems like the 404 page is requested from another location (a few levels down into the non-existing directories).

I assume there should be a small PHP script that takes the requested URL, and generates the relative path to the image in order to let the error page work properly. Any ideas?

Thanks in advance.

(I know that the absolute path starting with http:// works, but I'd rather use the relative path)

If you use:

$_SERVER['DOCUMENT_ROOT']

it will return the complete path to the root of the domain you are at (ie. /hsphere/home/user/domain.com). So the link to your image should be something like:

<?php
// Create a constant for the document root.
define("DOC_ROOT", $_SERVER['DOCUMENT_ROOT']);
?>
<img src="<?= DOC_ROOT; ?>/imagefolder/imagename.jpg" width="300px" height="150px" alt="404 image" />

That will always be the path to the image no matter where your script calls it from.

Hi,

That path would not work if used in the scr attribute for an image tag (or any tag that gets included client side).

Anyway, it's working fine with

<img src="http://<?php echo $_SERVER['HTTP_HOST']; ?>/path/image.png">

and I guess there aren't so much advantages with working with relative filenames anyway.

Thanks for your time though! :)

Of course you are right Lapixx. Shows how important it is to think before you post. I myself have never tied to use the example I offered (because it doesn't work!)

I do use the solution you offered yourself all the time.

I see how one could write a function to calculate the relative path, but I don't really see the point when using

$_SERVER['HTTP_HOST']

works perfectly.

Glad you didn't follow my advice ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.