programing

머리글만 컬을 통해 php로 검색

easyjava 2023. 9. 26. 22:37
반응형

머리글만 컬을 통해 php로 검색

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

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

(2) 처음 질문에 대한 대답은 YES입니다. 원격 파일의 마지막 수정 날짜 또는 If-Modified-Since 헤더를 로컬에 저장된 데이터의 시간 날짜와 비교하기 위해서만 가져오려고 합니다. 변경된 경우 로컬에 저장할 수 있습니다.하지만 내 스크립트는 그 정보를 가져올 수 없는 것 같습니다.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)요청하지 않았더라도 주석이 없고 헤더 데이터가 표시되며 다음과 같습니다.

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'가 반환됩니다.

그래서, 내가 뭘 잘못하고 있는 거지?

$헤더를 에 전달합니다.curl_getinfo().그럴 것 같네요.$curl(컬 핸들).당신은 단지 그것을 얻을 수 있습니다.filetime지나감으로써CURLINFO_FILETIME에 대한 두 번째 매개 변수로서curl_getinfo(). (흔히)filetime사용할 수 없습니다. 이 경우 -1)로 보고됩니다.

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

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 헤더만 반환하기 때문에 서버의 부하가 더 가벼워질 것입니다(결국은 a에 응답합니다).HEAD요청).얼마나 가벼운지는 크게 다를 것입니다.

이거 왜 컬을 써요?다음을 위한 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: 형식 = 1을 추가할 수도 있습니다.

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

그러면 다음이 반환됩니다.

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
)

여기 더 읽어보기(PHP).NET)

(1) 예. HEAD 요청은 (이 경우 발행하는 것처럼) 표준 GET 요청과 같은 헤더 및 내용이 아닌 HTTP 헤더만 반환하기 때문에 서버에서 훨씬 가볍습니다.

(2) CURLOPT_RETURNTRANCE 옵션을 다음과 같이 설정해야 합니다.true전화 드리기 전에curl_exec()인쇄된 내용이 아닌 내용물을 반환하도록 합니다.

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

그것은 또한 당신의 수업을 올바르게 할 수 있게 해 줄 것입니다.

기본 스트림 컨텍스트를 설정할 수 있습니다.

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

그러면 다음을 사용합니다.

$headers = get_headers($url,1);

get_headers가 로그인 프롬프트나 쿠키와 같은 트리거 인증 루틴과 같은 단계를 건너뛸 때 get_headers가 cURL보다 더 효율적인 것 같습니다.

다음은 CURLOPT_HEADER를 사용하여 출력 문자열을 맵으로 구문 분석하는 구현 방법입니다.

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;
};

샘플 사용량:

$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'
)

추가할 필요가 있습니다.

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

머리글을 인쇄하는 대신 반환해야 합니다.

헤더만 반환하는 것이 서버에 더 가벼운지 여부는 실행 중인 스크립트에 따라 다르지만 일반적으로 그렇습니다.

당신도 date time 대신 file time을 원한다고 생각합니다.

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

반응형