使用PHP curl如何获取目标url抛出的http代码

使用PHP curl如何获取目标url抛出的http代码,php,file,curl,Php,File,Curl,我使用的是PHP curl,我的目标url根据请求参数给出200或500。 但不管它抛出500或200,我都会使用curl\u getinfo($ch,CURLINFO\u HTTP\u代码)得到200。这是密码 /** * use for get any file form a remote uri * * @param String $url * @return String */ public function getFileUsingCurl($url) { //set

我使用的是PHP curl,我的目标url根据请求参数给出200或500。 但不管它抛出500或200,我都会使用curl\u getinfo($ch,CURLINFO\u HTTP\u代码)得到200。这是密码

/**
 * use for get any file form a remote uri
 *
 * @param String $url
 * @return String
 */
public function getFileUsingCurl($url)
{
    //set all option
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

    $file = curl_exec($ch);

    if (200 == curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
        curl_close($ch);
        return $file;
    } else {
        curl_close($ch);
        return false;
    }
}

如何从目标url中获取正确的HTTP代码?

能否尝试在终端上卷曲url,以检查其状态代码:
curl_setopt($c, CURLOPT_HEADER, true); // you need this to get the headers
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl-I www.site.com


(我知道这是一个问题而不是答案,但我还没有足够的stackoverflow rep来评论哈哈,所以当我有更多信息时,我会将其编辑为答案)

你应该使用
curl\u setopt($c,CURLOPT\u HEADER,true)以在输出中包含标题

然后使用
var\u dump($file)
查看它是否真的是200

使用下面的代码检查状态应该有效

$infoArray = curl_getinfo($ch);
$httpStatus = $infoArray['http_code'];
if($httpStatus == "200"){
    // do stuff here
}
用于以理智的方式与CURL交互。然后,您的脚本会变成:

<?php
use Guzzle\Http\Client;

// Create a client and provide a base URL
$client = new Client('http://www.example.com');

$response = $client->get('/');
$code = $response->getStatusCode();
试试这个:

public function getFileUsingCurl($url)
{
    //set all option
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    $file = curl_exec($ch);
    $curlinfo = curl_getinfo($ch);
    curl_close($ch);
    $httpcode = $curlinfo['http_code'];
    if($httpcode == "200"){
    return $file;
    }else{
    return false;
    }

}
注:

确保您没有被重定向(代码
301或302

代码中有同一行,请下次阅读问题。