Clase cURL (PHP)

  • Autor Autor zcriptz
  • Fecha de inicio Fecha de inicio
zcriptz

zcriptz

1
Ómicron
Programador
Verificación en dos pasos activada
Verificado por Whatsapp
Suscripción a IA
Ya había hecho un tema pero cambié muchas cosas, si ven algún bug avisen!

Guardan este código en un archivo PHP con el nombre que quieran, en este caso cURL.php

PHP:
<?php

class cURL{
    public function __construct($cookies=NULL, $agent=NULL, $proxy=NULL){
        $this->SETOPT = array(
            'RETURNTRANSFER' => 1,
            'FOLLOWLOCATION' => 1,
            'SSL_VERIFYHOST' => 0,
            'SSL_VERIFYPEER' => 0,
            'CUSTOMREQUEST'  => 'GET',
        );
        $this->proxy = $proxy;
        if($cookies){
            $this->SETOPT['COOKIEJAR'] = $cookies;
            $this->SETOPT['COOKIEFILE'] = $cookies;
        }
        $this->SETOPT['USERAGENT'] = $agent;
    }

    private function cURLOPT($c){
        curl_setopt_array($c, array_combine(array_map(function ($k){ return constant('CURLOPT_'.$k); }, array_keys($this->SETOPT)), $this->SETOPT));
        return $this;
    }

    private function cURL(){
        $c = curl_init();
        if($this->proxy){
            $proxyData = array_flip(explode('@', $this->proxy));
            $this->SETOPT['PROXY'] = $proxyData[0];
            if($pD[1]) $this->SETOPT['PROXYUSERPWD'] = $proxyData[1];
            if(!$this->SETOPT['PROXYTYPE']) $this->SETOPT['PROXYTYPE'] = 'HTTP';
        }
        if(@$this->headers) curl_setopt($c, CURLOPT_HTTPHEADER, $this->headers);
        return $c;
        }

    public function exec($c){
        $this->cURLOPT($c);
        $this->result = curl_exec($c);
        return $this;
    }

    private function close($c){
        return curl_close($c);
    }

    public function browse($URL=NULL, $ref=NULL, $post=NULL){
        if($URL) $this->SETOPT['URL'] = $URL;
        if($ref) $this->SETOPT['REFERER'] = $ref;
        $c = $this->cURL();
        if($this->SETOPT['POSTFIELDS'] || $this->SETOPT['POSTFIELDS'] = $post){
            $this->SETOPT['POST'] = 1;
            $this->SETOPT['CUSTOMREQUEST'] = 'POST';
        }else{
            $this->SETOPT['POST'] = 0;
            unset($this->SETOPT['CUSTOMREQUEST']);
        }
        if(curl_error($c)) die('cURL Error ('.curl_errno($c).')');
        return $this->exec($c);
    }

    public function getSize(){
        return explode('/', $this->getHeader('Content-Range')[1])[1];
    }

    public function searchHeader($h){
        foreach($this->headers AS $k => $v) if($e = explode(':', $v) AND stristr($e[0], $h)) return array_map('trim', $e);
        return false;
    }

    public function getHeader($header=NULL, $follow=1){
        $c = $this->cURL();
        $this->SETOPT = array_merge(
            array(
                'HEADER' => 1,
                'FOLLOWLOCATION' => $follow,
                'NOBODY' => 1
            ),
            $this->SETOPT
        );
        $this->headers = array_filter(array_map('trim', explode(PHP_EOL, $this->exec($c)->result)));

        if($header) return $this->searchHeader($header);
        return $this;
    }

    public function forceDownload($n=NULL, $b=1024){
        if(!$b) die('no bytes');
        set_time_limit(0);
        header('Content-Type: application/octet-stream');
        ($n) ? header("Content-Disposition: attachment; filename=$n") : header(@implode(':', $this->searchHeader('Content-Disposition')));
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Expires: 0');
        header('Pragma: public');
        if($s = $this->size OR $s = $this->getSize()) header('Content-Length: '.$s);
        $i = 0;
        while($i <= $s){
            $c = $this->cURL();
            if($b) $r = $i.'-'.(($i+$b) > $s ? $s : $i+$b);
            $this->SETOPT['HEADER'] = 0;
            $this->SETOPT['NOBODY'] = 0;
            $this->SETOPT = array_merge(
                array(
                     'RANGE' => $r,
                    'WRITEFUNCTION' => array($this, 'writeBytes'),
                    'BINARYTRANSFER' => 1
                ),
                $this->SETOPT
               );
            $this->exec($c);
           $i = $i+$b+1;
        }
    }

    private function writeBytes($c, $str){
        print($str);
        $this->flush();
        return strlen($str);
    }

    private function flush(){
        ob_end_flush();
        ob_flush();
        flush();
        ob_start();
        return $this;
    }

    public function SETOPTS($a){
        $this->SETOPT = array_merge($this->SETOPT, $a);
    }

    public function getURLs($from=NULL){
        if($from) $this->browse($from);
        preg_match_all("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $this->result, $this->URLs);
        return $this;
    }

    function cmd($c){
        preg_match_all('/curl "[^"]+|-H "[^"]+|--[^"]+"[^"]+/', str_replace('^', '', str_replace('\^"', "'", $c)), $cmdInfo);
        $this->SETOPT['POSTFIELDS'] = '';
        foreach($cmdInfo[0] AS $curlInfo)
            !strstr($curlInfo, '--data')
                ?
                    strstr($curlInfo, '-H "')
                        &&
                    ($curlInfo = str_replace('-H "', '', $curlInfo))
                        &&
                    $this->headers[] = $curlInfo
                :
                    $this->SETOPT['POSTFIELDS'] = urldecode(preg_replace('/--[^"]+"/', '', $curlInfo))
        ;

        return $this->browse(str_replace('curl "', '', $cmdInfo[0][0]), '');
    }
}


Demo 1:
PHP:
<?php
require_once('cURL.php');

$cURL = new cURL('cookies.txt', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36');
$cURL->headers = array(
    'accept: */*',
    'origin: https://www.forobeta.com',
    'accept-language: es-ES,es;q=0.9'
);
echo $cURL->browse('https://www.forobeta.com', 'https://www.prueba.com')->result;

En el caso del demo estaría devolviendo el código HTML de ForoBeta, enviando como referer "prueba.com".

Puse algunas cabeceras para que vean como se pueden agregar.

________________________________________________________________________________




Demo 2:
PHP:
<?php
require_once('cURL.php');

$cURL = new cURL('cookies.txt', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36');
$cURL->SETOPT = array(
    'URL' => 'https://www.forobeta.com',
    'REFERER' => 'https://www.google.com'
);

print_r($cURL->getHeader()->headers);

Resultado:
Array
(
[0] => HTTP/2 301
[1] => location: https://forobeta.com/
[2] => content-type: text/html; charset=UTF-8
[3] => date: Wed, 24 Jul 2019 23:07:34 GMT
[4] => server: LiteSpeed
[5] => alt-svc: quic=":443"; ma=2592000; v="35,39,43,44"
[7] => HTTP/2 200
[8] => set-cookie: bb_lastactivity=0; expires=Thu, 23-Jul-2020 23:07:34 GMT; Max-Age=31535999; path=/; secure
[9] => content-type: text/html; charset=UTF-8
[10] => date: Wed, 24 Jul 2019 23:07:35 GMT
[11] => server: LiteSpeed
[12] => alt-svc: quic=":443"; ma=2592000; v="35,39,43,44"
)
En este caso obtendremos las cabeceras de ForoBeta entrando como si fuera de Google. (Como obtener cabeceras)

________________________________________________________________________________




Demo 3 (Para enviar campos POST)

PHP:
<?php
require_once('cURL.php');

$cURL = new cURL('cookies.txt', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36');
$cURL->headers = array(
    'accept: */*',
    'origin: https://www.w3schools.com',
    'accept-language: es-ES,es;q=0.9'
);
echo $cURL->browse('https://www.w3schools.com/action_page.php', 'https://www.w3schools.com', 'firstname=Nombre&lastname=Apellido')->result;

En este caso usé el formulario de W3School para mostrar como envio los campos "firstname" y "lastname" por POST.

Resultado:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Forms action page</title>
<link rel="stylesheet" href="/w3css/4/w3.css">
<body class="w3-container">
<h1>Submitted Form Data</h1>
<h2>Your input was received as:</h2>
<div class="w3-container w3-large w3-border" style="word-wrap:break-word">
firstname=Nombre&lastname=Apellido&nbsp;</div>

<p>The server has processed your input and returned this answer.</p>

<div class="w3-panel w3-pale-yellow w3-leftbar w3-border-yellow">
<p><strong>Note:</strong> This tutorial will not teach you how servers are processing input.
Processing input is explained in our <a href="/php/default.asp" target="_blank">PHP tutorial</a>.</p>
</div>

</body>
</html>
__________________________

Clase para navegar webs con SOCKET (PHP)
 
Última edición:
Gracias, puede ahorrarme algo de tiempo, a favoritos
 
Excelente introducción a cURL. Es interesante las posibilidades que brinda
 
Increible esta muy bien gracias por la introduccion al php debio tomarte mucho tiempo hacer esto lo voy a guardar con el nombre de cURL.php en mis archivos. 🙂🙂
 
No se estaban enviado las cabeceras, solucionado.
 
Muchas gracias, me va a ser muy útil 🙂
 
No se estaban enviado las cabeceras, solucionado.

no hay forma de enviar los headers y hacer redireccion??

ejemplo: quiero hacer redireccion a una pagina pero quiero que tenga otro referrer distinto a la pagina de donde lo hago
 
no hay forma de enviar los headers y hacer redireccion??

ejemplo: quiero hacer redireccion a una pagina pero quiero que tenga otro referrer distinto a la pagina de donde lo hago

Si, en las demos se puede ver como seteo referers.
 
Si, en las demos se puede ver como seteo referers.

hablo de como combinar un header location con esta clase en php para hacer una redireccion desde php a otra url enviando otro referrer para que parezca que la redireccion fue de otro sitio
 
A favoritos! yo siempre hago scraping y esto me va de lujo gracias, por cierto zcriptz entre curl php y Simple HTML Dom cual seria mas fácil algo más como y cuando debo usar los headers
 
hablo de como combinar un header location con esta clase en php para hacer una redireccion desde php a otra url enviando otro referrer para que parezca que la redireccion fue de otro sitio

PHP:
<?php

require_once('cURL.php');

$cURL = new cURL('cookies.txt', $_SERVER['HTTP_USER_AGENT']);
$cURL->SETOPT['URL'] = 'https://webconlocation.com';
$cURL->SETOPT['REFERER'] = 'https://webreferer.com';

echo $cURL->browse($cURL->getHeader('location')[1])->result;
 
A favoritos! yo siempre hago scraping y esto me va de lujo gracias, por cierto zcriptz entre curl php y Simple HTML Dom cual seria mas fácil algo más como y cuando debo usar los headers

En la demo 1 y 3 se puede ver como usar headers.
A mi parecer es más sencillo con mi clase, es una por indice.

O puedes usar "cmd".


Aquí lo uso.
 
PHP:
<?php

require_once('cURL.php');

$cURL = new cURL('cookies.txt', $_SERVER['HTTP_USER_AGENT']);
$cURL->SETOPT['URL'] = 'https://webconlocation.com';
$cURL->SETOPT['REFERER'] = 'https://webreferer.com';

echo $cURL->browse($cURL->getHeader('location')[1])->result;

hablo de hacer un header("location: www.dominio.com") y que este ponerle un referrer distinto al sitio donde estoy haciendo la redireccion, no quiero leer el contenido
 
Atrás
Arriba