N
N
Nikita Gusakov2013-01-23 23:28:54
PHP
Nikita Gusakov, 2013-01-23 23:28:54

Setting a 404 when accessing a file?

When requesting a non-existent file, the request reaches index.php and something needs to be done about it. How correct is the following:

private function process_request()
  {
    $request = strtolower($_SERVER['REQUEST_URI']);
    $query_string = strstr($request, '?');
    if( !empty($query_string) ){
      $request = str_replace($query_string, '', $request);
    }
    $ext = strstr($request, '.');
    $good_ext = array('.php', '.html', '.htm');
    if($ext===false){
      return $request;
    }elseif(in_array($ext, $good_ext)){
      $right_url = str_replace($ext, '', $request);
      $this->redirect($right_url);
    }else{
      $this->set_404();
    }
  }
  private function set_404()
  {
    if( !headers_sent() ){
      header('HTTP/1.1 404 Not Found');
      header('Status: 404 Not Found');
      exit();
    }else{
      Ylog('Headers have been sent!');
    }
  }
  private function redirect($page)
  {
    if( !headers_sent() ){
      header('HTTP/1.1 303 See Other');
      header('Location: '.$page);
      exit();
    }else{
      Ylog('Headers have been sent!');
    }
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WEBIVAN, 2013-01-24
@hell0w0rd

Judging by the code, everything that has an extension other than '.php', '.html', '.htm' should return 404.
I don't understand why it should be brought to php at all, why not cut it off at the .htaccess level?

A
akral, 2013-01-24
@akral

header('HTTP/1.1 404 Not Found');
header('Status: 404 Not Found');
The function headerhas a parameter for status , no need to invent your own solutions:
header(' ', true, 404);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question