2010-04-05 4 views
-1

컬 (Curl) 클래스가 있습니다.이미지를 저장하는 php-curl 스크립트 --- 실제로는 captcha 이미지

$url = 'http://www.google.com' 
$fields = array('q'=>'search term'); //maybe some other arguments. but let's keep it simple. 
$curl = new Curl(); 
$page = $curl->post($url,$fields); 

$ 페이지가 일부 이미지는 기본적으로 그들을로드하지 않습니다 컬을 이십 기가 바이트해야합니다 :

의 난이 코드를 가지고 가정하자. 컬을 사용하지 않고 특정 이미지를 저장할 수있는 방법을 알아야합니다. 일단 $ page = $ curl-> post (..)를 사용하면 그 파일을 얻기 위해 다른 $ curl-> post (_image_location_)를 사용하지 않고 이미지를 저장할 수 있어야합니다.

왜 필요한지는 양식에서 captcha 이미지를 저장하는 것입니다. 양식에 액세스하여로드되는 특정 이미지를 가져와야합니다. 이미지의 URL에 액세스하려고하면 다른 보안 문자 이미지가 표시됩니다.

답변

1

설명하는 것은 불가능합니다. 웹 페이지의 모든 외부 리소스 (예 : 이미지, 스크립트, 스타일 시트 등 HTML 컨텐트 자체에 포함되지 않은 모든 것)에 대해서는 별도의 요청을 검색해야합니다. 이것은 모든 브라우저가 작동하는 방식입니다.

많은 captcha는 세션별로 작동합니다. HTML 페이지에 대한 초기 요청은 응답 헤더의 일부로 다시 전송되는 세션 쿠키를 생성 할 가능성이 큽니다. 이 쿠키는 이미지가 요청 될 때 예상됩니다. 이미지에 대한 일반 컬 요청 만하면 해당 쿠키를 보내지 않으므로 다른 이미지를 얻습니다.

페이지를 분석하고 어떤 종류의 세션 관리가 진행되고 있는지 정확하게 판단하고, Curl 요청을 적절하게 수정해야합니다. 그러나 제가 언급했듯이, 쿠키 기반이 될 것으로 생각됩니다. 시작하기 위해 CURLOPT_COOKIEJAR curl_setopt() 매개 변수를 확인하는 것이 좋습니다. pretty straightforward examples에 대해서도 Google을 검색 할 수 있습니다.

1

이것은 전체 수업입니다. 질문이 있으면 더 잘 설명 할 수 있습니다.

<?php 

/** 
* Description of class-curl 
* 
* @author NEO 
*/ 
class cURL { 

    public $headers; 
    public $user_agent; 
    public $compression; 
    public $cookie_file; 
    public $proxy; 
    public $process; 
    public $url; 
    public $hash; 
    public $content; 

    public function __construct($url) { 
     $this->url = $url; 
     $this->process = curl_init($this->url); 
     $cookiename = uniqid('cookie_') . '.txt'; 
     $this->cURL($cookies = TRUE, $cookiename); 
    } 

    public function cURL($cookies = TRUE, $cookie = 'cookie.txt', $compression = 'gzip', $proxy = '') { 
     $this->headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg'; 
     $this->headers[] = 'Connection: Keep-Alive'; 
     $this->headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8'; 
     $this->user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)'; 
     $this->compression = $compression; 
     $this->proxy = $proxy; 
     $this->cookies = $cookies; 
     if ($this->cookies == TRUE) 
      $this->cookie($cookie); 
    } 

    public function cookie($cookie_file) { 
     if (file_exists($cookie_file)) { 
      $this->cookie_file = $cookie_file; 
     } else { 
      fopen($cookie_file, 'w') or $this->error('The cookie file could not be opened. Make sure this directory has the correct permissions'); 
      $this->cookie_file = $cookie_file; 
      @fclose($this->cookie_file); 
     } 
    } 

    //Capturar todo el codigo fuente de la web solicitada 
    public function get() { 
     curl_setopt($this->process, CURLOPT_HTTPHEADER, $this->headers); 
     curl_setopt($this->process, CURLOPT_HEADER, 0); 
     curl_setopt($this->process, CURLOPT_USERAGENT, $this->user_agent); 
     if ($this->cookies == TRUE) { 
      curl_setopt($this->process, CURLOPT_COOKIEFILE, $this->cookie_file); 
      curl_setopt($this->process, CURLOPT_COOKIEJAR, $this->cookie_file); 
     } 
     curl_setopt($this->process, CURLOPT_ENCODING, $this->compression); 
     curl_setopt($this->process, CURLOPT_TIMEOUT, 90); 
     if ($this->proxy) 
      curl_setopt($this->process, CURLOPT_PROXY, $this->proxy); 
     curl_setopt($this->process, CURLOPT_RETURNTRANSFER, 1); 
     //curl_setopt($this->process, CURLOPT_FOLLOWLOCATION, 1); 
     $return = curl_exec($this->process); 
     //curl_close($this->process); 
     return $return; 
    } 

    public function post($data) { 
     curl_setopt($this->process, CURLOPT_HTTPHEADER, $this->headers); 
     curl_setopt($this->process, CURLOPT_HEADER, 1); 
     curl_setopt($this->process, CURLOPT_USERAGENT, $this->user_agent); 
     if ($this->cookies == TRUE) 
      curl_setopt($this->process, CURLOPT_COOKIEFILE, $this->cookie_file); 
     if ($this->cookies == TRUE) 
      curl_setopt($this->process, CURLOPT_COOKIEJAR, $this->cookie_file); 
     curl_setopt($this->process, CURLOPT_ENCODING, $this->compression); 
     curl_setopt($this->process, CURLOPT_TIMEOUT, 30); 
     if ($this->proxy) 
      curl_setopt($this->process, CURLOPT_PROXY, $this->proxy); 
     curl_setopt($this->process, CURLOPT_POSTFIELDS, $data); 
     curl_setopt($this->process, CURLOPT_RETURNTRANSFER, 1); 
     //curl_setopt($this->process, CURLOPT_FOLLOWLOCATION, 1); 
     curl_setopt($this->process, CURLOPT_POST, 1); 
     $return = curl_exec($this->process); 
     //curl_close($this->process); 
     return $return; 
    } 

    public function error($error) { 
     echo "<center><div style='width:500px;border: 3px solid #FFEEFF; padding: 3px; background-color: #FFDDFF;font-family: verdana; font-size: 10px'><b>cURL Error</b><br>$error</div></center>"; 
     die; 
    } 

    public function grab_image() { 
     //obener una imagen desde la url especificada, se puede mejorar para que 
     //se le de una url y me mande todas las imagenes que encuentre 
     curl_setopt($this->process, CURLOPT_HEADER, 0); 
     curl_setopt($this->process, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($this->process, CURLOPT_BINARYTRANSFER, 1); 
     $raw = curl_exec($this->process); 
     $name = explode("/", $this->url); 
     $name = array_pop($name); 
     if (file_exists($name)) { 
      unlink($name); 
     } 
     $fp = fopen($name, 'x'); 
     fwrite($fp, $raw); 
     fclose($fp); 
     return $name; 
     //return $raw; 
    } 

    public function cURLclose() { 
     unlink($this->cookie_file); 
     curl_close($this->process); 
     unset($this); 
    } 

    public function saveCaptcha($source) { 
     preg_match('/ipt" src="(h[^"]+)/', $source, $result); 
     $captcha = $this->get($result[1]); 
      $ch = curl_init(); 
      curl_setopt($ch, CURLOPT_URL, $result[1]); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
      $captcha = curl_exec($ch); 
      curl_close($ch); 
     $hash = explode("challenge :", $captcha); 
     $hash1 = explode("'", $hash[1]); 
     $cont = $hash1[1]; 
     $img = 'http://www.google.com/recaptcha/api/image?c=' . $cont; 
      $ch = curl_init($img); 
      curl_setopt($ch, CURLOPT_HEADER, 0); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
      curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); 
      $rawdata=curl_exec($ch); 
      curl_close($ch); 
      $name = uniqid('captcha_'); 
      $fp = fopen("$name.jpg",'w'); 
      fwrite($fp, $rawdata); 
      fclose($fp); 
     //ese cont hay que guardarlo en BD y generar otro para la imagen 
     //$picturename = $this->grab_image1($img); 
     $picturename = $name.".jpg"; 
     $picture = array('name' => $picturename, 'hash' => $cont); 
     return $picture; 
    } 
} 

?> 

그래서 당신은이 호출이 클래스 컬 할 수 있도록 :

include 'class-Curl.php'; 

//Pedir un nuevo captcha con una nueva cookie 
$url = 'http://lok.myvnc.com/insertar-anuncio.html'; 
//Crear el objeto Curl 
$captcha = new cURL($url); 
//Capturar el codigo funte de la pagina 
$source = $captcha->get(); 
//Parsear el codigo javascripts del captcha y bajarla al disco 
$captchaimg = $captcha->saveCaptcha($source); 
//Guardar en Base de Datos las variables ID, picturename, picturehash, cookie 


var_dump($captchaimg); 
?> 
<IMG src="<?php echo $_SERVER['DOCUMENT_ROOT']."/sms/".$captchaimg['name'] ?>"> 
+0

당신은 좀 더이 코드를 설명 할 수 있습니까? 들어오는 것이 무엇이이 기능에서 빠져 나옵니까? – angabriel

+0

나는 변덕스러운 변화를 이해하기 바란다. DB에 쿠키, captcha 및 de captcha 해시를 저장합니다. 그래서 나중에 게시물에 세 가지를 게시합니다 ($ 데이터). – n3omaster

관련 문제