Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access apache errordocument directive from PHP

Tags:

php

apache

I would like to make a php script output like a real 404 page (as set in the Apache ErrorDocument directive) if certain conditions are not met. I'm not sure how I can / if it's possible to access this value from PHP..

if(!@$_SESSION['value']){
 header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
 echo $default_page['404'];
 exit();
}
echo 'Welcome to a secret place.';

I understand the ErrorDocument value can be overwritten, but I'm particularly interested in the 'default' value hardcoded by Apache. If it's possible to know the value which is overwitten (eg by a .htaccess file), then that's a bonus :)

http://httpd.apache.org/docs/2.0/mod/core.html#ErrorDocument

edit: to be clear, I'd like to send the content the default 404 page (or 403, etc) of Apache from PHP. If I only use header on its own then nothing is output to the client/user (at least in FF/Chrome, IE has its own built in pages which are shown).

like image 268
aland Avatar asked Jan 20 '23 14:01

aland


1 Answers

The recommended way to set the response code from PHP is as @mario suggested:

Header('Status: 404 Not Found');

If you want to get the body of the page the server would ordinarily provide for a 404, and don't care about the URL getting rewritten in the user's browser, you could use something like:

$uri_404 = 'http://'
    . $_SERVER['HTTP_HOST']
    . ($_SERVER['HTTP_PORT'] ? (':' . $_SERVER['HTTP_PORT']) : '')
    . '/was-nowhere-to-be-seen';
Header("Location: $uri");

(When you're directly frobbing the Location header field, you need to supply a full URI.) The result of this is that the user's browser's will end up pointing to that bogus location, which may not be what you want. (Probably isn't.) So then you could actuall collect the contents of the page yourself and combine the two, in effect:

Header('Status: 404 Not Found');

$uri_404 = 'http://'
    . $_SERVER['HTTP_HOST']
    . ($_SERVER['HTTP_PORT'] ? (':' . $_SERVER['HTTP_PORT']) : '')
    . '/was-nowhere-to-be-seen';
$curl_req = curl_init($uri);
curl_setopt($curl_req, CURLOPT_MUTE, true);
$body = curl_exec($curl_req);
print $body;
curl_close($curl_req);

That should fetch the contents of the 404 page the server reports for the bogus URI, and you can then copy it and use it yourself. This should properly handle any ErrorDocument 404 handler output.

like image 103
RoUS Avatar answered Jan 30 '23 13:01

RoUS