├── .gitignore ├── CurlWrapper.php ├── LICENSE ├── README.md └── composer.json /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .DS_Store 3 | composer.phar -------------------------------------------------------------------------------- /CurlWrapper.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright 2010-2011, 2014 Leonid Svyatov 7 | * @license http://www.opensource.org/licenses/mit-license.html MIT License 8 | * @version 1.3.0 9 | * @link http://github.com/svyatov/CurlWrapper 10 | */ 11 | class CurlWrapper 12 | { 13 | /** 14 | * @var resource cURL handle 15 | */ 16 | protected $ch = null; 17 | /** 18 | * @var string Filename of a writable file for cookies storage 19 | */ 20 | protected $cookieFile = ''; 21 | /** 22 | * @var array Cookies to send 23 | */ 24 | protected $cookies = array(); 25 | /** 26 | * @var array Headers to send 27 | */ 28 | protected $headers = array(); 29 | /** 30 | * @var array cURL options 31 | */ 32 | protected $options = array(); 33 | /** 34 | * @var array Predefined user agents. The 'chrome' value is used by default 35 | */ 36 | protected static $predefinedUserAgents = array( 37 | // IE 11 38 | 'ie' => 'Mozilla/5.0 (compatible; MSIE 11.0; Windows NT 6.1; WOW64; Trident/6.0)', 39 | // Firefox 29 40 | 'firefox' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20120101 Firefox/29.0', 41 | // Opera 20 42 | 'opera' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.46 Safari/537.36 OPR/20.0.1387.24 (Edition Next)', 43 | // Chrome 32 44 | 'chrome' => 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36', 45 | // Google Bot 46 | 'bot' => 'Googlebot/2.1 (+http://www.google.com/bot.html)', 47 | ); 48 | /** 49 | * @var array GET/POST params to send 50 | */ 51 | protected $requestParams = array(); 52 | /** 53 | * @var string cURL response data 54 | */ 55 | protected $response = ''; 56 | /** 57 | * @var array cURL transfer info 58 | */ 59 | protected $transferInfo = array(); 60 | 61 | /** 62 | * Initiates the cURL handle 63 | * 64 | * @throws CurlWrapperCurlException 65 | */ 66 | public function __construct() 67 | { 68 | if (!extension_loaded('curl')) { 69 | throw new CurlWrapperException('cURL extension is not loaded.'); 70 | } 71 | 72 | $this->ch = curl_init(); 73 | 74 | if (!$this->ch) { 75 | throw new CurlWrapperCurlException($this->ch); 76 | } 77 | 78 | $this->setDefaults(); 79 | } 80 | 81 | /** 82 | * Closes and frees the cURL handle 83 | */ 84 | public function __destruct() 85 | { 86 | if (is_resource($this->ch)) { 87 | curl_close($this->ch); 88 | } 89 | 90 | $this->ch = null; 91 | } 92 | 93 | /** 94 | * Adds a cookie for a cURL transfer 95 | * 96 | * Examples: 97 | * $curl->addCookie('user', 'admin'); 98 | * $curl->addCookie(array('user'=>'admin', 'test'=>1)); 99 | * 100 | * @param string|array $name Name of cookie or array of cookies (name=>value) 101 | * @param string $value Value of cookie 102 | */ 103 | public function addCookie($name, $value = null) 104 | { 105 | if (is_array($name)) { 106 | $this->cookies = $name + $this->cookies; 107 | } else { 108 | $this->cookies[$name] = $value; 109 | } 110 | } 111 | 112 | /** 113 | * Adds a header for a cURL transfer 114 | * 115 | * Examples: 116 | * $curl->addHeader('Accept-Charset', 'utf-8;q=0.7,*;q=0.7'); 117 | * $curl->addHeader('Pragma', ''); 118 | * $curl->addHeader(array('Accept-Charset'=>'utf-8;q=0.7,*;q=0.7', 'Pragma'=>'')); 119 | * 120 | * @param string|array $header Header or array of headers (header=>value) 121 | * @param string $value Value of header 122 | */ 123 | public function addHeader($header, $value = null) 124 | { 125 | if (is_array($header)) { 126 | $this->headers = $header + $this->headers; 127 | } else { 128 | $this->headers[$header] = $value; 129 | } 130 | } 131 | 132 | /** 133 | * Adds an option for a cURL transfer (@see http://php.net/manual/en/function.curl-setopt.php) 134 | * 135 | * @param integer|array $option CURLOPT_XXX predefined constant or associative array of constants (constant=>value) 136 | * @param mixed $value Value of option 137 | */ 138 | public function addOption($option, $value = null) 139 | { 140 | if (is_array($option)) { 141 | $this->options = $option + $this->options; 142 | } else { 143 | $this->options[$option] = $value; 144 | } 145 | } 146 | 147 | /** 148 | * Adds a request (GET/POST) parameter for a cURL transfer 149 | * 150 | * Examples: 151 | * $curl->addRequestParam('param', 'test'); 152 | * $curl->addRequestParam('param=test&otherparam=123'); 153 | * $curl->addRequestParam(array('param'=>'test', 'otherparam'=>123)); 154 | * 155 | * @param string|array $name Name of parameter, query string or array of parameters (name=>value) 156 | * @param string $value Value of parameter 157 | */ 158 | public function addRequestParam($name, $value = null) 159 | { 160 | if (is_array($name)) { 161 | $this->requestParams = $name + $this->requestParams; 162 | } elseif (is_string($name) && $value === null) { 163 | parse_str($name, $params); 164 | if (!empty($params)) { 165 | $this->requestParams = $params + $this->requestParams; 166 | } 167 | } else { 168 | $this->requestParams[$name] = $value; 169 | } 170 | } 171 | 172 | /** 173 | * Clears the cookies file 174 | */ 175 | public function clearCookieFile() 176 | { 177 | if (!is_writable($this->cookieFile)) { 178 | throw new CurlWrapperException('Cookie file "'.($this->cookieFile).'" is not writable or does\'n exists!'); 179 | } 180 | 181 | file_put_contents($this->cookieFile, '', LOCK_EX); 182 | } 183 | 184 | /** 185 | * Clears the cookies 186 | */ 187 | public function clearCookies() 188 | { 189 | $this->cookies = array(); 190 | } 191 | 192 | /** 193 | * Clears the headers 194 | */ 195 | public function clearHeaders() 196 | { 197 | $this->headers = array(); 198 | } 199 | 200 | /** 201 | * Clears the options 202 | */ 203 | public function clearOptions() 204 | { 205 | $this->options = array(); 206 | } 207 | 208 | /** 209 | * Clears the request parameters 210 | */ 211 | public function clearRequestParams() 212 | { 213 | $this->requestParams = array(); 214 | } 215 | 216 | /** 217 | * Makes the 'DELETE' request to the $url with an optional $requestParams 218 | * 219 | * @param string $url 220 | * @param array $requestParams 221 | * @return string 222 | */ 223 | public function delete($url, $requestParams = null) 224 | { 225 | return $this->request($url, 'DELETE', $requestParams); 226 | } 227 | 228 | /** 229 | * Makes the 'GET' request to the $url with an optional $requestParams 230 | * 231 | * @param string $url 232 | * @param array $requestParams 233 | * @return string 234 | */ 235 | public function get($url, $requestParams = null) 236 | { 237 | return $this->request($url, 'GET', $requestParams); 238 | } 239 | 240 | /** 241 | * Returns the last transfer's response data 242 | * 243 | * @return string 244 | */ 245 | public function getResponse() 246 | { 247 | return $this->response; 248 | } 249 | 250 | /** 251 | * Gets the information about the last transfer 252 | * 253 | * If $key is given, returns its value. Otherwise, returns an associative array with the following elements: 254 | * url - Last effective URL 255 | * content_type - Content-Type: of downloaded object, NULL indicates server did not send valid Content-Type: header 256 | * http_code - Last received HTTP code 257 | * header_size - Total size of all headers received 258 | * request_size - Total size of issued requests, currently only for HTTP requests 259 | * filetime - Remote time of the retrieved document, if -1 is returned the time of the document is unknown 260 | * ssl_verify_result - Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER 261 | * redirect_count - Number of redirects it went through if CURLOPT_FOLLOWLOCATION was set 262 | * total_time - Total transaction time in seconds for last transfer 263 | * namelookup_time - Time in seconds until name resolving was complete 264 | * connect_time - Time in seconds it took to establish the connection 265 | * pretransfer_time - Time in seconds from start until just before file transfer begins 266 | * size_upload - Total number of bytes uploaded 267 | * size_download - Total number of bytes downloaded 268 | * speed_download - Average download speed 269 | * speed_upload - Average upload speed 270 | * download_content_length - content-length of download, read from Content-Length: field 271 | * upload_content_length - Specified size of upload 272 | * starttransfer_time - Time in seconds until the first byte is about to be transferred 273 | * redirect_time - Time in seconds of all redirection steps before final transaction was started 274 | * certinfo - There is official description for this field yet 275 | * request_header - The request string sent. For this to work, add the CURLINFO_HEADER_OUT option 276 | * 277 | * @param string $key @see http://php.net/manual/en/function.curl-getinfo.php 278 | * @throws CurlWrapperException 279 | * @return array|string 280 | */ 281 | public function getTransferInfo($key = null) 282 | { 283 | if (empty($this->transferInfo)) { 284 | throw new CurlWrapperException('There is no transfer info. Did you do the request?'); 285 | } 286 | 287 | if ($key === null) { 288 | return $this->transferInfo; 289 | } 290 | 291 | if (isset($this->transferInfo[$key])) { 292 | return $this->transferInfo[$key]; 293 | } 294 | 295 | throw new CurlWrapperException('There is no such key: '.$key); 296 | } 297 | 298 | /** 299 | * Makes the 'HEAD' request to the $url with an optional $requestParams 300 | * 301 | * @param string $url 302 | * @param array $requestParams 303 | * @return string 304 | */ 305 | public function head($url, $requestParams = null) 306 | { 307 | return $this->request($url, 'HEAD', $requestParams); 308 | } 309 | 310 | /** 311 | * Makes the 'POST' request to the $url with an optional $requestParams 312 | * 313 | * @param string $url 314 | * @param array $requestParams 315 | * @return string 316 | */ 317 | public function post($url, $requestParams = null) 318 | { 319 | return $this->request($url, 'POST', $requestParams); 320 | } 321 | 322 | /** 323 | * Makes the 'PUT' request to the $url with an optional $requestParams 324 | * 325 | * @param string $url 326 | * @param array $requestParams 327 | * @return string 328 | */ 329 | public function put($url, $requestParams = null) 330 | { 331 | return $this->request($url, 'PUT', $requestParams); 332 | } 333 | 334 | /** 335 | * Makes the 'POST' request to the $url with raw $data 336 | * Use this method to send raw JSON, etc. 337 | * 338 | * @param string $url 339 | * @param string $data 340 | * @return string 341 | */ 342 | public function rawPost($url, $data) 343 | { 344 | $this->prepareRawPayload($data); 345 | 346 | return $this->request($url, 'RAW_POST'); 347 | } 348 | 349 | /** 350 | * Makes the 'PUT' request to the $url with raw $data 351 | * Use this method to send raw JSON, etc. 352 | * 353 | * @param string $url 354 | * @param string $data 355 | * @return string 356 | */ 357 | public function rawPut($url, $data) 358 | { 359 | $this->prepareRawPayload($data); 360 | 361 | return $this->request($url, 'PUT'); 362 | } 363 | 364 | /** 365 | * Removes the cookie for next cURL transfer 366 | * 367 | * @param string $name Name of cookie 368 | */ 369 | public function removeCookie($name) 370 | { 371 | if (isset($this->cookies[$name])) { 372 | unset($this->cookies[$name]); 373 | } 374 | } 375 | 376 | /** 377 | * Removes the header for next cURL transfer 378 | * 379 | * @param string $header 380 | */ 381 | public function removeHeader($header) 382 | { 383 | if (isset($this->headers[$header])) { 384 | unset($this->headers[$header]); 385 | } 386 | } 387 | 388 | /** 389 | * Removes the option for next cURL transfer 390 | * 391 | * @param integer $option CURLOPT_XXX predefined constant 392 | */ 393 | public function removeOption($option) 394 | { 395 | if (isset($this->options[$option])) { 396 | unset($this->options[$option]); 397 | } 398 | } 399 | 400 | /** 401 | * Removes the request parameter for next cURL transfer 402 | * 403 | * @param string $name 404 | */ 405 | public function removeRequestParam($name) 406 | { 407 | if (isset($this->requestParams[$name])) { 408 | unset($this->requestParams[$name]); 409 | } 410 | } 411 | 412 | /** 413 | * Makes the request of the specified $method to the $url with an optional $requestParams 414 | * 415 | * @param string $url 416 | * @param string $method 417 | * @param array $requestParams 418 | * @throws CurlWrapperCurlException 419 | * @return string 420 | */ 421 | public function request($url, $method = 'GET', $requestParams = null) 422 | { 423 | $this->setURL($url); 424 | $this->setRequestMethod($method); 425 | 426 | if (!empty($requestParams)) { 427 | $this->addRequestParam($requestParams); 428 | } 429 | 430 | $this->initOptions(); 431 | $this->response = curl_exec($this->ch); 432 | 433 | if ($this->response === false) { 434 | throw new CurlWrapperCurlException($this->ch); 435 | } 436 | 437 | $this->transferInfo = curl_getinfo($this->ch); 438 | 439 | return $this->response; 440 | } 441 | 442 | /** 443 | * Reinitiates the cURL handle 444 | * IMPORTANT: headers, options, request parameters, cookies and cookies file are remain untouched! 445 | */ 446 | public function reset() 447 | { 448 | $this->__destruct(); 449 | $this->transferInfo = array(); 450 | $this->__construct(); 451 | } 452 | 453 | /** 454 | * Reinitiates the cURL handle and resets all data 455 | * Including headers, options, request parameters, cookies and cookies file 456 | */ 457 | public function resetAll() 458 | { 459 | $this->clearHeaders(); 460 | $this->clearOptions(); 461 | $this->clearRequestParams(); 462 | $this->clearCookies(); 463 | $this->clearCookieFile(); 464 | $this->reset(); 465 | } 466 | 467 | /** 468 | * Sets the number of seconds to wait while trying to connect, use 0 to wait indefinitely 469 | * 470 | * @param integer $seconds 471 | */ 472 | public function setConnectTimeOut($seconds) 473 | { 474 | $this->addOption(CURLOPT_CONNECTTIMEOUT, $seconds); 475 | } 476 | 477 | /** 478 | * Sets the filename to store cookies 479 | * 480 | * @param string $filename 481 | * @throws CurlWrapperException 482 | */ 483 | public function setCookieFile($filename) 484 | { 485 | if (!is_writable($filename)) { 486 | throw new CurlWrapperException('Cookie file "'.$filename.'" is not writable or does\'n exists!'); 487 | } 488 | 489 | $this->cookieFile = $filename; 490 | } 491 | 492 | /** 493 | * Sets the default headers 494 | */ 495 | public function setDefaultHeaders() 496 | { 497 | $this->headers = array( 498 | 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 499 | 'Accept-Charset' => 'utf-8;q=0.7,*;q=0.7', 500 | 'Accept-Language' => 'en-US,en;q=0.8', 501 | 'Accept-Encoding' => 'gzip,deflate', 502 | 'Keep-Alive' => '300', 503 | 'Connection' => 'keep-alive', 504 | 'Cache-Control' => 'max-age=0', 505 | 'Pragma' => '' 506 | ); 507 | } 508 | 509 | /** 510 | * Sets the default options 511 | */ 512 | public function setDefaultOptions() 513 | { 514 | $this->options = array( 515 | CURLOPT_RETURNTRANSFER => true, 516 | CURLOPT_HEADER => false, 517 | CURLOPT_ENCODING => 'gzip,deflate', 518 | CURLOPT_AUTOREFERER => true, 519 | CURLOPT_CONNECTTIMEOUT => 15, 520 | CURLOPT_TIMEOUT => 30, 521 | ); 522 | } 523 | 524 | /** 525 | * Sets default headers, options and user agent if $userAgent is given 526 | * 527 | * @param string $userAgent Some predefined user agent name (ie, firefox, opera, etc.) or any string you want 528 | */ 529 | public function setDefaults($userAgent = null) 530 | { 531 | $this->setDefaultHeaders(); 532 | $this->setDefaultOptions(); 533 | 534 | if (!empty($userAgent)) { 535 | $this->setUserAgent($userAgent); 536 | } else { 537 | $this->setUserAgent('chrome'); 538 | } 539 | } 540 | 541 | /** 542 | * If $value is true sets CURLOPT_FOLLOWLOCATION option to follow any "Location: " header that the server 543 | * sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers 544 | * that it is sent, unless CURLOPT_MAXREDIRS option is set). 545 | * 546 | * @param boolean $value 547 | */ 548 | public function setFollowRedirects($value) 549 | { 550 | $this->addOption(CURLOPT_FOLLOWLOCATION, $value); 551 | } 552 | 553 | /** 554 | * Sets the contents of the "Referer: " header to be used in a HTTP request 555 | * 556 | * @param string $referer 557 | */ 558 | public function setReferer($referer) 559 | { 560 | $this->addOption(CURLOPT_REFERER, $referer); 561 | } 562 | 563 | /** 564 | * Sets the maximum number of seconds to allow cURL functions to execute 565 | * 566 | * @param integer $seconds 567 | */ 568 | public function setTimeout($seconds) 569 | { 570 | $this->addOption(CURLOPT_TIMEOUT, $seconds); 571 | } 572 | 573 | /** 574 | * Sets the contents of the "User-Agent: " header to be used in a HTTP request 575 | * You can use CurlWrapper's predefined shortcuts: 'ie', 'firefox', 'opera' and 'chrome' 576 | * 577 | * @param string $userAgent 578 | */ 579 | public function setUserAgent($userAgent) 580 | { 581 | if (isset(self::$predefinedUserAgents[$userAgent])) { 582 | $this->addOption(CURLOPT_USERAGENT, self::$predefinedUserAgents[$userAgent]); 583 | } else { 584 | $this->addOption(CURLOPT_USERAGENT, $userAgent); 585 | } 586 | } 587 | 588 | /** 589 | * Sets the HTTP Authentication type. 590 | * 591 | * Defaults to CURLAUTH_BASIC. 592 | * 593 | * @param int $type 594 | */ 595 | public function setAuthType($type = CURLAUTH_BASIC) { 596 | $this->addOption(CURLOPT_HTTPAUTH, $type); 597 | } 598 | 599 | /** 600 | * Sets the username and password for HTTP Authentication. 601 | * 602 | * @param string $username 603 | * @param string $password 604 | */ 605 | public function setAuthCredentials($username, $password) { 606 | $this->addOption(CURLOPT_USERPWD, "$username:$password"); 607 | } 608 | 609 | /** 610 | * Sets the value of cookieFile to empty string 611 | */ 612 | public function unsetCookieFile() 613 | { 614 | $this->cookieFile = ''; 615 | } 616 | 617 | /** 618 | * Builds url from associative array produced by parse_str() function 619 | * 620 | * @param array $parsedUrl 621 | * @return string 622 | */ 623 | protected function buildUrl($parsedUrl) 624 | { 625 | return (isset($parsedUrl['scheme']) ? $parsedUrl["scheme"].'://' : ''). 626 | (isset($parsedUrl['user']) ? $parsedUrl["user"].':' : ''). 627 | (isset($parsedUrl['pass']) ? $parsedUrl["pass"].'@' : ''). 628 | (isset($parsedUrl['host']) ? $parsedUrl["host"] : ''). 629 | (isset($parsedUrl['port']) ? ':'.$parsedUrl["port"] : ''). 630 | (isset($parsedUrl['path']) ? $parsedUrl["path"] : ''). 631 | (isset($parsedUrl['query']) ? '?'.$parsedUrl["query"] : ''). 632 | (isset($parsedUrl['fragment']) ? '#'.$parsedUrl["fragment"] : ''); 633 | } 634 | 635 | /** 636 | * Sets the final options and prepares request params, headers and cookies 637 | * 638 | * @throws CurlWrapperCurlException 639 | */ 640 | protected function initOptions() 641 | { 642 | if (!empty($this->requestParams)) { 643 | if (isset($this->options[CURLOPT_HTTPGET])) { 644 | $this->prepareGetParams(); 645 | } else { 646 | $this->addOption(CURLOPT_POSTFIELDS, http_build_query($this->requestParams)); 647 | } 648 | } 649 | 650 | if (!empty($this->headers)) { 651 | $this->addOption(CURLOPT_HTTPHEADER, $this->prepareHeaders()); 652 | } 653 | 654 | if (!empty($this->cookieFile)) { 655 | $this->addOption(CURLOPT_COOKIEFILE, $this->cookieFile); 656 | $this->addOption(CURLOPT_COOKIEJAR, $this->cookieFile); 657 | } 658 | 659 | if (!empty($this->cookies)) { 660 | $this->addOption(CURLOPT_COOKIE, $this->prepareCookies()); 661 | } 662 | 663 | if (!curl_setopt_array($this->ch, $this->options)) { 664 | throw new CurlWrapperCurlException($this->ch); 665 | } 666 | } 667 | 668 | /** 669 | * Converts the cookies array to the correct string format 670 | * 671 | * @return string 672 | */ 673 | protected function prepareCookies() 674 | { 675 | $cookiesString = ''; 676 | 677 | foreach ($this->cookies as $cookie => $value) { 678 | $cookiesString .= $cookie.'='.$value.'; '; 679 | } 680 | 681 | return $cookiesString; 682 | } 683 | 684 | /** 685 | * Converts request parameters to the query string and adds it to the request url 686 | */ 687 | protected function prepareGetParams() 688 | { 689 | $parsedUrl = parse_url($this->options[CURLOPT_URL]); 690 | $query = http_build_query($this->requestParams); 691 | 692 | if (isset($parsedUrl['query'])) { 693 | $parsedUrl['query'] .= '&'.$query; 694 | } else { 695 | $parsedUrl['query'] = $query; 696 | } 697 | 698 | $this->setUrl($this->buildUrl($parsedUrl)); 699 | } 700 | 701 | /** 702 | * Sets up options for POST/PUT request with raw $data 703 | * 704 | * @param string $data 705 | */ 706 | protected function prepareRawPayload($data) 707 | { 708 | $this->clearRequestParams(); 709 | $this->addHeader('Content-Length', strlen($data)); 710 | $this->addOption(CURLOPT_POSTFIELDS, $data); 711 | } 712 | 713 | /** 714 | * Converts the headers array to the cURL's option format array 715 | * 716 | * @return array 717 | */ 718 | protected function prepareHeaders() 719 | { 720 | $headers = array(); 721 | 722 | foreach ($this->headers as $header => $value) { 723 | $headers[] = $header.': '.$value; 724 | } 725 | 726 | return $headers; 727 | } 728 | 729 | /** 730 | * Sets the HTTP request method 731 | * 732 | * @param string $method 733 | */ 734 | protected function setRequestMethod($method) 735 | { 736 | // Preventing request methods collision 737 | $this->removeOption(CURLOPT_NOBODY); 738 | $this->removeOption(CURLOPT_HTTPGET); 739 | $this->removeOption(CURLOPT_POST); 740 | $this->removeOption(CURLOPT_CUSTOMREQUEST); 741 | 742 | switch (strtoupper($method)) { 743 | case 'HEAD': 744 | $this->addOption(CURLOPT_NOBODY, true); 745 | break; 746 | 747 | case 'GET': 748 | $this->addOption(CURLOPT_HTTPGET, true); 749 | break; 750 | 751 | case 'POST': 752 | $this->addOption(CURLOPT_POST, true); 753 | break; 754 | 755 | case 'RAW_POST': 756 | $this->addOption(CURLOPT_CUSTOMREQUEST, 'POST'); 757 | break; 758 | 759 | default: 760 | $this->addOption(CURLOPT_CUSTOMREQUEST, $method); 761 | } 762 | } 763 | 764 | /** 765 | * Sets the request url 766 | * 767 | * @param string $url Request URL 768 | */ 769 | protected function setUrl($url) 770 | { 771 | $this->addOption(CURLOPT_URL, $url); 772 | } 773 | } 774 | 775 | /** 776 | * CurlWrapper Exceptions class 777 | */ 778 | class CurlWrapperException extends Exception 779 | { 780 | /** 781 | * @param string $message 782 | */ 783 | public function __construct($message) 784 | { 785 | $this->message = $message; 786 | } 787 | } 788 | 789 | /** 790 | * CurlWrapper cURL Exceptions class 791 | */ 792 | class CurlWrapperCurlException extends CurlWrapperException 793 | { 794 | /** 795 | * @param resource $curlHandler 796 | */ 797 | public function __construct($curlHandler) 798 | { 799 | $this->message = curl_error($curlHandler); 800 | $this->code = curl_errno($curlHandler); 801 | } 802 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010-2011, Leonid Svyatov 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | CurlWrapper 2 | =========== 3 | 4 | Flexible wrapper class for PHP cURL extension 5 | 6 | See [php.net/curl](http://php.net/curl) for more information about the libcurl extension for PHP. 7 | 8 | It's a fairly simple library, so if you want something more powerful take a look at [Guzzle](https://github.com/guzzle/guzzle). 9 | 10 | 11 | Install 12 | ------- 13 | 14 | ### via Composer (recommended) 15 | 16 | `php composer.phar require svyatov/curlwrapper '~1.3'` 17 | 18 | ### via download 19 | 20 | Just grab the [latest release](https://github.com/svyatov/CurlWrapper/releases). 21 | 22 | 23 | Usage 24 | ----- 25 | 26 | ### Initialization 27 | 28 | ```php 29 | try { 30 | $curl = new CurlWrapper(); 31 | } catch (CurlWrapperException $e) { 32 | echo $e->getMessage(); 33 | } 34 | ``` 35 | 36 | ### Performing request 37 | 38 | The CurlWrapper object supports 5 types of requests: HEAD, GET, POST, PUT, and DELETE. You must specify an url to request and optionally specify an associative array or query string of variables to send along with it. 39 | 40 | ```php 41 | $response = $curl->head($url, $params); 42 | $response = $curl->get($url, $params); 43 | $response = $curl->post($url, $params); 44 | $response = $curl->put($url, $params); 45 | $response = $curl->delete($url, $params); 46 | ``` 47 | 48 | To use a custom request methods, you can call the `request` method: 49 | 50 | ```php 51 | $response = $curl->request($url, 'ANY_CUSTOM_REQUEST_TYPE', $params); 52 | ``` 53 | 54 | 55 | Examples: 56 | 57 | ```php 58 | $response = $curl->get('google.com?q=test'); 59 | 60 | $response = $curl->get('google.com?q=test', array('some_variable' => 'some_value')); 61 | // CurlWrapper will append '&some_variable=some_value' to the url 62 | 63 | $response = $curl->post('test.com/posts', array('title' => 'Test', 'body' => 'This is a test')); 64 | ``` 65 | 66 | All requests return response body as is or throw a CurlWrapperException if an error occurred. 67 | 68 | ### Performing POST/PUT request with raw payload 69 | 70 | Some times you need to send not encoded POST params, but a raw JSON or other raw data format. 71 | 72 | ```php 73 | $response = $curl->rawPost($url, $jsonData); 74 | $response = $curl->rawPut($url, 'raw random data'); 75 | ``` 76 | 77 | Note that data is sending as as, without any URL-encoding manipulation. Keep that in mind. 78 | 79 | You might also need to change the content type header for those types of request: 80 | 81 | ```php 82 | $curl->addHeader('Content-Type', 'text/plain'); 83 | // or 84 | $curl->addHeader('Content-Type', 'application/json'); 85 | // and then 86 | $response = $curl->rawPost($url, $jsonData); 87 | ``` 88 | 89 | It depends on API server-side you are working with. 90 | 91 | 92 | ### Getting additional information about request sent 93 | 94 | ```php 95 | $info = $curl->getTransferInfo(); 96 | ``` 97 | 98 | This will give you associative array with following keys: 99 | 100 | * `url` - Last effective URL 101 | * `content_type` - Content-Type: of downloaded object, NULL indicates server did not send valid Content-Type: header 102 | * `http_code` - Last received HTTP code 103 | * `header_size` - Total size of all headers received 104 | * `request_size` - Total size of issued requests, currently only for HTTP requests 105 | * `filetime` - Remote time of the retrieved document, if -1 is returned the time of the document is unknown 106 | * `ssl_verify_result` - Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER 107 | * `redirect_count` - Number of redirects it went through if CURLOPT_FOLLOWLOCATION was set 108 | * `total_time` - Total transaction time in seconds for last transfer 109 | * `namelookup_time` - Time in seconds until name resolving was complete 110 | * `connect_time` - Time in seconds it took to establish the connection 111 | * `pretransfer_time` - Time in seconds from start until just before file transfer begins 112 | * `size_upload` - Total number of bytes uploaded 113 | * `size_download` - Total number of bytes downloaded 114 | * `speed_download` - Average download speed 115 | * `speed_upload` - Average upload speed 116 | * `download_content_length` - content-length of download, read from Content-Length: field 117 | * `upload_content_length` - Specified size of upload 118 | * `starttransfer_time` - Time in seconds until the first byte is about to be transferred 119 | * `redirect_time` - Time in seconds of all redirection steps before final transaction was started 120 | * `certinfo` - There is official description for this field yet 121 | * `request_header` - The request string sent. For this to work, add the CURLINFO_HEADER_OUT option 122 | 123 | You can also easily fetch any single piece of this array: 124 | 125 | ```php 126 | $httpCode = $curl->getTransferInfo('http_code'); 127 | ``` 128 | 129 | 130 | ### Cookie sessions 131 | 132 | To maintain a session across requests and cookies support you must set file's name where cookies to store: 133 | 134 | ```php 135 | $curl->setCookieFile('some_file_name.txt'); 136 | ``` 137 | 138 | This file must be writable or the CurlWrapperException will be thrown. 139 | 140 | 141 | ### Basic configuration options 142 | 143 | You can easily set the referer, user-agent, timeout and whether or not follow redirects: 144 | 145 | ```php 146 | $curl->setReferer('http://google.com'); 147 | $curl->setUserAgent('some user agent string'); 148 | $curl->setTimeout(15); // seconds 149 | $curl->setFollowRedirects(true); // to follow redirects 150 | ``` 151 | 152 | ### HTTP Basic Authentication 153 | 154 | You can set a username and password for use in HTTP basic auth: 155 | ```php 156 | $curl->setAuthType(); 157 | $curl->setAuthCredentials('username', 'password'); 158 | ``` 159 | 160 | ### Setting custom headers 161 | 162 | You can set custom headers to send with the request: 163 | 164 | ```php 165 | $curl->addHeader('Host', '98.52.78.243'); 166 | $curl->addHeader('Some-Custom-Header', 'Some Custom Value'); 167 | ``` 168 | 169 | Or use a single array: 170 | 171 | ```php 172 | $curl->addHeader(array('Host'=>'98.52.78.243', 'Some-Custom-Header'=>'Some Custom Value')); 173 | ``` 174 | 175 | 176 | ### Setting custom cURL options 177 | 178 | You can set/override any cURL option (see the [curl_setopt documentation](http://www.php.net/manual/en/function.curl-setopt.php) for a list of them): 179 | 180 | ```php 181 | $curl->addOption(CURLOPT_AUTOREFERER, true); 182 | ``` 183 | 184 | 185 | Changelog 186 | --------- 187 | 188 | * **v1.3.0** 189 | 190 | `new` added *setAuthType()* and *setAuthCredentials()* methods for HTTP basic authentication 191 | 192 | * **v1.2.0** 193 | 194 | `new` added *rawPost()* and *rawPut()* methods for POST/PUT requests with raw payload 195 | 196 | `new` added *setFollowRedirects()* method for quick access to cURL *CURLOPT_FOLLOWLOCATION* option 197 | 198 | Contributing 199 | ------------ 200 | 201 | 1. Fork it 202 | 2. Create your feature branch (`git checkout -b my-new-feature`) 203 | 3. Commit your changes (`git commit -am 'Added some feature'`) 204 | 4. Push to the branch (`git push origin my-new-feature`) 205 | 5. Create new Pull Request 206 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "svyatov/curlwrapper", 3 | "type": "library", 4 | "description": "Flexible wrapper class for PHP cURL extension", 5 | "keywords": ["curl","http","util","helper"], 6 | "homepage": "https://github.com/svyatov/CurlWrapper", 7 | "license": "MIT", 8 | "authors": [ 9 | { 10 | "name": "Leonid Svyatov", 11 | "email": "leonid@svyatov.ru", 12 | "homepage": "http://svyatov.ru", 13 | "role": "Developer" 14 | } 15 | ], 16 | "support": { 17 | "email": "leonid@svyatov.ru", 18 | "issues": "https://github.com/svyatov/CurlWrapper/issues", 19 | "source": "https://github.com/svyatov/CurlWrapper" 20 | }, 21 | "require": { 22 | "php": ">=5.3.2" 23 | }, 24 | "autoload": { 25 | "classmap": ["CurlWrapper.php"] 26 | } 27 | } --------------------------------------------------------------------------------