Access apache errordocument directive from PHP

后端 未结 3 745
遇见更好的自我
遇见更好的自我 2021-01-06 05:10

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

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 06:05

    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.

提交回复
热议问题