Home > Backend Development > PHP Tutorial > php curl_init curl 消息头和消息体

php curl_init curl 消息头和消息体

WBOY
Release: 2016-06-06 20:06:31
Original
1131 people have browsed it

给定一个 远程图片地址(http地址) 然后用curl 请求 通过检查返回的 消息头 判断远程图片是否存在
但是这里有个严重的效率问题就是消息体
消息体把图片也给返回了 有设置可以 只产生消息体 让消息体为空或者或不产生消息体吗

<code>//检查远程文件
function checkRemoteFile($file_name, $path) {
    $path = $path . "/" . $file_name;
    $ch = curl_init();
    $timeout = 30;  //在尝试连接时等待的秒数。设置为0,则无限等待。
    curl_setopt($ch, CURLOPT_URL, $path);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $contents = curl_exec($ch);
//echo $contents;

    if (preg_match("/404/", $contents)) {
        echo '0';
        return false;
    } elseif(preg_match("/200/", $contents)) {
        echo $contents;
        return true;
    }
} </code>
Copy after login
Copy after login

回复内容:

给定一个 远程图片地址(http地址) 然后用curl 请求 通过检查返回的 消息头 判断远程图片是否存在
但是这里有个严重的效率问题就是消息体
消息体把图片也给返回了 有设置可以 只产生消息体 让消息体为空或者或不产生消息体吗

<code>//检查远程文件
function checkRemoteFile($file_name, $path) {
    $path = $path . "/" . $file_name;
    $ch = curl_init();
    $timeout = 30;  //在尝试连接时等待的秒数。设置为0,则无限等待。
    curl_setopt($ch, CURLOPT_URL, $path);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $contents = curl_exec($ch);
//echo $contents;

    if (preg_match("/404/", $contents)) {
        echo '0';
        return false;
    } elseif(preg_match("/200/", $contents)) {
        echo $contents;
        return true;
    }
} </code>
Copy after login
Copy after login

不用curl不就行了,fopen好像也可以打开远程文件吧。

<code>$hd = fopen($remoteUrl, 'r');
if ($hd === false) die('404')
else fclose($hd);</code>
Copy after login

哦,看到你的评论了,用 curl_setopt($ch, CURLOPT_NOBODY, true); 看看

curl不可以吗?你试试这个呢!

<code>public function checkRemoteHttpFileExists($url) {
    $curl = curl_init($url);
    // 不取回数据
    curl_setopt($curl, CURLOPT_NOBODY, true);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
    // @curl_setopt($curl, CUROPT_RETURNTRANSFER,1);
    // 发送请求
    $result = @curl_exec($curl);
    $found = false;
    // 如果请求没有发送失败
    if ($result !== false) {
        // 再检查http响应码是否为200
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($statusCode == 200) {
            $found = true;
        }
    }
    curl_close($curl);
    return $found;
}</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template