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.
Update:
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.
Update 2:
Didn't see the post from @Janoz below - he correctly mentions REDIRECT_URL
.
ErrorDocument
directive, or ?) – DaciaErrorDocument 404 /404/
- and the 404 page has the line included above. – Ploss<?php var_dump($_SERVER); ?>
from an instance when you get this behaviour? I'm confused as to why none of these approaches work. I experimented a bit with Apache and couldn't produce a situation where none of them got the result you want. – Medius