Programing

curl을 통해 PHP에서 헤더 만 검색

lottogame 2020. 12. 8. 07:37
반응형

curl을 통해 PHP에서 헤더 만 검색


사실 두 가지 질문이 있습니다.

(1) php와 curl을 사용하는 전체 페이지 검색과 달리 헤더 만 검색하면 원격 서버에서 사용되는 처리 능력 이나 대역폭이 감소 합니까?

(2) 내가 생각하고 틀릴 수도 있기 때문에 첫 번째 질문에 대한 대답은 YES 입니다. 로컬에 저장된 데이터이므로 변경된 경우 로컬에 저장할 수 있습니다. 그러나 내 스크립트는 해당 정보를 가져올 수없는 것 같습니다 NULL.

class last_change {

 public last_change;

 function set_last_change() {
  $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "http://url/file.xml");
    curl_setopt($curl, CURLOPT_HEADER, true);
    curl_setopt($curl, CURLOPT_FILETIME, true);
    curl_setopt($curl, CURLOPT_NOBODY, true);
  // $header = curl_exec($curl);
  $this -> last_change = curl_getinfo($header);
  curl_close($curl);
 }

 function get_last_change() {
  return $this -> last_change['datetime']; // I have tested with Last-Modified & If-Modified-Since to no avail
 }

}

경우에 $header = curl_exec($curl)uncomented이며, 헤더 데이터는 다음과 같이 내가 그것을 요구하고있다하지 않은 경우에도 표시됩니다 :

HTTP/1.1 200 OK
Date: Fri, 04 Sep 2009 12:15:51 GMT
Server: Apache/2.2.8 (Linux/SUSE)
Last-Modified: Thu, 03 Sep 2009 12:46:54 GMT
ETag: "198054-118c-472abc735ab80"
Accept-Ranges: bytes
Content-Length: 4492
Content-Type: text/xml

이를 바탕으로 'Last-Modified'가 반환됩니다.

그래서 내가 뭘 잘못하고 있니?


$ header를에 전달합니다 curl_getinfo(). $curl(컬 핸들) 이어야합니다 . 에 두 번째 매개 변수로 filetime전달하여을 가져올 수 있습니다 . (종종 사용할 수없는 경우 -1로보고됩니다).CURLINFO_FILETIMEcurl_getinfo()filetime

하지만 당신의 수업은 유용 할 수있는 많은 정보를 버리는 낭비적인 것 같습니다. 다른 방법은 다음과 같습니다.

class URIInfo 
{
    public $info;
    public $header;
    private $url;

    public function __construct($url)
    {
        $this->url = $url;
        $this->setData();
    }

    public function setData() 
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $this->url);
        curl_setopt($curl, CURLOPT_FILETIME, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        $this->header = curl_exec($curl);
        $this->info = curl_getinfo($curl);
        curl_close($curl);
    }

    public function getFiletime() 
    {
        return $this->info['filetime'];
    }

    // Other functions can be added to retrieve other information.
}

$uri_info = new URIInfo('http://www.codinghorror.com/blog/');
$filetime = $uri_info->getFiletime();
if ($filetime != -1) {
    echo date('Y-m-d H:i:s', $filetime);
} else {
    echo 'filetime not available';
}

예, HTTP 헤더 만 반환 (결국 HEAD요청에 응답)하므로 서버에서로드가 더 가벼워집니다 . 얼마나 가벼울지는 크게 다릅니다.


왜 CURL을 사용합니까? 이를위한 PHP 기능이 있습니다.

$headers=get_headers("http://www.amazingjokes.com/img/2014/530c9613d29bd_CountvonCount.jpg");
print_r($headers);

다음을 반환합니다.

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Tue, 11 Mar 2014 22:44:38 GMT
    [2] => Server: Apache
    [3] => Last-Modified: Tue, 25 Feb 2014 14:08:40 GMT
    [4] => ETag: "54e35e8-8873-4f33ba00673f4"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 34931
    [7] => Connection: close
    [8] => Content-Type: image/jpeg
)

이 후 콘텐츠 유형을 쉽게 얻을 수 있습니다.

get_headers에 format = 1을 추가 할 수도 있습니다.

$headers=get_headers("http://www.amazingjokes.com/img/2014/530c9613d29bd_CountvonCount.jpg",1);
    print_r($headers);

This will return the following:

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Tue, 11 Mar 2014 22:44:38 GMT
    [Server] => Apache
    [Last-Modified] => Tue, 25 Feb 2014 14:08:40 GMT
    [ETag] => "54e35e8-8873-4f33ba00673f4"
    [Accept-Ranges] => bytes
    [Content-Length] => 34931
    [Connection] => close
    [Content-Type] => image/jpeg
)

More reading here (PHP.NET)


(1) Yes. A HEAD request (as you're issuing in this case) is far lighter on the server because it only returns the HTTP headers, as opposed to the headers and content like a standard GET request.

(2) You need to set the CURLOPT_RETURNTRANSFER option to true before you call curl_exec() to have the content returned, as opposed to printed:

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

That should also make your class work correctly.


Here is my implementation using CURLOPT_HEADER, then parsing the output string into a map:

function http_headers($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);

    $headers = curl_exec($ch);

    curl_close($ch);

    $data = [];
    $headers = explode(PHP_EOL, $headers);
    foreach ($headers as $row) {
        $parts = explode(':', $row);
        if (count($parts) === 2) {
            $data[trim($parts[0])] = trim($parts[1]);
        }
    }

    return $data;
};

Sample usage:

$headers = http_headers('https://i.ytimg.com/vi_webp/g-dKXOlsf98/hqdefault.webp');
print_r($headers);

Array
(
    ['Content-Type'] => 'image/webp'
    ['ETag'] => '1453807629'
    ['X-Content-Type-Options'] => 'nosniff'
    ['Server'] => 'sffe'
    ['Content-Length'] => 32958
    ['X-XSS-Protection'] => '1; mode=block'
    ['Age'] => 11
    ['Cache-Control'] => 'public, max-age=7200'
)

You need to add

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

to return the header instead of printing it.

Whether returning only the headers is lighter on the server depends on the script that's running, but usually it will be.

I think you also want "filetime" instead of "datetime".


You can set the default stream context:

stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD'
        )
    )
);

Then use:

$headers = get_headers($url,1);

get_headers seems to be more efficient than cURL once get_headers skip steps like trigger authentication routines such as log in prompts or cookies.

참고URL : https://stackoverflow.com/questions/1378915/header-only-retrieval-in-php-via-curl

반응형