这是检查是否可以通过文件获取内容获得URL的好方法


Is this a good way to check if a URL can be obtained via file get contents

if($url  = file_get_contents("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=".$user)){}
else die("Invalid User");

这是运行此脚本的好方法吗?

我不确定你的意思,但如果你问你的file_get_contents电话是否正确,那么我必须说是的,因为,正如这里所说:

On failure, file_get_contents() will return FALSE.

是的,您的代码是正确的,并且会用页面的内容填充$url,或者如果请求的 URL 导致错误代码,则返回 false。 但请注意,值为 0 或空字符串的页面也将解释为 false 。 若要避免这种情况,请使用强匹配!==

if(false !== ($url  = file_get_contents("https://api.twitter.com/1/statuses/user_timeline.json?screen_name=".$user)))

如果您只想检查 URL 是否有效,请使用 get_headers 仅获取带有 HTTP HEAD 请求的响应标头:

stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD'
        )
    )
);
$headers = get_headers('http://example.com'. 1);
// get the response code
$parts = explode(' ', $headers[0]);
$code = $parts[1];
if($code == 200) ... // success
if($code == 404) ... // failure

这将使您免于通过网络传输整个页面。

您需要

检查=== false(注意三个=),因为空内容或内容0也会通过测试。

最好通过 $http_response_header 变量检查 HTTP 状态代码 - 它应该在 200 范围内 (200-299)。