How can one check to see if a remote file exists using PHP?

前端 未结 22 2878
死守一世寂寞
死守一世寂寞 2020-11-22 05:52

The best I could find, an if fclose fopen type thing, makes the page load really slowly.

Basically what I\'m trying to do is

22条回答
  •  孤城傲影
    2020-11-22 06:38

    This can be done by obtaining the HTTP Status code (404 = not found) which is possible with file_get_contentsDocs making use of context options. The following code takes redirects into account and will return the status code of the final destination (Demo):

    $url = 'http://example.com/';
    $code = FALSE;
    
    $options['http'] = array(
        'method' => "HEAD",
        'ignore_errors' => 1
    );
    
    $body = file_get_contents($url, NULL, stream_context_create($options));
    
    foreach($http_response_header as $header)
        sscanf($header, 'HTTP/%*d.%*d %d', $code);
    
    echo "Status code: $code";
    

    If you don't want to follow redirects, you can do it similar (Demo):

    $url = 'http://example.com/';
    $code = FALSE;
    
    $options['http'] = array(
        'method' => "HEAD",
        'ignore_errors' => 1,
        'max_redirects' => 0
    );
    
    $body = file_get_contents($url, NULL, stream_context_create($options));
    
    sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code);
    
    echo "Status code: $code";
    

    Some of the functions, options and variables in use are explained with more detail on a blog post I've written: HEAD first with PHP Streams.

提交回复
热议问题