api통신이나 특정 파일,url을 읽을때 file_get_contents()나 curl을 사용한다.
네이버 블로그에서 특정 문자가 있는지 확인하는 로직을 짜야해서 작성중이였는데
file_get_contents()
<?
$search_keyword = iconv("euc-kr","utf-8",urlDecode($search_keyword)); //찾아야되는 배너
$url = $_POST["url"]; //네이버 블로그 주소
$data = file_get_contents($url);
preg_match("/<iframe.*src=\"(.*)\".*><\/iframe>/isU",$data,$match);
$blog = "https://blog.naver.com";
$blog_pc_url = $blog.$match[1];
$data2 = file_get_contents($blog_pc_url);
preg_match("/<div id=\"postListBody\">(.*?)<div class=\"post_footer_contents\">.*/s", $data2, $match2);
$search_data = preg_replace("/\s+/","",$match2[1]);
$search_data = strtolower($search_data);
if(strpos($search_data,$search_keyword)) {
echo "success";
} else {
echo "fail";
}
?>
먼저 iframe에 src의 속성값을 찾는 코드를 작성했는데
file_get_contents()함수에서 https로 접속하려고 할때 에러가 난다.
그래서 curl을 사용해서 데이터를 비교하려고 했다.
<?
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$search_keyword = iconv("euc-kr","utf-8",urlDecode($search_keyword)); //찾아야되는 배너
$url = $_POST["url"]; //네이버 블로그 주소
$data = file_get_contents_curl($url);
preg_match("/<iframe.*src=\"(.*)\".*><\/iframe>/isU",$data,$match);
$blog = "https://blog.naver.com";
$blog_pc_url = $blog.$match[1];
$data2 = file_get_contents_curl($blog_pc_url);
preg_match("/<div id=\"postListBody\">(.*?)<div class=\"post_footer_contents\">.*/s", $data2, $match2);
$search_data = preg_replace("/\s+/","",$match2[1]);
$search_data = strtolower($search_data);
if(strpos($search_data,$search_keyword)) {
echo "success";
} else {
echo "fail";
}
?>
별건 없고 함수하나 추가해서 비교하는 부분을 바꾸어 주었다.
근데 자꾸 fail이 나온다..내가 블로그 내용 하나 써서 테스트 해봐야겠다.
curl을 더 선호한다고 하는데
여기서 file_get_contents()와 curl의 차이는
file_get_contents() : 함수, curl : 라이브러리 이다.
또 몇개 찾아봤는데
1. file_get_contents()를 사용할 경우, 로그인이 필요하지 않은 페이지의 URL만 확인 가능하며,
읽어올 대상 페이지의 서버 혹은 소스에 allow_url_fopen 옵션이 활성화되어 있어야 한다.
2. curl_setopt를 통해 사용할 수 있는 설정들이 다양하다. 간단한 기능이라면 file_get_contents()를 쓰겠지만 다영한 기능을 사용한다면 curl을 사용한다고 한다.
3. 속도가 curl이 좀 더 빠르다고 하는데 내가 하는 프로젝트들은 크게 이슈가 없어서 잘 모르겠음.
두개 다 써보면서 공부해보는게 제일 좋을듯 합니다!
찾아보니까 네이버 블로그가 내가 보이는데로 개발자모드에 텍스트가 찍혀있는게 아니였음!!
방식에는 문제없습니다. 잘 활용하시길 바랍니다~!
'PHP' 카테고리의 다른 글
php.ini 수정없이 php설정값 바꾸기 (0) | 2024.09.20 |
---|---|
PHP 출력문 비교 echo, print, print_r, var_dumb (0) | 2024.07.31 |
PHP fsockopen() 함수로 API 연동하기 (0) | 2024.07.08 |
봇 자동등록 방지 로직 (0) | 2024.05.31 |
PHP 캡챠 연동 (0) | 2024.05.30 |