<?php
/**
* Description of httpClient
*
* @author smn
*/
class httpClient {
protected $_curl;
protected $_url = '';
protected $_methods = array(
'GET' => CURLOPT_HTTPGET,
'POST' => CURLOPT_POST);
protected $_method;
protected $_postData = array();
protected $_headers = array();
protected $_followLocation = true;
protected $_maxRedirects = 10;
protected $_httpVersion = array(
'1' => CURL_HTTP_VERSION_1_0,
'2' => CURL_HTTP_VERSION_1_1);
protected $_httpV = 2;
protected $_timeout = 30;
protected $_queryParams = array();
protected $_result;
//protected $_compressTypes = array('compress', 'deflate', 'gzip', 'identity'); // supporto solo gzip e deflate (lib zlib)
protected $_compressTypes = array('gzip','deflate');
protected $_acceptEncoding = array();
public function __construct($url = '') {
$this->_curl = curl_init();
curl_setopt($this->_curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); // disable ipv6
$this->setMethod();
$this->setHttpVersion();
$this->setFollowLocation();
if ($url) {
$this->setUrl($url);
}
}
public function __destruct() {
$this->_curl = null;
}
public function remakeUrl() {
if (!$this->_url) {
return;
}
$url = $this->_url;
$parsed = parse_url($url);
unset($parsed['query']);
$u = (isset($parsed['scheme'])) ? $parsed['scheme'] : 'http';
$u .= '://' . $parsed['host'];
$u .= (isset($parsed['path'])) ? $parsed['path'] : '/';
$params = '';
/*if (count($this->_queryParams) > 0) {
$params .= http_build_query($this->_queryParams);
}*/
//$u .= '?' .$params; è inutile aggiungere i parametri nella remake , gli aggiunge già setUrl()
$this->setUrl($u);
}
public function isPost() {
if ($this->getMethod() == 'POST') {
return true;
}
return false;
}
public function isGet() {
if ($this->getMethod() == 'GET') {
return true;
}
return false;
}
public function setUrl($url, $flushqs = false) {
$this->_url = $url;
// $flushqs se true cancella precedenti querystring solo nel caso di get
$parsed = parse_url($url);
$params = (array_key_exists('query', $parsed)) ? $parsed['query'] : null;
$u = (isset($parsed['scheme'])) ? $parsed['scheme'] : 'http';
$u .= '://' . $parsed['host'];
$u .= (isset($parsed['path'])) ? $parsed['path'] : '/';
curl_setopt($this->_curl, CURLOPT_URL, $u);
$this->_url = $u;
// url impostata, ora setto le queryParams
if (($flushqs === true) && ($this->isGet())) {
$this->flushQueryString();
}
if (!is_null($params)) {
foreach (explode('&', $params) as $qs) {
$q = explode('=', $qs);
$key = $q[0];
$value = (isset($q[1])) ? $q[1] : '';
$this->setQueryParam($key, $value);
}
}
}
public function getUrl($include_queryString = false) {
// include querystring restituisce nel caso in cui sia get il metodo, la url compresa di querystring
//$this->remakeUrl();
$url = $this->_url;
if (($this->isGet()) && (count($this->_queryParams) > 0) && ($include_queryString == true)) {
$url .= '?' .http_build_query($this->_queryParams);
}
return $url;
}
public function getScheme() {
return parse_url($this->_url, PHP_URL_SCHEME);
}
public function getHost() {
return parse_url($this->_url, PHP_URL_HOST);
}
public function getPath() {
if (!parse_url($this->_url, PHP_URL_PATH)) {
return "/";
}
return parse_url($this->_url, PHP_URL_PATH);
}
public function getPort() {
if (!parse_url($this->_url, PHP_URL_PORT)) {
return 80;
}
return parse_url($this->_url, PHP_URL_PORT);
}
public function setMethod($method = 'GET') {
if (array_key_exists(strtoupper($method), $this->_methods)) {
curl_setopt($this->_curl, $this->_methods[strtoupper($method)], true);
$this->_method = strtoupper($method);
}
}
public function getMethod() {
return $this->_method;
}
public function setPost($postData, $postValue = '') {
$this->_postData[$postData] = $postValue;
}
public function getPost($post) {
if (array_key_exists($post, $this->_postData)) {
return $this->_postData[$post];
}
}
public function setPostData($data = array()) {
foreach ($data as $post => $value) {
$this->setPost($post, $value);
}
}
public function setQueryParam($key, $value = '') {
$this->_queryParams[$key] = $value;
}
public function getQueryParam($key) {
if (array_key_exists($key, $this->_queryParams)) {
return $this->_queryParams[$key];
}
}
public function setQueryParams($queryParams = array()) {
foreach ($queryParams as $key => $value) {
$this->setQueryParam($key, $value);
}
}
public function flushQueryString() {
$this->_queryParams = array();
}
public function flushHeaders() {
$this->_headers = array();
}
public function setHeader($header, $value = '') {
$this->_headers[$header] = $value;
}
public function getHeader($header) {
if (array_key_exists($header, $this->_headers)) {
return $this->_headers[$header];
}
return false;
}
public function setHeaders($headers = array()) {
foreach ($headers as $header => $value) {
$this->setHeader($header, $value);
}
}
public function setMaxRedirect($maxRedirect = 10) {
if (is_int($maxRedirect)) {
$this->_maxRedirects = $maxRedirect;
curl_setopt($this->_curl, CURLOPT_MAXREDIRS, $maxRedirect);
}
}
public function getMaxRedirect() {
return $this->_maxRedirects;
}
public function setFollowLocation($follow = true) {
if (is_bool($follow)) {
$this->_followLocation = $follow;
curl_setopt($this->_curl, CURLOPT_FOLLOWLOCATION, $follow);
}
}
public function setCompressType($compressType = '', $quality = null) {
if (!extension_loaded('zlib')) {
return;
}
if ($compressType == '') {
return;
}
if (array_search($compressType, $this->_compressTypes) === false) {
return false;
}
if (array_key_exists($compressType, $this->_compressTypes)) {
if (is_null($quality) && (array_key_exists('quality',$this->_acceptEncoding[$compressType]))) {
unset($this->_acceptEncoding[$compressType][$quality]);
}
else {
$this->_acceptEncoding[$compressType][$quality] = $quality;
}
}
else {
if (is_null($quality)) {
$data = array('name' => $compressType);
}
else {
$data = array('name' => $compressType, 'quality' => $quality);
}
$this->_acceptEncoding[$compressType] = $data;
}
}
public function getCompressType($compressType) {
if (array_key_exists($compressType, $this->_acceptEncoding)) {
return true;
}
return false;
}
public function delCompressType($compressType) {
if ($this->getCompressType($compressType)) {
unset($this->_acceptEncoding[$compressType]);
}
}
public function setUtf8($utf8 = true) {
if ($utf8 == true) {
$this->setHeader('Content-Type','text/html; charset=utf-8');
}
else {
unset($this->_headers['Content-Type']); // va cambiato
}
}
private function __implodeAcceptEncoding() {
$encodeParams = array();
if (count($this->_acceptEncoding) == 0) {
unset($this->_headers['Accept-Encoding']);
return;
}
foreach($this->_acceptEncoding as $encode) {
$nameEncode = $encode['name'];
$encodeParams[] = (array_key_exists('quality',$encode)) ? $nameEncode .';q=' .$encode['quality'] : $nameEncode;
}
$this->setHeader('Accept-Encoding', implode(', ', $encodeParams));
}
public function getFollowLocation() {
return $this->_followLocation;
}
public function setHttpVersion($httpVersion = 2) {
if (is_int($httpVersion)) {
if (array_key_exists($httpVersion, $this->_httpVersion)) {
curl_setopt($this->_curl, CURLOPT_HTTP_VERSION, $this->_httpVersion[$httpVersion]);
$this->_httpV = $this->_httpVersion[$httpVersion];
}
}
}
public function getHttpVersion() {
return $this->_httpV;
}
public function setTimeOut($timeout = 30) {
if (is_int($timeout)) {
curl_setopt($this->_curl, CURLOPT_TIMEOUT, $timeout);
$this->_timeout = $timeout;
}
}
public function getTimeOut() {
return $this->_timeout;
}
public function setUserAgent($value = 'my client') {
$this->_headers["User-Agent"] = $value;
}
public function getUserAgent() {
return $this->_headers["User-Agent"];
}
private function __implodeHeader() {
$_header = array();
$this->__implodeAcceptEncoding(); // ogni volta che genero gli header genero anche quello dell'encoding
ksort($this->_headers);
foreach ($this->_headers as $header => $value) {
$_header[] = $header . ':' . $value;
}
curl_setopt($this->_curl, CURLOPT_HTTPHEADER, $_header);
}
public function send() {
curl_setopt($this->_curl, CURLOPT_HEADER, true); // imposto la ricezione degli header
curl_setopt($this->_curl, CURLOPT_RETURNTRANSFER, true); // imposto il body
curl_setopt($this->_curl, CURLOPT_SSL_VERIFYPEER, false); // imposto la verifica dell'ssl a false
$this->__implodeHeader(); // imposto tutti gli header alla curl resource
//$this->remakeUrl();
// se sono in get, devo ricreare l'url con i parametri
$url = $this->getUrl();
if (($this->isGet()) && (count($this->_queryParams) > 0)) {
$url .= '?' .http_build_query($this->_queryParams);
curl_setopt($this->_curl, CURLOPT_URL, $url);
}
// se sto in post, devo settare i postdata sull'ggetto curl
if ($this->isPost()) {
// se ho l'header Content-Type con multipart/form-data, gli passo un array a CURLOPT_POSTFIELDS
// se ho l'header Content-Type con application/x-www-form-urlencoded , gli passo una stringa encoded con http_build_query
// se ho l'header Content-Type che non è uno di quei due o non lo tengo proprio, gli passo l'array
//
// quindi, in sostanza, se è application/x-www-form-urlencoded gli passo una stringa encoded, altrimenti glielo passo array
if ($this->getHeader('Content-Type') == 'application/x-www-form-urlencoded') {
curl_setopt($this->_curl, CURLOPT_POSTFIELDS, http_build_query($this->_postData));
}
else {
curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $this->_postData);
}
}
$this->_result = curl_exec($this->_curl);
}
public function getResponseCode() {
return curl_getinfo($this->_curl, CURLINFO_HTTP_CODE); // ultimo codice, anche in caso di redirect
}
public function getOnlyHeader() {
// to dev
}
public function getResponseHeaders() {
$header = substr($this->_result, 0, curl_getinfo($this->_curl, CURLINFO_HEADER_SIZE)); // prendo la risposta fino al carattere pari alla dimensione degli header
$h = explode('\r\n\r\n', $header);
$headers = array();
foreach (explode(chr(13), $h[0]) as $_index => $_header) {
$split = preg_split('/\:/', $_header, 2);
if (count($split) > 1) {
// migliorare con trim per eliminare spazi ad inizio e fine
$headerName = str_replace(chr(10), '', $split[0]); // elimina carattere NL
$headerValue = str_replace(chr(10), '', $split[1]); // elimina carattere NL
$headerValue = substr($headerValue,1, strlen($headerValue)); // elimina il primo carattere che è uno spazio
if (array_key_exists($headerName, $headers)) {
if (is_array($headers[$headerName])) {
$headers[$headerName][] = $headerValue;
}
else {
$oldValue = $headers[$headerName];
$headers[$headerName] = array($oldValue, $headerValue);
}
}
else {
$headers[$headerName] = $headerValue;
}
}
}
return $headers;
}
public function getCookies() {
}
public function getResponseBody() {
$body = substr($this->_result, curl_getinfo($this->_curl, CURLINFO_HEADER_SIZE));
// unici formati supportati attualmente sono gzip e deflate
if (!extension_loaded('zlib')) {
return $body;
}
$headers = $this->getResponseHeaders();
if (!array_key_exists('Content-Encoding', $headers)) {
return $body;
}
$compress = $headers['Content-Encoding'];
if ($compress == 'gzip') {
$body = gzdecode($body);
}
if ($compress == 'deflate') {
$body = gzinflate($body);
}
return $body;
}
public function getRawResponseBody() {
$body = substr($this->_result, curl_getinfo($this->_curl, CURLINFO_HEADER_SIZE));
return $body;
}
public function getObject() {
return $this->_curl;
}
public function getNumberOfRedirect() {
return curl_getinfo($this->_curl, CURLINFO_REDIRECT_COUNT);
}
}
?>
|