I have a custom 404 page which works fine except for the message I want to display on this page.
I would like it to say the url of the page which can't be found but instead it displays the url of the 404 page.
Here's what I have...
You were looking for <?php echo $_SERVER['REQUEST_URI'] ?>.
The htaccess file contains the line: ErrorDocument 404 /404/
php file, you can create one as a simple HTML file with a . php extension and then upload it to your site's theme directory. Any time a 404 error occurs, WordPress will serve up this 404. php page to the user.
You need to use $_SERVER['HTTP_REFERER']
instead - that will be the address they requested first.
This only works in the exact case described in the question - where the browser has actually been redirected to the 404 page. In that situation, $_SERVER['REQUEST_URI']
contains the URI of the 404 page rather than the originally requested page as described.
Using Apache's ErrorDocument 404 /handle404.php
in the site config or .htaccess
would mean that $_SERVER['REQUEST_URI']
would actually work, but a more robust solution is the option in the update below.
Apparently $_SERVER['REDIRECT_URL']
might be a better bet however, having searched around a bit.
For both cases, as mentioned by the commenters below, bear in mind that any headers are just as prone to malicious content as $_POST
, $_GET
and others, so process them before outputting anything.
Didn't see the post from @Janoz below - he correctly mentions REDIRECT_URL
.
From the perspective of the php page, that really is the request uri. Showing the error page is done by the webserver. Apache for example will add some extra server variables. REDIRECT_URL is probably the one you are looking for.
I did not write this function but it is what I use to do the same thing:
function selfURL() {
$s = empty($_SERVER["HTTPS"]) ? ''
: ($_SERVER["HTTPS"] == "on") ? "s"
: "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? ""
: (":".$_SERVER["SERVER_PORT"]);
return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
function strleft($s1, $s2) {
return substr($s1, 0, strpos($s1, $s2));
}
then to print it:
<?php print(selfURL()); ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With