Access apache errordocument directive from PHP

后端 未结 3 787
遇见更好的自我
遇见更好的自我 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 05:42

    There is no default method for that. But you can always cheat:

    header("Status: 404 Not There");
    
    // no worky
    #readfile("http://$_SERVER[HTTP_HOST]/non-existant-url");
    
    // doesn't work either (Apache detects the fraud)
    #virtual("/non-existant-url");
    
    // otherwise a HTTP class, this one works but is seldomly available
    $request = new HttpRequest("http://localhost/error", 1);
    $answer = $request->send();
    print $answer->getBody();
    

    This triggers a subrequest. Since it's on the local server, I would disregard any bigger performance penalties. But it might be worth to investiage using the Apache/mod_php virtual() function.

    Notably this method depends on knowing a certain location of a 404 resource. If there is already url rewriting in place, then another trick is necessary in your .htaccess:

    RewriteRule  ^non-existant-url$  error  [E=404,L]
    

    This forces the resource to generate the expected result, thus making the default errordocument available.

提交回复
热议问题