如何使用PHP curl_setopt检查服务器错误类型


How to check server error type with PHP curl_setopt?

我正试图使用PHP curl_setopt作为下面的函数从另一个网站查询数据,但我不知道当我的合作伙伴服务器收到以下描述的任何错误时该数据是否有效。

    [Server Error 5xx]
    500="Internal Server Error"
    501="Not Implemented"
    502="Bad Gateway"
    503="Service Unavailable"
    504="Gateway Timeout"
    505="HTTP Version Not Supported"

   public function getNumber() {
        $url = "http://website/PalmHallServer_kl/!queryLuckNumberRecordByPeriods.action";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: Json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $contents = curl_exec($ch);
        $res = false;
        if ($contents) {
            $res = TRUE;
        } else {
            $res = FALSE;
        }
        echo json_encode(array("res" => $res, 'data' => $contents));
    }

首先告诉curl您希望看到返回的头

curl_setopt($ch, CURLOPT_HEADER, true); 

然后你可以使用获得响应代码

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

要查看响应标头中包含的所有信息,可以执行

print_r(curl_getinfo($ch));