PHP predefined variables and URLs
November 14, 2007 5:10 AM   Subscribe

I'm developing a custom 404 page using .htaccess to redirect to the 404.html. I'm trying to use PHP (via an include in the 404.html) to show the referring page (using $_SERVER['HTTP_REFERER']). This works fine. I'd also like to return the bad URL that originates the 404. Is this possible using PHP?

I've reviewed the documentation at php.net regarding predefined variables but I'm not seeing what I want. If it's not possible via PHP is it possible using any other technology? If so, any suggestions? I do not have access to the server configuration BTW.

Thanks.
posted by lyam to Technology (6 answers total)
 
On most servers you can use $_SERVER['REQUEST_URI'] to get the current page's URL relative to root, or use something like this to build the full URL. Whatever you use, make sure it's HTML-encoded before being displayed to avoid any potential XSS nastiness.
(I assume you're not actually doing an HTTP redirect, just rewriting the URL to point to 404.html internally? Otherwise the current page would be 404.html and the referer would be the page originating the error)
posted by malevolent at 5:57 AM on November 14, 2007


Response by poster: Well that explains why REQUEST_URI wasn't giving me the results I was after. Thanks for the heads up. I guess I need to be using mod_rewrite to to internally redirect?
posted by lyam at 6:08 AM on November 14, 2007


If you define the 404 in htaccess with something like
ErrorDocument 404 /_errors/404.php
then the URL won't change and REQUEST_URI will be intact within 404.php
posted by malevolent at 8:16 AM on November 14, 2007


Response by poster: I've attempted exactly that. What happens is that when I use relative paths, I get the path name output to the screen. When I use an absolute path it works, however the URL does change to the 404.htm.
posted by lyam at 8:53 AM on November 14, 2007


Best answer: On my servers (local OS X MAMP and remote Linux), if I use something like
ErrorDocument 404 _errors/404.php
then yes, it just outputs the path, but if I add the slash at the start to specify a path relative to root then it works fine. As you've found, specifying a full URL results in a redirect.
posted by malevolent at 10:07 AM on November 14, 2007


Response by poster: Wow, I swear I tried that as well, but I must've been mistaken. All is well now. Thanks!
posted by lyam at 10:18 AM on November 14, 2007


« Older What do you do whan "save early and save often"...   |   Annoying dust-up in my basement Newer »
This thread is closed to new comments.