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

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

4

3 回答 3

2

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

On failure, file_get_contents() will return FALSE.
于 2012-05-25T13:00:20.017 回答
1

是的,您的代码是正确的,并且将填充$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

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

于 2012-05-25T13:00:52.997 回答
0

您需要检查=== false(注意三个=),因为空内容或内容0也会导致测试失败。

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

于 2012-05-25T13:06:27.893 回答