Jump to content
Xander

[PHP] clasa CURL

Recommended Posts

Posted

Daca este nevoie o sa dau si explicatii mai in detaliu... am incercat sa dau niste exemple care sa acopere cat mai mult din ce poate face

Ce ar trebui sa faca: sa usureze foarte mult utilizarea librariei curl in php


class.curl.php:

<?php

class curl
{
var $C , $debug = false , $lastcode , $logverbose = "";
var $useCookies = true;
var $agent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.67 Safari/534.13";
var $LastData , $proxy , $proxytype , $CJ = "./cookiejar.txt";
var $ref , $autoref = 0; // 0 = manual , 1 = normal(only GET updates ref) , 2 = full (all requests update ref)
var $headers = array() , $cleanup = array() , $opts = array();
var $url;
public static $debugHandle;
var $error = false;
var $errorMessage = "";
function __construct($opts = array())
{
$this->C = curl_init();

foreach($opts as $key => $var) // jquery style options
{
$this->$key = $var;
}

$default_options = array
(
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_TIMEOUT => 60,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $this->agent,
CURLOPT_FORBID_REUSE => true,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0
);

$this->addHeader(array("Expect" => ""));

$this->setOpt($default_options);

if(isset($opts['useCookies']))
{
if($opts['useCookies']) $this->SetCookieJar();
}

}
function setAgent($agent)
{
$this->setOpt( array ( CURLOPT_USERAGENT => $agent ) );
$this->agent = $agent;
}
function __destruct()
{
$this->Close();
}
function Close()
{
@curl_close($this->C);
if($this->autoclear) $this->Clear();
}
function getAutoRef()
{
return $this->autoref;
}
function setAutoRef($activate)
{
$this->autoref = (int)$activate;
}
function SetCookieJar($data = "")
{
if($data == "")
$data = $this->CJ;
return $this->_SetCookieJar($data);
}
function _SetCookieJar($data)
{
$this->CJ = $data;
if ( $data != "" )
{
$this->setOpt
(
array
(
CURLOPT_COOKIEJAR => $this->CJ,
CURLOPT_COOKIEFILE => $this->CJ
)
);
$this->ProcessCookieJar();
}
}
function Clear()
{
if ( $this->useCookies && file_exists ( $this->CJ ) )
unlink ( $this->CJ );
}
function ProcessCookieJar()
{
if( !file_exists ( $this->CJ ) )
{
file_put_contents( $this->CJ , "" );
chmod ( $this->CJ , 777 ) ;
}
}
function Req($param , $data = "" , $update = true)
//$url , $data = "" , $update = true)
{
if ( is_array ( $param ) )
{
foreach($param as $key => $val)
{
$$key = $val;
}
}
else
$url = $param;

if ( $this->debug )
curl::$debugHandle = fopen("log.txt" , "a");
else
curl::$debugHandle = fopen("php://stderr" , "w");

if($update)
$this->LastData = $this->___req($url , $data);
else
$temp = $this->___req($url , $data);

$this->info = curl_getinfo( $this->C );

fclose(curl::$debugHandle);

$this->cleanHeaders();

return $update ? $this->LastData : $temp;
}

function ___req($url , $data = "")
{
$this->error = false;
$this->errorMessage = "";

if($this->ref != "") // set referer header if present
$this->addHeader(array("Referer" => $this->ref));

$request = $this->getRequest($data);

$opts = array
(
CURLOPT_URL => $url,
CURLOPT_PORT => substr_compare($url , "https://" , 0 , 8 , true) === 0 ? 443 : 80 ,
CURLOPT_PROXY => $this->proxy ? $this->getProxy(0) : "",
CURLOPT_PROXYTYPE => $this->proxy ? $this->getProxy(1) : "",
CURLOPT_VERBOSE => $this->debug ? 1 : 0,
CURLOPT_STDERR => curl::$debugHandle,
CURLOPT_HTTPHEADER => $this->getHeaders()
);
if($this->debug && (is_callable($this->logverbose) || method_exists($this,"logverbose"))) $this->logverbose($this , "Request info (" . CURLOPT_POST . ":" . @(int)$opts[CURLOPT_POST] . "): " . $url . "<pre>" . print_r($request , true) . "</pre>");
if($request['type'] == "POST")
{
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = $request['data'];
if($this->debug) fwrite(curl::$debugHandle , "POSTFIELDS:\n" . print_r($request['data'],true) . "\n");
}
else
{
$opts[CURLOPT_POSTFIELDS] = -1;
$opts[CURLOPT_POST] = -1;
}

$this->setOpt($opts);

if($this->autoref == 2) // auto update ref even if POST
$this->ref = $url;

else if($this->autoref == 1 && ! $request['type'] == "POST") // auto update ref only on GET
$this->ref = $url;

$this->_setOpts();

if( ( $ret = curl_exec($this->C) ) === false )
{
$this->error = true;

$this->errorMessage = 'Curl error: (' . $url . ') - ' . curl_error($this->C);

if($this->debug)
if (is_callable($this->logverbose) || method_exists($this , "logverbose"))
$this->logverbose($this , $url . "<br />" . $ret );
else
echo $this->errorMessage . "\n";

return false;
}
else
{
$this->lastcode = curl_getinfo($this->C, CURLINFO_HTTP_CODE);
if($this->debug && (is_callable($this->logverbose) || method_exists($this , "logverbose")))
$this->logverbose($this , $url . "<br />" . $ret );
return $ret;
}
}

function getResponseCode($url , $data = "")
{
$this->Req($url , $data);
return $this->lastcode;
}
function getInfo($url , $data = "" , $arr = "")
{
$this->Req($url , $data);
if($arr != "")
return $this->info[$arr];
return $this->info;
}

function getRequest($data)
{
$request = array();
$request['data'] = $data;

if ( !is_array($data) && $data == "" ) // not array and blank data : get
$request['type'] = "GET";
else if ( is_array ( $data ) ) // array : POST
{
$request['type'] = "POST";
$upload = false;
foreach($data as $k => $v)
if( !is_array($v) && substr($v , 0 , 1) == "@" )
{
$upload = true;
break;
}
if($upload == false) // no file upload : serialize ( x-www-form-urlencoded ) else multipart/form-data
$request['data'] = $this->serialize($data);
}
else
$request['type'] = "POST"; // x-www-form-urlencoded ( already serialized )

return $request;
}
function getProxy($method)
{
if(!$method)
return $this->proxy;
return $this->proxytype == "http" ? CURLPROXY_HTTP : CURLPROXY_SOCKS5;
}
function addHeader($array , $persist = false)
{
foreach($array as $k => $v)
{
$this->headers[$k] = $v;
if(!$persist)
$this->cleanup[] = $k;
}
}
function getHeaders()
{
$hdrs = array();
foreach($this->headers as $key => $val)
$hdrs[] = $key . ": " . $val;
return $hdrs;
}
function cleanHeaders()
{
foreach($this->cleanup as $key)
unset($this->headers[$key]);
$this->cleanup = array();
}
function purgeHeaders()
{
$this->headers = array();
}
function _setOpts()
{
curl_setopt_array($this->C , $this->opts);
}
function setOpt($opts , $v = null)
{
if(is_array($opts) && $v == null)
foreach($opts as $key => $val)
if($val == -1)
unset($this->opts[$key]);
else
$this->opts[$key] = $val;
else
if($v == -1)
unset($this->opts[$opts]);
else
$this->opts[$opts] = $v;
}
function opt($k , $v)
{
curl_setopt($this->C , $k , $v);
}

function serialize($arr , $name = "")
{
$ret = "";
foreach($arr as $key=>$val)
{
if(is_array($val))
$ret .= ($ret != ""?"&":"") . $this->serialize($val,$key);
else
{
if($name != "")
$ret .= ($ret !=""?"&":"") . $name . "[" . $key . "]=".$val;
else
$ret .= ($ret !=""?"&":"") . $key . "=" . $val;
}
}
return $ret;
}

public function __call($name , $args)
{
if(is_callable($this->$name))
call_user_func_array($this->$name , $args);
}
}

?>




<?php

class curl_debug extends curl
{
public function logverbose($object ,$test)
{
echo "This uses a member function: " . (int)$object->error . "\n";
}
}


$c = new curl(array("agent" => "My curl script" , "debug" => true , "logverbose" => function($obj,$data){ echo "This uses a closure: " . (int)$obj->error . "\n";}));

// direct call
$c->Req("https://google.ro");

// array call
$c->Req(
array(
"url" => "http://www.google.ro" ,
"data" => // daca setezi data se face automat post
array( // data este un vector asociativ
"q" => "searching for something",
"myfile" => "@/some/existing/file",
"param" => array(
"multiple" => "fields",
"with" => "the",
"same" => "name"
)
)
)
);

// direct call post
$c->Req("http://google.ro" , array("q" => "searching") , false); // param 3 = (bool) update this->LastData

// bad call
$c->Req("https://google.rz");

// change log function
$c->logverbose = function($o , $d){ echo "Changed verbose log\n"; };
$c->Req("https://google.ro");

// alta metoda de a seta functia de log
$d = new curl_debug();
$d->debug = true;
$d->Req("https://google.com");


?>

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...