Foros del Web » Programando para Internet » PHP »

Clase para utilizar Curl

Estas en el tema de Clase para utilizar Curl en el foro de PHP en Foros del Web. En mi último proyecto estoy utilizando la librería de php Curl. Así que he creado una clase sencilla para utilizar fácilmente esta librería. Código PHP: ...
  #1 (permalink)  
Antiguo 19/05/2014, 12:49
 
Fecha de Ingreso: octubre-2012
Mensajes: 135
Antigüedad: 11 años, 6 meses
Puntos: 8
Clase para utilizar Curl

En mi último proyecto estoy utilizando la librería de php Curl. Así que he creado una clase sencilla para utilizar fácilmente esta librería.

Código PHP:
class conectar{
    public 
$html

    public function 
__construct($url=""
    {
        if (
$url != ""){
            
            
$this->url=$url
            
$this->ch curl_init();  
                
        }else{
            echo 
'Error: url = ""';
            exit;
        }
    }
    
        public function 
tiempo($max
    {
        if(isset(
$max)){
          
            
curl_setopt($this->chCURLOPT_CONNECTTIMEOUT$max);
        }else{
            echo 
'Error: tiempo maximo = ""';
            exit;
    
        }
    }
     
    
    public function 
obtener_html() 
    {
      

        
curl_setopt($this->chCURLOPT_RETURNTRANSFERtrue); 
        
curl_setopt($this->chCURLOPT_URL$this->url); 
        
$this->html curl_exec($this->ch);  
        
curl_close($this->ch);

        return 
$this->html;
    
    
  }
     
      public function 
anadir_get($array
    {
        if(
count($array) == 0){
            echo 
'Error: array_get = ""';
            exit;
        }else{
            
$this->get "?";
            foreach ( 
$array as $clave=>$valor){
            
            
                
$this->get .=$clave."=".$valor."&";
            
            
            }
            
$this->url .=$this->get;
        }
    
    }
  
  
        public function 
redir($max=2)
    {
        
curl_setopt($this->chCURLOPT_RETURNTRANSFERtrue);
        
curl_setopt($this->chCURLOPT_MAXREDIRS,$max);
    
    }
  
  
      public function 
anadir_post($array
    {
        if(
count($array) == 0){
            echo 
'Error: array_post = ""';
            exit;
        }else{
             
curl_setopt($this->chCURLOPT_POSTtrue);  

            
curl_setopt($this->chCURLOPT_POSTFIELDShttp_build_query($array)); 
        
        }

    
    }
  
  
      public function 
anadir_cookie($array
    {
        
        if(
is_array($array) and count($array) != 0){
         
            
$this->cookie "";
            
$cont 1;
            foreach ( 
$array as $clave=>$valor){
                    
                    if(
$cont count($array)){
                        
$this->cookie .=$clave."=".$valor.";";
                    }else{
                        
$this->cookie .=$clave."=".$valor;
                    }
                
$cont++;
            }

        }else{
                echo 
'Error: array_cookie = ""';
            exit;
        }
    
        
curl_setopt($this->ch,CURLOPT_COOKIE,$this->cookie);
        


    }

Se utiliza de manera fácil.

Código PHP:
$conexion = new conectar("url"); // iniciamos la clase
$conexion->anadir_post($array); // array con las variables que queremos mandar por post
$conexion->anadir_get($array);// array con las variables que queremos mandar por get
$conexion->anadir_cookie($array);// array con las variables que queremos mandar por cookie
$conexion->redir(2); // redireccionar y número max de ellas.(2 por defecto)
$conexion->tiempo(30); //tiempo máximo.

$html $conexion->obtener_html();  // obtienes el código fuente de la url 

Si la valoráis y la veis útil, seguiré con ella, y la mejoraré.

Saludos.
  #2 (permalink)  
Antiguo 19/05/2014, 13:20
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Clase para utilizar Curl

Sería excelente si subes tu código a GitHuby lo publicas como dependencia en Composer.

De otra forma el aporte no tiene sentido, seguramente con el tiempo se perderá.
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
  #3 (permalink)  
Antiguo 19/05/2014, 13:29
 
Fecha de Ingreso: octubre-2012
Mensajes: 135
Antigüedad: 11 años, 6 meses
Puntos: 8
gracias por la idea, mañana con mas tiempo lo hago. ya le he pedido al administrador que lo ponga en aportes.
  #4 (permalink)  
Antiguo 19/05/2014, 13:52
Avatar de Italico76  
Fecha de Ingreso: abril-2007
Mensajes: 3.303
Antigüedad: 17 años
Puntos: 292
Respuesta: Clase para utilizar Curl

Excelente... no lo he probado.. pero te hice unos cambios:

Código PHP:
Ver original
  1. <?php
  2. /*
  3.     EasyCurl
  4.     @author: Cesar Blanco Guillamon (16)   
  5.     @history: cambio de nombre a la clase, cambio de nombre a metodos, cambio de visibilidad de metodos, uso de excepciones
  6.  
  7. */
  8. class EasyCurl{
  9.     private $html;  
  10.     private $url;  
  11.     private $ch;  
  12.     private $http_get;
  13.  
  14.     public function __construct($url)  
  15.     {
  16.         if (!empty($url)){
  17.              
  18.             $this->url=$url;  
  19.             $this->ch = curl_init();               
  20.                  
  21.         }else
  22.             throw new Exception('Error: url = ""');        
  23.     }
  24.      
  25.     public function setTiempo($max)  
  26.     {
  27.         if(isset($max))                
  28.             curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, $max);
  29.         else
  30.             throw new Exception('Error: tiempo maximo = ""');            
  31.          
  32.     }
  33.      
  34.      
  35.     public function getHtml()  
  36.     {      
  37.         curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);  
  38.         curl_setopt($this->ch, CURLOPT_URL, $this->url);  
  39.         $this->html = curl_exec($this->ch);  
  40.         curl_close($this->ch);
  41.  
  42.         return $this->html;
  43.     }
  44.      
  45.      public function addGet($array)  
  46.     {
  47.         if(count($array) == 0)
  48.             throw new Exception('Error: array_get = ""');                      
  49.         else{
  50.             $this->http_get = "?";
  51.             foreach ( $array as $clave=>$valor){
  52.              
  53.              
  54.                 $this->http_get .=$clave."=".$valor."&";
  55.              
  56.              
  57.             }
  58.             $this->url .=$this->http_get;
  59.         }
  60.      
  61.     }
  62.    
  63.        public function redir($max=2)
  64.     {
  65.         curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
  66.         curl_setopt($this->ch, CURLOPT_MAXREDIRS,$max);
  67.      
  68.     }
  69.    
  70.    
  71.     public function addPost($array)  
  72.     {
  73.         if(count($array) == 0)
  74.             throw new Exception('Error: array_post = ""');            
  75.         else{
  76.             curl_setopt($this->ch, CURLOPT_POST, true);  
  77.             curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($array));          
  78.         }
  79.  
  80.      
  81.     }
  82.    
  83.    
  84.     public function addCookie($array)  
  85.     {
  86.          
  87.         if(is_array($array) and count($array) != 0){
  88.          
  89.             $this->cookie = "";
  90.             $cont = 1;
  91.             foreach ( $array as $clave=>$valor){
  92.                      
  93.                     if($cont < count($array)){
  94.                         $this->cookie .=$clave."=".$valor.";";
  95.                     }else{
  96.                         $this->cookie .=$clave."=".$valor;
  97.                     }
  98.                 $cont++;
  99.             }
  100.  
  101.         }else{
  102.                 throw new Exception('Error: array_cookie = ""');
  103.             exit;
  104.         }
  105.      
  106.         curl_setopt($this->ch,CURLOPT_COOKIE,$this->cookie);
  107.          
  108.  
  109.  
  110.     }
  111. }  
  112.  
  113.  
  114. // Prueba:
  115.  
  116. $conexion = new EasyCurl("https://www.facebook.com/meryttt"); // iniciamos la clase
  117. exit();
  118. $conexion->addPost($array); // array con las variables que queremos mandar por post
  119. $conexion->addGet($array);// array con las variables que queremos mandar por get
  120. $conexion->addCookie($array);// array con las variables que queremos mandar por cookie
  121. $conexion->redir(2); // redireccionar y número max de ellas.(2 por defecto)
  122. $conexion->setTime(30); //tiempo máximo.
  123.  
  124. $html = $conexion->obtener_html();  // obtienes el código fuente de la url
__________________
Salu2!

Última edición por Italico76; 19/05/2014 a las 14:08
  #5 (permalink)  
Antiguo 19/05/2014, 15:13
 
Fecha de Ingreso: octubre-2012
Mensajes: 135
Antigüedad: 11 años, 6 meses
Puntos: 8
Respuesta: Clase para utilizar Curl

Muchas gracias por el aporte, es la primera clase que construyo, llevo una semana conociendo POO.
Ahora me toca googlear para buscar un par de cosas que no entiendo de las que has puesto xD
  #6 (permalink)  
Antiguo 20/05/2014, 03:12
 
Fecha de Ingreso: octubre-2012
Mensajes: 135
Antigüedad: 11 años, 6 meses
Puntos: 8
Respuesta: Clase para utilizar Curl

https://github.com/botxiidev/EasyCurl-php-Class ya está el repositorio oficial.
Gracias a todos.
  #7 (permalink)  
Antiguo 20/05/2014, 03:21
Avatar de Eleazan  
Fecha de Ingreso: abril-2008
Ubicación: Ibiza
Mensajes: 1.879
Antigüedad: 16 años
Puntos: 326
Respuesta: Clase para utilizar Curl

Te he creado un "issue"...

Para fastidiar más que nada xD

Saludos!
__________________
>> Eleazan's Source
>> @Eleazan
  #8 (permalink)  
Antiguo 20/05/2014, 03:29
Avatar de Eleazan  
Fecha de Ingreso: abril-2008
Ubicación: Ibiza
Mensajes: 1.879
Antigüedad: 16 años
Puntos: 326
Respuesta: Clase para utilizar Curl

A parte del setOpt que te he comentado en github... hay veces que, con cURL, interesa obtener una web, obtener unos datos, y luego consultar otra web... no creo que el curl_close en getHtml() sea la mejor opción. Deberías sacarlo fuera ;)
Y añadir un setUrl o similar! ;)

Saludos!
PD: Trabajo bastante con cURL, suelo usar esta: https://github.com/php-curl-class/php-curl-class, q está bastante bien! ;)
__________________
>> Eleazan's Source
>> @Eleazan

Etiquetas: clases, curl, poo
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 1 personas




La zona horaria es GMT -6. Ahora son las 03:15.