컬을 사용하여 PHP에서 HTTP 코드 가져오기

사이트가 업/다운 상태이거나 다른 사이트로 리다이렉트되는 경우 CURL을 사용하여 사이트의 상태를 가져옵니다.최대한 합리화하고 싶은데 잘 안 돼요.

<?php $ch = curl_init($url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_TIMEOUT,10); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
return $httpcode; ?> 

이걸 함수로 포장해 놨어요정상적으로 동작하지만, 페이지 전체를 다운로드하기 때문에 퍼포먼스가 최상은 아닙니다.삭제하면 문제가 생깁니다.$output = curl_exec($ch);그것은 되돌아온다0항상요.

퍼포먼스를 향상시키는 방법을 아는 사람 있나요?



질문에 대한 답변



먼저 URL이 실제로 유효한지(문자열, 비어 있지 않은, 올바른 구문)를 확인합니다.이것이 서버측을 빠르게 체크할 수 있습니다.예를 들어, 먼저 이 작업을 수행하면 많은 시간을 절약할 수 있습니다.

if(!$url
!is_string($url)
! preg_match('/^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$/i', $url)){
return false; } 

헤더만 가져오고 본문 내용은 가져오지 마십시오.

@curl_setopt($ch, CURLOPT_HEADER
, true);
// we want headers @curl_setopt($ch, CURLOPT_NOBODY
, true);
// we don't need body 

URL 상태 http 코드 취득에 대한 자세한 내용은 제가 작성한 다른 게시물을 참조하십시오(다음 리다이렉트에도 도움이 됩니다).


전체:

$url = 'http://www.example.com'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, true);
// we want headers curl_setopt($ch, CURLOPT_NOBODY, true);
// we don't need body curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT,10); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
echo 'HTTP code: ' . $httpcode; 



// must set $url first.... $http = curl_init($url); // do your curl thing here $result = curl_exec($http); $http_status = curl_getinfo($http, CURLINFO_HTTP_CODE); curl_close($http); echo $http_status; 



$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_TIMEOUT, 20); $rt = curl_exec($ch); $info = curl_getinfo($ch); echo $info["http_code"]; 



PHP의 “get_headers” 함수를 사용해 보십시오.

다음과 같은 것들이 있습니다.

<?php
$url = 'http://www.example.com';
print_r(get_headers($url));
print_r(get_headers($url, 1)); ?> 



curl_getinfo– 특정 전송에 대한 정보를 가져옵니다.

curl_getinfo 체크

<?php // Create a curl handle $ch = curl_init('http://www.yahoo.com/');
// Execute curl_exec($ch);
// Check if any error occurred if(!curl_errno($ch)) {
$info = curl_getinfo($ch);
echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url']; }
// Close handle curl_close($ch);