PHP

 

 

1.  url 이미지 가져와서 저장하기

 

<?php
ini_set("allow_url_fopen", 1);


$url ="https://images.websiteplanet.com/wp-content/uploads/2018/03/Overview-14-1.png";
/* url 파일 가져오기  */
$img_contents=file_get_contents($url);


/* 가져온 파일 저장하기  절대 경로 사용 , 저장할  디렉토리는 707 권한 디렉토리  */
file_put_contents('/var/www/html/gatherhere/data/a.png' ,$img_contents);



?>

 

 

2. GET 방식

$data = array(
    'test' => 'test'
);

$url = "https://www.naver.com" . "?" , http_build_query($data, '', );

$ch = curl_init();                                 //curl 초기화
curl_setopt($ch, CURLOPT_URL, $url);               //URL 지정하기
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    //요청 결과를 문자열로 반환 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);      //connection timeout 10초 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);   //원격 서버의 인증서가 유효한지 검사 안함
 
$response = curl_exec($ch);
curl_close($ch);
 
return $response;

 

3.post 방식

$data = array(
    'test' => 'test'
);
 
$url = "https://www.naver.com";
 
$ch = curl_init();                                 //curl 초기화
curl_setopt($ch, CURLOPT_URL, $url);               //URL 지정하기
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    //요청 결과를 문자열로 반환 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);      //connection timeout 10초 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);   //원격 서버의 인증서가 유효한지 검사 안함
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);       //POST data
curl_setopt($ch, CURLOPT_POST, true);              //true시 post 전송 
 
$response = curl_exec($ch);
curl_close($ch);
 
return $response;

 

결과및 오류 확인

response = curl_exec ($ch);
 
var_dump($response);        //결과 값 출력
print_r(curl_getinfo($ch)); //모든 정보 출력
echo curl_errno($ch);       //에러 정보 출력
echo curl_error($ch);       //에러 정보 출력
cs

 

 

 

4. curl로 사이트 작동 여부 확인

<!--

    CURL -> 웹 사이트와 간단한 통신(입출력)을 가능하게 해줌
            이것을 응용한 활용법
    1. 특정 웹사이트의 정상 작동 여부 체크하기
    2. 특정 웹사이트의 소스 가져오기 (현재 시간의 날씨 가져오기, 현재 시간의 추가 가져오기, 심지어 쇼핑몰의 상품 가져오기)

    사전 조건 : php-curl 리눅스 서버에 설치되어 있어야 함...

-->
<?php
    ini_set("allow_url_fopen", 1);
    header('Content-Type: text/html; charset=UTF-8');

    
    ///$userAgent  참조 : https://kakao-tam.tistory.com/110
    
    $username='test';
    $password='1234';
    $location='https://www.daum.net/';
    
    
    $userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36";    
    $ch = curl_init(); //curl 초기화
    curl_setopt($ch,CURLOPT_URL,$location); //URL 지정하기
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);  //요청 결과를 문자열로 반환
    curl_setopt($ch,CURLOPT_USERPWD,"$username:$password"); //로그인이 필요한 경우   
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 10초내에 서버에서 응답이 없을경우 강제 해제 됨
    curl_setopt($ch, CURLOPT_TIMEOUT, 400);  //- 400초 내에 다운로드가 완료되지 않을경우 강제 해제된다.
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
    $webcontents = curl_exec($ch);  //실행
   
    $response_code="";
    if(!curl_errno($ch)){
        //정상실행
        $response_code=curl_getinfo($ch, CURLINFO_HTTP_CODE);
    }else{
        $response_code="ERR";
    }
    
    
    $res_code_header=substr($response_code, 0, 1);
    
    if($res_code_header!="2" || !$webcontents || strpos($webcontents, 'https://t1.daumcdn.net/kas/static/ba.min.js')===false){
        //사이트 접속 실패
        echo "사이트 접속 실패";
    }else{
       //사이트 접속 성공
       echo "사이트 접속 성공";       
    }
        
    curl_close($ch);
    
?>

 

 

5.특정 데이터만 추출   findStringBetweenAndB  -   추출한 부분 앞뒤로  코드 입력

<?php

    error_reporting( E_ALL );
    ini_set( "display_errors", 1 );

    ini_set("allow_url_fopen", 1);
    header('Content-Type: text/html; charset=UTF-8');

    
    //https://www.google.com/search?q=%EC%84%9C%EC%9A%B8+%EB%82%A0%EC%94%A8&client=avast-a-1&ei=Gj_KYu2VGc2M-Qa0vJiwCQ&ved=0ahUKEwjtioPLqO34AhVNRt4KHTQeBpYQ4dUDCA4&uact=5&oq=%EC%84%9C%EC%9A%B8+%EB%82%A0%EC%94%A8&gs_lcp=Cgdnd3Mtd2l6EAMyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgAEIAEOgcIABBHELADSgQIQRgASgQIRhgAUNoBWNoBYKAEaAFwAXgAgAF-iAF-kgEDMC4xmAEAoAEByAEKwAEB&sclient=gws-wiz

  
    //userAgent 접속자 userAgent 정보 사이트:   http://www.useragentstring.com/ 
     //$userAgent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0";
    //$userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 Config/96.2.3881.82";
    
    $userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 Unique/98.7.5806.7";
    //$userAgent="Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0";
    
    function getContents($webpage){ //웹페이지 내용 가져오기
    
        $ch=curl_init($webpage); //curl 초기화
        
        curl_setopt($ch, CURLOPT_FAILONERROR, true); //TRUE로 설정 시 HTTP 헤더로 보내는 LOCATION헤더의 내용을 따른다.
        curl_setopt($ch, CURLOPT_HEADER, 0); // TRUE로 설정 시 헤더의 내용을 출력        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // TRUE로 설정 시 curl_exec()의 반환 값을 문자열로 반환
        //curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); // 30초내에 서버에서 응답이 없을경우 강제 해제 됨
        curl_setopt($ch, CURLOPT_TIMEOUT, 400);  //400초 내에 다운로드가 완료되지 않을경우 강제 해제된다.
                  
        $webcontents=curl_exec($ch);        
        curl_close($ch);
        
        return $webcontents;        
    }
    
    
    
    function findStringBetweenAndB($dest, $A, $B) {
        $firstFindIdx=strpos($dest, $A);
        $firstFindIdx=$firstFindIdx +strlen($A);
        $secondFindIdx=strpos($dest, $B, $firstFindIdx);
        
        $findSearString=trim(substr($dest, $firstFindIdx, $secondFindIdx-$firstFindIdx));
        return $findSearString;
    }
    
    
    $getCrawling =getContents("https://www.fmkorea.com/");
    
    
    $dataExtract1 =findStringBetweenAndB($getCrawling, '<li class="li  li_best2_pop1 li_best2_hotdeal0">', '</li>');
    
    $dataExtract1=findStringBetweenAndB($dataExtract1, 'document_srl=', '"');
    
    //https://www.fmkorea.com/index.php?mid=humor&sort_index=pop&order_type=desc&document_srl=4833825191&listStyle=webzine
    //4833825191
    
    echo $data1
    
       
  
    
?>

 

 

 

 

이미지 링크 추출

아래와 같은 본문이 있을시 여기서 이미지나 링크만 추출 하여 보자.

 

$str = "<a name='top'></a>
<img src='http://xxxx.com/a.gif' border='0' alt=''>
<img src='http://xxxx.com/b.png' border='0' alt=''>
<a href='http://xxxx.com/gogo.html?no=2' target='_blank'><img src='http://xxxx.com/gif.php?no=5368753' border='0' alt=''></a>";

 

 

 

여러가지 방법이 있겠지만
1번째.

// a 링크만 추출하기
preg_match_all("|<a[^>]+>(.*)</a>|U",stripslashes($str),$out1, PREG_PATTERN_ORDER); 
preg_match_all("|<a[^>]+>.*</a>|U",stripslashes($str),$out2, PREG_PATTERN_ORDER); 
preg_match_all("^<a.*<\/a>^U", stripslashes($str), $out3);

// http 로 시작하는 것만추출
preg_match_all("((http)://[a-z0-9-]+.[][a-zA-Z0-9:&#@=_~%;?/.+-]+)",stripslashes($str),$out4, PREG_PATTERN_ORDER); 

// 이미지만 추출
preg_match_all("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i", stripslashes($str), $out5);

print_r ($out1);
print_r ($out2);
print_r ($out3);
print_r ($out4);
print_r ($out5);

 

 

 

결과 값

Array
(
    [0] => Array
        (
            [0] => <a name='top'></a>
            [1] => <a href='http://xxxx.com/gogo.html?no=2' target='_blank'><img src='http://xxxx.com/gif.php?no=5368753' border='0' alt=''></a>
        )

    [1] => Array
        (
            [0] => 
            [1] => <img src='http://xxxx.com/gif.php?no=5368753' border='0' alt=''>
        )

)
Array
(
    [0] => Array
        (
            [0] => <a name='top'></a>
            [1] => <a href='http://xxxx.com/gogo.html?no=2' target='_blank'><img src='http://xxxx.com/gif.php?no=5368753' border='0' alt=''></a>
        )

)
Array
(
    [0] => Array
        (
            [0] => <a name='top'></a>
            [1] => <a href='http://xxxx.com/gogo.html?no=2' target='_blank'><img src='http://xxxx.com/gif.php?no=5368753' border='0' alt=''></a>
        )

)
Array
(
    [0] => Array
        (
            [0] => http://xxxx.com/a.gif
            [1] => http://xxxx.com/b.png
            [2] => http://xxxx.com/gogo.html?no=2
            [3] => http://xxxx.com/gif.php?no=5368753
        )

    [1] => Array
        (
            [0] => http
            [1] => http
            [2] => http
            [3] => http
        )

)
Array
(
    [0] => Array
        (
            [0] => <img src='http://xxxx.com/a.gif' border='0' alt=''>
            [1] => <img src='http://xxxx.com/b.png' border='0' alt=''>
            [2] => <img src='http://xxxx.com/gif.php?no=5368753' border='0' alt=''>
        )

    [1] => Array
        (
            [0] => http://xxxx.com/a.gif
            [1] => http://xxxx.com/b.png
            [2] => http://xxxx.com/gif.php?no=5368753
        )

)

 

 

 


2번째.
처음 나온는 이미지 추출(jpg,gif,png)

$photo = getImg($str);
print_r ($photo);
function getImg($content) {
	$img = "";
	preg_match("<img [^<>]*>", $content, $imgTag);
	
	if($imgTag[0]){ 
		if( stristr($imgTag[0], "http://") ) {
			preg_match("/http:\/\/.*\.(jp[e]?g|gif|png)/Ui", $imgTag[0], $imgName);
			$img = $imgName[0];
		} else {
			preg_match("/.*\.(jp[e]?g|gif|png)/Ui", $imgTag[0], $imgName);
			$img = $imgName[0];
		}
	}
	/*
	if($imgTag) {
		if( stristr($imgTag[2], "http://") ) {
			preg_match("/http:\/\/.*\.(jp[e]?g|gif|png)/Ui", $imgTag[2], $imgName);
			$img = $imgName[0];
		} else {
			preg_match("/.*\.(jp[e]?g|gif|png)/Ui", $imgTag[2], $imgName);
			$img = $imgName[0];
		}
	}
	*/
	return $img;
}

 

 

결과 값
http://xxxx.com/a.gif

3. 세번째.
특정 웹페이지를 읽어 그 페이지에 있는 이미지 추출

 

<?php
$startPage  = "1";      // 시작 페이지
$endPage    = "2";     // 마지막 페이지

for($i=$startPage; $endPage+1 > $i;$i++)
{
	$data           = "";   // 초기화
	$datafile       = "http://xxxx.com/photo.html?page=$i"; // 리스트 페이지
	$fp             = @fopen($datafile, "r");
	while (!feof ($fp))
	{
		$data .= fgets($fp);
	}
	fclose($fp);

	preg_match_all("/<img[^>]*src=[\"']?([^>\"']+)[\"']?[^>]*>/i",$data, $matches);

	foreach($matches as $key => $value)
	{
		foreach($value as $key_2 => $value_2)
		{
			//$value_2 =  ereg_replace(".thumb","",$value_2);
			//$value_2 =  ereg_replace("img src=","",$value_2);
			echo $value_2."<br />";
		}
		break;
	}
}
?> 

 

이미지추출 :출처

https://yesyo.com/mintbbs/bbs/board.php?bo_table=php&wr_id=111&page=4

 

 

 

 

 

 

 

 

 

 

 

 

 

출처: PHP CURL 사용법 (GET, POST)

 

 

 

about author

PHRASE

Level 60  라이트

남편이 분할때 맞서지 마라. -부부이십훈-

댓글 ( 6)

댓글 남기기

작성