티스토리 뷰
반응형
PHP에서 웹 크롤링 시 프록시 및 User-Agent 설정을 사용하면 크롤링 대상 서버에 보다 자연스럽게 요청을 보낼 수 있으며, 차단 회피에도 도움이 됩니다.
✅ file_get_contents() 대신 cURL 사용 이유
file_get_contents()는 간단하지만 프록시 설정, User-Agent 지정, 타임아웃 제어, 에러 핸들링 등이 부족합니다. 그래서 크롤링할 때는 보통 cURL을 사용합니다.
🧩 병렬 웹 크롤러 + 프록시 + User-Agent 적용 예제 (parallel + curl)
🔧 전체 코드 예시 (parallel_crawler_with_proxy.php)
<?php
use parallel\Runtime;
/**
* URL에서 HTML 제목을 추출하는 함수
*/
function fetchWithCurl($url, $proxy = null, $userAgent = null) {
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 15,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
]);
// 프록시 설정 (있을 경우)
if ($proxy) {
curl_setopt($ch, CURLOPT_PROXY, $proxy);
}
// User-Agent 설정
if ($userAgent) {
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
}
$html = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($html === false) {
return "[$url] => Error: $err";
}
// 타이틀 추출
if (preg_match('/<title>(.*?)<\/title>/i', $html, $matches)) {
return "[$url] => " . trim($matches[1]);
} else {
return "[$url] => (No title found)";
}
}
// 크롤링할 URL 목록
$urls = [
'https://www.php.net',
'https://www.wikipedia.org',
'https://www.github.com',
'https://www.stackoverflow.com',
'https://www.openai.com',
];
// 프록시 (없으면 null)
$proxy = null; // 예시: "127.0.0.1:8080" or "http://proxyhost:port"
// User-Agent
$userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/114.0.0.0 Safari/537.36";
// 병렬 실행
$runtimes = [];
$futures = [];
foreach ($urls as $url) {
$runtime = new Runtime();
$runtimes[] = $runtime;
$futures[] = $runtime->run(function($url, $proxy, $ua) {
return fetchWithCurl($url, $proxy, $ua);
}, [$url, $proxy, $userAgent]);
}
// 결과 출력
foreach ($futures as $future) {
echo $future->value() . PHP_EOL;
}
🧪 실행
php parallel_crawler_with_proxy.php
🔁 프록시 회전 및 User-Agent 무작위화 (옵션)
$proxies = ['123.123.123.123:8080', '222.222.222.222:3128'];
$userAgents = [
"Mozilla/5.0 ... Chrome/114",
"Mozilla/5.0 ... Firefox/112",
"Mozilla/5.0 ... Safari/605.1.15"
];
$proxy = $proxies[array_rand($proxies)];
$userAgent = $userAgents[array_rand($userAgents)];
✅ 요약
기능 | 구현 방식 |
병렬 실행 | parallel\Runtime |
User-Agent | curl_setopt(..., CURLOPT_USERAGENT, ...) |
프록시 사용 | curl_setopt(..., CURLOPT_PROXY, ...) |
에러 처리 | curl_error()으로 확인 |
반응형
'배움 > PHP' 카테고리의 다른 글
Http 파사드(Illuminate\Support\Facades\Http) (0) | 2025.07.02 |
---|---|
Laravel Helper Class 사용법 (0) | 2025.07.01 |
parallel 웹 크롤러 (0) | 2025.06.24 |
PHP Multi Thread 구현 (0) | 2025.06.24 |
Laravel 12 Swagger (0) | 2025.06.05 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- researcher
- PYTHON
- privatechannel
- wsl
- strict_types
- eloquent
- swagger
- php
- laravel 테스트
- ubuntu
- uniqid
- facades
- array_combine
- reflectionclass
- mysql
- 비동기
- laravel 12
- 설정
- laravel 11
- 명령어
- jp:a
- #collect
- createfromformat
- curl_multi_init
- flask
- ob_get_contents
- call_user_func
- WSL2
- Laravel
- 설치
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
글 보관함