【问题标题】:Check if tweet status exists?检查推文状态是否存在?
【发布时间】:2014-11-08 02:47:56
【问题描述】:

我需要一种方法来检查推文是否存在。我有类似 https://twitter.com/darknille/status/355651101657280512 这样的推文链接。我最好想要一种快速的检查方法(无需检索页面正文,只需 HEAD 请求),所以我尝试了类似的方法

function if_curl_exists($url)
{   

    $resURL = curl_init(); 
    curl_setopt($resURL, CURLOPT_URL, $url); 
    curl_setopt($resURL, CURLOPT_BINARYTRANSFER, 1); 
    curl_setopt($resURL, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback'); 
    curl_setopt($resURL, CURLOPT_FAILONERROR, 1); 
    $x = curl_exec ($resURL); 
    //var_dump($x);
    echo $intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE); 
    curl_close ($resURL); 
    if ($intReturnCode != 200 && $intReturnCode != 302 && $intReturnCode != 304) { 
        return false;
    }
    else return true;

}   

或者像这样

function if_curl_exists_1($url) 
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_NOBODY, true);//head request
    $result = curl_exec($curl);

    $ret = false;

    if ($result !== false) {
        //if request was ok, check response code
        echo $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);  

        if ($statusCode == 200) {
            $ret = true;   
        }
    }

    curl_close($curl);
    return $ret;
}

但是这两个都返回 null 和 curl_exec(),没有什么可以检查 http 状态代码。

另一种方法是使用twitter api,例如GET statuses/show/:idhttps://dev.twitter.com/docs/api/1.1/get/statuses/show/%3Aid,但是如果tweet不存在则没有特殊的返回值,如此处所述https://dev.twitter.com/discussions/8802

我需要建议最快的检查方法是什么,我正在使用 php。

【问题讨论】:

  • 如果没有推文匹配id,twitter API 调用会返回什么?
  • 文档对此只字未提,您可以在上面的链接中阅读。

标签: php http twitter


【解决方案1】:

您可能必须设置退货转帐标志

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

如果代码返回 30x 状态,您可能还需要添加关注位置标志

curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

【讨论】:

  • $url = 'https://twitter.com/darknille/status/355651101657280512';//false even tweet exists //$url = 'http://google.com';//works 200 //$url = 'http://php.net';//works 200 if( if_curl_postoji1($url) ) echo "yes"; else echo "no";
  • 所以它适用于所有网站,如 google、php.net 但不适用于 twitter,就像它们的服务器设置为不响应 HEAD 请求或一些额外的 http 参数。我想使用 https:// 的事实不会影响事情。
  • 只是说我添加了你的 2 个卷曲选项。
【解决方案2】:

您可以使用@get_header。它将返回一个数组,其中第一项具有响应代码:

$response = @get_headers($url);
print_r($response[0]);
if($response[0]=='HTTP/1.0 404 Not Found'){
    echo 'Not Found';
}else{
    echo 'Found';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 2018-10-07
    • 2021-12-09
    • 1970-01-01
    • 2022-06-20
    相关资源
    最近更新 更多