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


Using PHP curl how to get http code thrown by target url

我使用PHP curl,我的目标url给出200或500取决于请求参数。但无论如何,它抛出500或200我得到200使用curl_getinfo($ch, CURLINFO_HTTP_CODE)。下面是代码

/**
 * 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代码?

试试这个:

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 or 302)

你可以试着在你的终端上旋转url来检查它的状态码吗? curl -I www.site.com

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

您应该使用curl_setopt($c, CURLOPT_HEADER, true);在输出中包含标题。

http://www.php.net/manual/en/function.curl-setopt.php

然后用var_dump($file)看是否真的是200…

使用下面的代码检查状态应该可以工作

$infoArray = curl_getinfo($ch);
$httpStatus = $infoArray['http_code'];
if($httpStatus == "200"){
    // do stuff here
}
curl_setopt($c, CURLOPT_HEADER, true); // you need this to get the headers
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

使用guzzle以同样的方式与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();