페이지 수집할때 많이 사용하는 형태의 curl
사이트의 페이지를 소켓방식으로 수집할때 많이 사용하는 curl 클래스 입니다.
본인의 상황에 따라서 좀더 조건을 줘서 처리를 하면 되며 쿠키를 저장해서 다시 보내줘야 한 다면 이 부분에 대한 주석 처리 된것을 풀어서 테스트 해보면 됩니다.
중요한것은 HTTP 프로토콜에 대한 명확한 이해가 가장 중요합니다.
원리를 모르는 상태에서 사용을 하다보면 헛발질을 많이 할 수 밖에 없기 때문이죠~
코딩을 잘 한다는 것은 깔끔하게 재사용가능하게 하는 것도 중요하지만 더 중요한 것은 원리를 이해하고 문제를 해결 하는 것입니다.
// 변수 선언
$method = 'get';
$post_data = '';
$referer = '';
$userAgent = '';
// 변수들을 배열에 넣기
$aRequest = [
'http_url' => $http_url,
'method' => $method,
'post_data' => $post_data,
'referer' => $referer,
'userAgent' => $userAgent
];
$oNetUtil = new NetworkUtil();
/*
*/
class NetworkUtil
{
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0';
const FILE_COOKIE = './file_cookie.txt';
public function __construct($userAgent='', $cookFile='') {
if ( strlen($userAgent) > 12 ) $this->USER_AGENT = $userAgent;
if ( strlen($cookFile) > 2 ) $this->FILE_COOKIE = $cookFile;
}
function get_data( $aRequest=[] )
{
if ( is_array($aRequest) ) extract($aRequest);
$http_url = $requestArray['http_url'];
$method = $requestArray['method'];
$post_data = $requestArray['post_data'];
$referer = $requestArray['referer'];
$userAgent = $requestArray['userAgent'];
$USER_AGENT = $this->USER_AGENT;
if ( strlen($userAgent) > 12 ) $USER_AGENT = $userAgent;
$file_cookie = $this->FILE_COOKIE;
$timeOut = 5;
$aURL = parse_url($http_url);
$HTTP_HOST = $aURL['host'];
$resolveHost = $HTTP_HOST;
// print_r($aURL); exit;
$method = strtoupper($method);
if ( $method == 'GET' || $method == 'POST' || $method == 'HEAD' );
else {
return false;
}
$aHeader = array();
$aHeader[] = "User-Agent: " . $USER_AGENT;
$aHeader[] = "Host: " . $HTTP_HOST;
$aHeader[] = "Accept-Encoding: gzip, deflate, br";
$aHeader[] = "Accept-Language: ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7";
$aHeader[] = "Accept-Language: ko";
$aHeader[] = "Connection: keep-alive";
// $aHeader[] = "";
//multipart/form-data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $http_url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeOut);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER , $aHeader);
// curl_setopt($ch, CURL_HTTP_VERSION_1_1, 1);
// curl_setopt($ch, CURLOPT_USERAGENT, $USER_AGENT);
// curl_setopt($ch, CURLOPT_RESOLVE, ["$resolveHost:443:$serverIP"]);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $metohd);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if( $referer ) {
curl_setopt($ch, CURLOPT_REFERER, $referer);
}
if ( strlen($post_data) > 0 ) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// echo $http_url . PHP_EOL;
// echo 'post: ' . $post_data . PHP_EOL;
}
// curl_setopt($ch, CURLOPT_COOKIEFILE, $file_cookie); // 서버로 보내주는것
// curl_setopt($ch, CURLOPT_COOKIEJAR, $file_cookie); // 서버에서 받은것 저장하기
$response = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
curl_close($ch);
$header = '';
$body = '';
if ( $http_status == 200 ) {
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
$http_body = $body;
$encodeType = '';
if( stristr($header, 'Content-Encoding: gzip') ) {
$body = gzdecode($body);
$encodeType = 'gzip';
}
else if( stristr($header, 'Content-Encoding: br') ) {
$body = brotli_uncompress($body);
$encodeType = 'br';
}
}
$oRtn = (object)[];
$oRtn->response = $response;
$oRtn->http_status = $http_status;
$oRtn->header_size = $header_size;
$oRtn->http_body = $http_body;
$oRtn->header = $header;
$oRtn->body = $body;
$oRtn->encodeType = $encodeType;
return $oRtn;
}
function cutStringBetween($string, $start, $end) {
// 시작 문자열의 위치 찾기
$startPos = strpos($string, $start);
// 시작 문자열이 없다면 빈 문자열 반환
if ($startPos === false) return '';
// 끝 문자열의 위치 찾기
$endPos = strpos($string, $end, $startPos);
// 끝 문자열이 없다면 빈 문자열 반환
if ($endPos === false) return '';
// 시작 및 끝 문자열의 길이 계산
$startLen = strlen($start);
$endLen = strlen($end);
// 문자열 자르기
return substr($string, $startPos + $startLen, $endPos - $startPos - $startLen);
}
function createFullHtmlPage($content) {
return <<<HTML
<!DOCTYPE html>
<html lang='ko'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Document</title>
</head>
<body>
$content
</body>
</html>
HTML;
}
}