php-ccurl下载文件并获取标题


php curl download file and get header

我想通过php中的curl下载文件,并获取文件的头。

// handler
$h = fopen($filePath , 'w');
// curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_FILE, $h);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'getAllHeaders'));
$a = curl_exec($ch); // return false;
curl_close($ch);
fclose($h);
public function getAllHeaders($ch, $header)
{
    // check for 200 ok
    if (preg_match('/HTTP['/'.0-9's't]+200['s't]+OK/i', $header)) {
        // header 200 found
        $this->header200 = true;
    }
    // grab all headers keys and values
    preg_match('/^(?P<key>[a-z0-9'-]+)':(?P<value>.*)$/i', $header, $matches);
    // cycle
    foreach ($matches as $key => $value) {
        if (!is_numeric($key)) {
            $this->headers[strtolower(trim($key))] = trim($value);
        }
    }
    // headers
    return $this->headers;
}

但是我不能得到标题和文件不被下载。我该怎么解决。

以下约束适用于您不满足的getAllHeaders():

使用此回调函数时,必须写入标头数据。返回写入的字节数。

来源:php.net

怎么样:

public function getAllHeaders($ch, $header)
{
    // store header here (how about storing in a field that is an array of headers?)
    return strlen($header);
}