PHP,CURL:函数获取响应代码并返回变量

时间:2014-07-22 13:14:47

标签: php curl

我有以下功能:

function file_get_contents_curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, random_user_agent());
    curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-type: text/plain');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

我需要在此函数中包含一些逻辑,如果URL的响应代码是例如404,则返回null $data变量。我举了一个我正在寻找的例子:

function file_get_contents_curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, random_user_agent());
    curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-type: text/plain');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    $data = curl_exec($ch);

    if (empty($data) or (HTTP response code is 404)) {
        // some kind of an error happened
        die(curl_error($ch));
        curl_close($ch); 
        $data = null;
        return $data;
    } else {
        // everything  is ok
        return $data;

    }
}

2 个答案:

答案 0 :(得分:1)

curl_getinfo($ch)调用

之前使用curl_close()

答案 1 :(得分:1)

function file_get_contents_curl($url) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_USERAGENT, random_user_agent());
            curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-type: text/plain');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            $data = curl_exec($ch);

            if (empty($data) OR (curl_getinfo($ch, CURLINFO_HTTP_CODE == 404))) {
                    // some kind of an error happened
                    die(curl_error($ch));
                    curl_close($ch); 
                    $data = null;
                    return $data;
                } else {
                    // everything  is ok
                    return $data;

                }

        }