Skip to content
Advertisement

Checking the existing of a file by url inside native php router

I would like to know how could I check the existing of a file by a given url inside native php router (index.php) here is what I’ve tried :

function does_file_exists($url){
  try{
    $headers = get_headers($url);
    if(is_array($headers))
    {
      return (stripos($headers[0],"200 OK") || stripos($headers[0],"304 OK")) ? true : false;
    }
    else
    {

    }
  }
  catch(Exception $e)
  {

  }
  return false;
}

Inside (index.php)

$url = "http://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(does_file_exists($url))
{
  $ext = pathinfo($url, PATHINFO_EXTENSION);
  if(in_array($ext, $unauthorized_file_type))
  {
    Redirect('404.php');
    exit();
  }
  else
  {
    header("Location: $url");
    exit();
  }
}

The page takes long time to output a message ‘Warning: get_headers(http://[website]/test): failed to open stream: HTTP request failed’ may be due to reccursion. How can I solve that without .htaccess file?

Advertisement

Answer

You can do this by using the file_exists command in PHP.See the following example:

if (file_exists(__DIR__ . "/views/dashboard.php")) {


          include __DIR__ . “/views/dashboard.php”;

}

__DIR__ here refers to the directory of the currently-executing script, so you will want to make all paths relevant to that.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement