Will file_get_contents fail gracefully?

后端 未结 2 1985
耶瑟儿~
耶瑟儿~ 2021-01-04 14:07

I need file_get_contents to be fault tolerant, as in, if the $url fed to it returns a 404, to tell me about it before it echos out a warning. C

2条回答
  •  鱼传尺愫
    2021-01-04 14:32

    You could do an additional (HEAD) request to find out first, for instance

    $response = get_headers($url);
    if($response[1] === 'HTTP/1.1 200 OK') {
        $content = file_get_contents($url);
    }
    

    Or you can tell file_get_contents to ignore any errors and force-fetch the result of the $url by modifying the stream context:

    echo file_get_contents(
        'http://www.example.com/foo.html',
        FALSE,
        stream_context_create(array('http'=>array('ignore_errors' => TRUE)))
    )
    

提交回复
热议问题