From 1d796f105961947ee754d403ae53b64a691a372d Mon Sep 17 00:00:00 2001 From: Rafael de Barcelos Date: Sat, 22 Mar 2014 20:31:52 -0300 Subject: [PATCH 01/10] Namespace added --- lib/Shuber/LibCurl/Curl.php | 279 +++++++++++++++++++++++++++ lib/Shuber/LibCurl/CurlException.php | 83 ++++++++ lib/Shuber/LibCurl/CurlResponse.php | 83 ++++++++ 3 files changed, 445 insertions(+) create mode 100644 lib/Shuber/LibCurl/Curl.php create mode 100644 lib/Shuber/LibCurl/CurlException.php create mode 100644 lib/Shuber/LibCurl/CurlResponse.php diff --git a/lib/Shuber/LibCurl/Curl.php b/lib/Shuber/LibCurl/Curl.php new file mode 100644 index 0000000..d89fddd --- /dev/null +++ b/lib/Shuber/LibCurl/Curl.php @@ -0,0 +1,279 @@ + +**/ +class Curl { + + /** + * The file to read and write cookies to for requests + * + * @var string + **/ + public $cookie_file; + + /** + * Determines whether or not requests should follow redirects + * + * @var boolean + **/ + public $follow_redirects = true; + + /** + * An associative array of headers to send along with requests + * + * @var array + **/ + public $headers = array(); + + /** + * An associative array of CURLOPT options to send along with requests + * + * @var array + **/ + public $options = array(); + + /** + * The referer header to send along with requests + * + * @var string + **/ + public $referer; + + /** + * The user agent to send along with requests + * + * @var string + **/ + public $user_agent; + + /** + * Stores resource handle for the current CURL request + * + * @var resource + * @access protected + **/ + protected $request; + + /** + * Stores the HTTP auth credentials + * + * @var $userpwd + * @access protected + **/ + protected $userpwd; + + /** + * Initializes a Curl object + * + * Sets the $cookie_file to "curl_cookie.txt" in the current directory + * Also sets the $user_agent to $_SERVER['HTTP_USER_AGENT'] if it exists, 'Curl/PHP '.PHP_VERSION.' (http://github.com/shuber/curl)' otherwise + **/ + function __construct() { + $this->cookie_file = dirname(__FILE__).DIRECTORY_SEPARATOR.'curl_cookie.txt'; + $this->user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Curl/PHP '.PHP_VERSION.' (http://github.com/shuber/curl)'; + } + + /** + * Makes an HTTP DELETE request to the specified $url with an optional array or string of $vars + * + * Returns a CurlResponse object if the request was successful, false otherwise + * + * @param string $url + * @param array|string $vars + * @return CurlResponse object + **/ + function delete($url, $vars = array()) { + return $this->request('DELETE', $url, $vars); + } + + /** + * Makes an HTTP GET request to the specified $url with an optional array or string of $vars + * + * Returns a CurlResponse object if the request was successful, false otherwise + * + * @param string $url + * @param array|string $vars + * @return CurlResponse + **/ + function get($url, $vars = array()) { + if (!empty($vars)) { + $url .= (stripos($url, '?') !== false) ? '&' : '?'; + $url .= (is_string($vars)) ? $vars : http_build_query($vars, '', '&'); + } + return $this->request('GET', $url); + } + + /** + * Makes an HTTP HEAD request to the specified $url with an optional array or string of $vars + * + * Returns a CurlResponse object if the request was successful, false otherwise + * + * @param string $url + * @param array|string $vars + * @return CurlResponse + **/ + function head($url, $vars = array()) { + return $this->request('HEAD', $url, $vars); + } + + /** + * Makes an HTTP POST request to the specified $url with an optional array or string of $vars + * + * @param string $url + * @param array|string $vars + * @return CurlResponse|boolean + **/ + function post($url, $vars = array(), $enctype = NULL) { + return $this->request('POST', $url, $vars, $enctype); + } + + /** + * Makes an HTTP PUT request to the specified $url with an optional array or string of $vars + * + * Returns a CurlResponse object if the request was successful, false otherwise + * + * @param string $url + * @param array|string $vars + * @return CurlResponse|boolean + **/ + function put($url, $vars = array()) { + return $this->request('PUT', $url, $vars); + } + + /** + * Makes an HTTP request of the specified $method to a $url with an optional array or string of $vars + * + * Returns a CurlResponse object if the request was successful, false otherwise + * + * @param string $method + * @param string $url + * @param array|string $vars + * @return CurlResponse|boolean + **/ + function request($method, $url, $vars = array(), $enctype = null) { + $this->request = curl_init(); + if (is_array($vars) && $enctype != 'multipart/form-data') $vars = http_build_query($vars, '', '&'); + + $this->set_request_method($method); + $this->set_request_options($url, $vars); + $this->set_request_headers(); + + $response = curl_exec($this->request); + if (!$response) { + throw new CurlException(curl_error($this->request), curl_errno($this->request)); + } + + $response = new CurlResponse($response); + + curl_close($this->request); + + return $response; + } + + /** + * Sets the user and password for HTTP auth basic authentication method. + * + * @param string|null $username + * @param string|null $password + * @return Curl + */ + function setAuth($username, $password=null) + { + if (null === $username) { + $this->userpwd = null; + return $this; + } + + $this->userpwd = $username.':'.$password; + return $this; + } + + /** + * Formats and adds custom headers to the current request + * + * @return void + * @access protected + **/ + protected function set_request_headers() { + $headers = array(); + foreach ($this->headers as $key => $value) { + $headers[] = $key.': '.$value; + } + curl_setopt($this->request, CURLOPT_HTTPHEADER, $headers); + } + + /** + * Set the associated CURL options for a request method + * + * @param string $method + * @return void + * @access protected + **/ + protected function set_request_method($method) { + switch (strtoupper($method)) { + case 'HEAD': + curl_setopt($this->request, CURLOPT_NOBODY, true); + break; + case 'GET': + curl_setopt($this->request, CURLOPT_HTTPGET, true); + break; + case 'POST': + curl_setopt($this->request, CURLOPT_POST, true); + break; + default: + curl_setopt($this->request, CURLOPT_CUSTOMREQUEST, $method); + } + } + + /** + * Sets the CURLOPT options for the current request + * + * @param string $url + * @param string $vars + * @return void + * @access protected + **/ + protected function set_request_options($url, $vars) { + curl_setopt($this->request, CURLOPT_URL, $url); + if (!empty($vars)) curl_setopt($this->request, CURLOPT_POSTFIELDS, $vars); + + # Set some default CURL options + curl_setopt($this->request, CURLOPT_HEADER, true); + curl_setopt($this->request, CURLOPT_RETURNTRANSFER, true); + curl_setopt($this->request, CURLOPT_USERAGENT, $this->user_agent); + if ($this->cookie_file) { + curl_setopt($this->request, CURLOPT_COOKIEFILE, $this->cookie_file); + curl_setopt($this->request, CURLOPT_COOKIEJAR, $this->cookie_file); + } + if ($this->follow_redirects) curl_setopt($this->request, CURLOPT_FOLLOWLOCATION, true); + if ($this->referer) curl_setopt($this->request, CURLOPT_REFERER, $this->referer); + if ($this->userpwd) { + curl_setopt($this->request, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + curl_setopt($this->request, CURLOPT_USERPWD, $this->userpwd); + } else { + curl_setopt($this->request, CURLOPT_HTTPAUTH, false); + } + + # Set any custom CURL options + foreach ($this->options as $option => $value) { + curl_setopt($this->request, constant('CURLOPT_'.str_replace('CURLOPT_', '', strtoupper($option))), $value); + } + } + + /** + * Returns an associative array of curl options + * currently configured. + * + * @return array Associative array of curl options + */ + function get_request_options() { + return curl_getinfo( $this->request ); + } + +} \ No newline at end of file diff --git a/lib/Shuber/LibCurl/CurlException.php b/lib/Shuber/LibCurl/CurlException.php new file mode 100644 index 0000000..625bada --- /dev/null +++ b/lib/Shuber/LibCurl/CurlException.php @@ -0,0 +1,83 @@ + 'CURLE_ABORTED_BY_CALLBACK', + CURLE_BAD_CALLING_ORDER => 'CURLE_BAD_CALLING_ORDER', + CURLE_BAD_CONTENT_ENCODING => 'CURLE_BAD_CONTENT_ENCODING', + CURLE_BAD_FUNCTION_ARGUMENT => 'CURLE_BAD_FUNCTION_ARGUMENT', + CURLE_BAD_PASSWORD_ENTERED => 'CURLE_BAD_PASSWORD_ENTERED', + CURLE_COULDNT_CONNECT => 'CURLE_COULDNT_CONNECT', + CURLE_COULDNT_RESOLVE_HOST => 'CURLE_COULDNT_RESOLVE_HOST', + CURLE_COULDNT_RESOLVE_PROXY => 'CURLE_COULDNT_RESOLVE_PROXY', + CURLE_FAILED_INIT => 'CURLE_FAILED_INIT', + CURLE_FILE_COULDNT_READ_FILE => 'CURLE_FILE_COULDNT_READ_FILE', + CURLE_FILESIZE_EXCEEDED => 'CURLE_FILESIZE_EXCEEDED', + CURLE_FTP_ACCESS_DENIED => 'CURLE_FTP_ACCESS_DENIED', + CURLE_FTP_BAD_DOWNLOAD_RESUME => 'CURLE_FTP_BAD_DOWNLOAD_RESUME', + CURLE_FTP_CANT_GET_HOST => 'CURLE_FTP_CANT_GET_HOST', + CURLE_FTP_CANT_RECONNECT => 'CURLE_FTP_CANT_RECONNECT', + CURLE_FTP_COULDNT_GET_SIZE => 'CURLE_FTP_COULDNT_GET_SIZE', + CURLE_FTP_COULDNT_RETR_FILE => 'CURLE_FTP_COULDNT_RETR_FILE', + CURLE_FTP_COULDNT_SET_ASCII => 'CURLE_FTP_COULDNT_SET_ASCII', + CURLE_FTP_COULDNT_SET_BINARY => 'CURLE_FTP_COULDNT_SET_BINARY', + CURLE_FTP_COULDNT_STOR_FILE => 'CURLE_FTP_COULDNT_STOR_FILE', + CURLE_FTP_COULDNT_USE_REST => 'CURLE_FTP_COULDNT_USE_REST', + CURLE_FTP_PORT_FAILED => 'CURLE_FTP_PORT_FAILED', + CURLE_FTP_QUOTE_ERROR => 'CURLE_FTP_QUOTE_ERROR', + CURLE_FTP_SSL_FAILED => 'CURLE_FTP_SSL_FAILED', + CURLE_FTP_USER_PASSWORD_INCORRECT => 'CURLE_FTP_USER_PASSWORD_INCORRECT', + CURLE_FTP_WEIRD_227_FORMAT => 'CURLE_FTP_WEIRD_227_FORMAT', + CURLE_FTP_WEIRD_PASS_REPLY => 'CURLE_FTP_WEIRD_PASS_REPLY', + CURLE_FTP_WEIRD_PASV_REPLY => 'CURLE_FTP_WEIRD_PASV_REPLY', + CURLE_FTP_WEIRD_SERVER_REPLY => 'CURLE_FTP_WEIRD_SERVER_REPLY', + CURLE_FTP_WEIRD_USER_REPLY => 'CURLE_FTP_WEIRD_USER_REPLY', + CURLE_FTP_WRITE_ERROR => 'CURLE_FTP_WRITE_ERROR', + CURLE_FUNCTION_NOT_FOUND => 'CURLE_FUNCTION_NOT_FOUND', + CURLE_GOT_NOTHING => 'CURLE_GOT_NOTHING', + CURLE_HTTP_NOT_FOUND => 'CURLE_HTTP_NOT_FOUND', + CURLE_HTTP_PORT_FAILED => 'CURLE_HTTP_PORT_FAILED', + CURLE_HTTP_POST_ERROR => 'CURLE_HTTP_POST_ERROR', + CURLE_HTTP_RANGE_ERROR => 'CURLE_HTTP_RANGE_ERROR', + CURLE_LDAP_CANNOT_BIND => 'CURLE_LDAP_CANNOT_BIND', + CURLE_LDAP_INVALID_URL => 'CURLE_LDAP_INVALID_URL', + CURLE_LDAP_SEARCH_FAILED => 'CURLE_LDAP_SEARCH_FAILED', + CURLE_LIBRARY_NOT_FOUND => 'CURLE_LIBRARY_NOT_FOUND', + CURLE_MALFORMAT_USER => 'CURLE_MALFORMAT_USER', + CURLE_OBSOLETE => 'CURLE_OBSOLETE', + CURLE_OPERATION_TIMEOUTED => 'CURLE_OPERATION_TIMEOUTED', + CURLE_OUT_OF_MEMORY => 'CURLE_OUT_OF_MEMORY', + CURLE_PARTIAL_FILE => 'CURLE_PARTIAL_FILE', + CURLE_READ_ERROR => 'CURLE_READ_ERROR', + CURLE_RECV_ERROR => 'CURLE_RECV_ERROR', + CURLE_SEND_ERROR => 'CURLE_SEND_ERROR', + CURLE_SHARE_IN_USE => 'CURLE_SHARE_IN_USE', + CURLE_SSH => 'CURLE_SSH', + CURLE_SSL_CACERT => 'CURLE_SSL_CACERT', + CURLE_SSL_CERTPROBLEM => 'CURLE_SSL_CERTPROBLEM', + CURLE_SSL_CIPHER => 'CURLE_SSL_CIPHER', + CURLE_SSL_CONNECT_ERROR => 'CURLE_SSL_CONNECT_ERROR', + CURLE_SSL_ENGINE_NOTFOUND => 'CURLE_SSL_ENGINE_NOTFOUND', + CURLE_SSL_ENGINE_SETFAILED => 'CURLE_SSL_ENGINE_SETFAILED', + CURLE_SSL_PEER_CERTIFICATE => 'CURLE_SSL_PEER_CERTIFICATE', + CURLE_TELNET_OPTION_SYNTAX => 'CURLE_TELNET_OPTION_SYNTAX', + CURLE_TOO_MANY_REDIRECTS => 'CURLE_TOO_MANY_REDIRECTS', + CURLE_UNKNOWN_TELNET_OPTION => 'CURLE_UNKNOWN_TELNET_OPTION', + CURLE_UNSUPPORTED_PROTOCOL => 'CURLE_UNSUPPORTED_PROTOCOL', + CURLE_URL_MALFORMAT => 'CURLE_URL_MALFORMAT', + CURLE_URL_MALFORMAT_USER => 'CURLE_URL_MALFORMAT_USER', + CURLE_WRITE_ERROR => 'CURLE_WRITE_ERROR' + ); + + function __construct( $curl_error_message, $curl_error_code ) + { + if( ! array_key_exists( $curl_error_code, self::$curl_errors ) ) + throw new Exception( "Unknown \$curl_error_code: $curl_error_code" ); + + parent::__construct( self::$curl_errors[$curl_error_code].": $curl_error_message", $curl_error_code ); + } + +} \ No newline at end of file diff --git a/lib/Shuber/LibCurl/CurlResponse.php b/lib/Shuber/LibCurl/CurlResponse.php new file mode 100644 index 0000000..e865921 --- /dev/null +++ b/lib/Shuber/LibCurl/CurlResponse.php @@ -0,0 +1,83 @@ + +**/ +class CurlResponse { + + /** + * The body of the response without the headers block + * + * @var string + **/ + public $body = ''; + + /** + * An associative array containing the response's headers + * + * @var array + **/ + public $headers = array(); + + /** + * Accepts the result of a curl request as a string + * + * + * $response = new CurlResponse(curl_exec($curl_handle)); + * echo $response->body; + * echo $response->headers['Status']; + * + * + * @param string $response + **/ + function __construct($response) { + # Headers regex + $pattern = '#HTTP/\d\.\d.*?$.*?\r\n\r\n#ims'; + + # Extract headers from response + preg_match_all($pattern, $response, $matches); + $headers_string = array_pop($matches[0]); + $headers = explode("\r\n", str_replace("\r\n\r\n", '', $headers_string)); + + # Inlude all received headers in the $headers_string + while (count($matches[0])) { + $headers_string = array_pop($matches[0]).$headers_string; + } + + # Remove all headers from the response body + $this->body = str_replace($headers_string, '', $response); + + # Extract the version and status from the first header + $version_and_status = array_shift($headers); + preg_match_all('#HTTP/(\d\.\d)\s((\d\d\d)\s((.*?)(?=HTTP)|.*))#', $version_and_status, $matches); + $this->headers['Http-Version'] = array_pop($matches[1]); + $this->headers['Status-Code'] = array_pop($matches[3]); + $this->headers['Status'] = array_pop($matches[2]); + + # Convert headers into an associative array + foreach ($headers as $header) { + preg_match('#(.*?)\:\s(.*)#', $header, $matches); + $this->headers[$matches[1]] = $matches[2]; + } + } + + /** + * Returns the response body + * + * + * $curl = new Curl; + * $response = $curl->get('google.com'); + * echo $response; # => echo $response->body; + * + * + * @return string + **/ + function __toString() { + return $this->body; + } + +} \ No newline at end of file From 9e1d63098544ac452437984d93c7519ffba78236 Mon Sep 17 00:00:00 2001 From: Rafael de Barcelos Date: Sat, 22 Mar 2014 20:33:20 -0300 Subject: [PATCH 02/10] Updated docummentation --- README.md | 154 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..c85496e --- /dev/null +++ b/README.md @@ -0,0 +1,154 @@ +# curl + +A basic CURL wrapper for PHP (see [http://php.net/curl](http://php.net/curl) for more information about the libcurl extension for PHP) + + +## Installation + +### Installing with the composer: + +Add composer.json package in your project file or create a new file. +```json +{ + "require":{ + "shuber/curl": "dev-master" + } +} +``` +Get the composer and install, or run the updater. +```bash +curl -sS https://getcomposer.org/installer | php +php composer.phar install +``` + +## Usage + +### Initialization + +Simply require the `Autoload` and initialize the object: + + require_once 'vendor/autoload.php'; + use Shuber\LibCurl as Curl; + $curl = new Curl\Curl(); + + +### Performing a Request + +The Curl object supports 5 types of requests: HEAD, GET, POST, PUT, and DELETE. You must specify a url to request and optionally specify an associative array or string of variables to send along with it. + + $response = $curl->head($url, $vars = array()); + $response = $curl->get($url, $vars = array()); # The Curl object will append the array of $vars to the $url as a query string + $response = $curl->post($url, $vars = array()); + $response = $curl->put($url, $vars = array()); + $response = $curl->delete($url, $vars = array()); + +To use a custom request methods, you can call the `request` method: + + $response = $curl->request('YOUR_CUSTOM_REQUEST_TYPE', $url, $vars = array()); + +All of the built in request methods like `put` and `get` simply wrap the `request` method. For example, the `post` method is implemented like: + + function post($url, $vars = array()) { + return $this->request('POST', $url, $vars); + } + +Examples: + + $response = $curl->get('google.com?q=test'); + + # The Curl object will append '&some_variable=some_value' to the url + $response = $curl->get('google.com?q=test', array('some_variable' => 'some_value')); + + $response = $curl->post('test.com/posts', array('title' => 'Test', 'body' => 'This is a test')); + +All requests return a CurlResponse object (see below) or false if an error occurred. You can access the error string with the `$curl->error()` method. + + +### The CurlResponse Object + +A normal CURL request will return the headers and the body in one response string. This class parses the two and places them into separate properties. + +For example + + $response = $curl->get('google.com'); + echo $response->body; # A string containing everything in the response except for the headers + print_r($response->headers); # An associative array containing the response headers + +Which would display something like + + + + Google.com + + + Some more html... + + + + Array + ( + [Http-Version] => 1.0 + [Status-Code] => 200 + [Status] => 200 OK + [Cache-Control] => private + [Content-Type] => text/html; charset=ISO-8859-1 + [Date] => Wed, 07 May 2008 21:43:48 GMT + [Server] => gws + [Connection] => close + ) + +The CurlResponse class defines the magic [__toString()](http://php.net/__toString) method which will return the response body, so `echo $response` is the same as `echo $response->body` + + +### Cookie Sessions + +By default, cookies will be stored in a file called `curl_cookie.txt`. You can change this file's name by setting it like this + + $curl->cookie_file = 'some_other_filename'; + +This allows you to maintain a session across requests + + +### Basic Configuration Options + +You can easily set the referer or user-agent + + $curl->referer = 'http://google.com'; + $curl->user_agent = 'some user agent string'; + +You may even set these headers manually if you wish (see below) + + +### Setting Custom Headers + +You can set custom headers to send with the request + + $curl->headers['Host'] = 12.345.678.90; + $curl->headers['Some-Custom-Header'] = 'Some Custom Value'; + + +### Setting Custom CURL request options + +By default, the `Curl` object will follow redirects. You can disable this by setting: + + $curl->follow_redirects = false; + +You can set/override many different options for CURL requests (see the [curl_setopt documentation](http://php.net/curl_setopt) for a list of them) + + # any of these will work + $curl->options['AUTOREFERER'] = true; + $curl->options['autoreferer'] = true; + $curl->options['CURLOPT_AUTOREFERER'] = true; + $curl->options['curlopt_autoreferer'] = true; + + +## Testing + +Uses [ztest](http://github.com/jaz303/ztest), simply download it to `path/to/curl/test/ztest` (or anywhere else in your php include_path) + +Then run `test/runner.php` + + +## Contact + +Problems, comments, and suggestions all welcome: [shuber@huberry.com](mailto:shuber@huberry.com) \ No newline at end of file From 1df4a6a27f02aad270f2b4961537c576b800c889 Mon Sep 17 00:00:00 2001 From: Rafael de Barcelos Date: Sat, 22 Mar 2014 20:34:10 -0300 Subject: [PATCH 03/10] Updated composer.php --- composer.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 8f0df6e..bc66a3f 100644 --- a/composer.json +++ b/composer.json @@ -5,6 +5,8 @@ "type": "library", "description": "PHP Wrapper for Curl", "autoload": { - "files": ["curl.php"] + "psr-0" : { + "":"lib/" + } } } \ No newline at end of file From b4d2ed8377364e5112b4f5c13b66032c48cea763 Mon Sep 17 00:00:00 2001 From: Rafael de Barcelos Maciel Date: Sat, 22 Mar 2014 20:37:23 -0300 Subject: [PATCH 04/10] Delete .gitignore --- .gitignore | 1 - 1 file changed, 1 deletion(-) delete mode 100644 .gitignore diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 609ae46..0000000 --- a/.gitignore +++ /dev/null @@ -1 +0,0 @@ -lib/curl_cookie.txt \ No newline at end of file From 238efe779f5fe4b1902b471457b6145a93d1a409 Mon Sep 17 00:00:00 2001 From: Rafael de Barcelos Maciel Date: Sat, 22 Mar 2014 20:37:37 -0300 Subject: [PATCH 05/10] Delete curl.php --- curl.php | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 curl.php diff --git a/curl.php b/curl.php deleted file mode 100644 index a41c113..0000000 --- a/curl.php +++ /dev/null @@ -1,5 +0,0 @@ - Date: Sat, 22 Mar 2014 20:38:06 -0300 Subject: [PATCH 06/10] Delete .gitmodules --- .gitmodules | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 .gitmodules diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index c782e85..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "test/ztest"] - path = test/ztest - url = git://github.com/jaz303/ztest.git From 0702a9cb2385d41c214a1d5189bdd7e9ad2f1927 Mon Sep 17 00:00:00 2001 From: Rafael de Barcelos Maciel Date: Sat, 22 Mar 2014 20:38:30 -0300 Subject: [PATCH 07/10] Delete README.markdown --- README.markdown | 140 ------------------------------------------------ 1 file changed, 140 deletions(-) delete mode 100644 README.markdown diff --git a/README.markdown b/README.markdown deleted file mode 100644 index 743e538..0000000 --- a/README.markdown +++ /dev/null @@ -1,140 +0,0 @@ -# curl - -A basic CURL wrapper for PHP (see [http://php.net/curl](http://php.net/curl) for more information about the libcurl extension for PHP) - - -## Installation - -Click the `download` link above or `git clone git://github.com/shuber/curl.git` - - -## Usage - -### Initialization - -Simply require and initialize the `Curl` class like so: - - require_once 'curl.php'; - $curl = new Curl; - - -### Performing a Request - -The Curl object supports 5 types of requests: HEAD, GET, POST, PUT, and DELETE. You must specify a url to request and optionally specify an associative array or string of variables to send along with it. - - $response = $curl->head($url, $vars = array()); - $response = $curl->get($url, $vars = array()); # The Curl object will append the array of $vars to the $url as a query string - $response = $curl->post($url, $vars = array()); - $response = $curl->put($url, $vars = array()); - $response = $curl->delete($url, $vars = array()); - -To use a custom request methods, you can call the `request` method: - - $response = $curl->request('YOUR_CUSTOM_REQUEST_TYPE', $url, $vars = array()); - -All of the built in request methods like `put` and `get` simply wrap the `request` method. For example, the `post` method is implemented like: - - function post($url, $vars = array()) { - return $this->request('POST', $url, $vars); - } - -Examples: - - $response = $curl->get('google.com?q=test'); - - # The Curl object will append '&some_variable=some_value' to the url - $response = $curl->get('google.com?q=test', array('some_variable' => 'some_value')); - - $response = $curl->post('test.com/posts', array('title' => 'Test', 'body' => 'This is a test')); - -All requests return a CurlResponse object (see below) or false if an error occurred. You can access the error string with the `$curl->error()` method. - - -### The CurlResponse Object - -A normal CURL request will return the headers and the body in one response string. This class parses the two and places them into separate properties. - -For example - - $response = $curl->get('google.com'); - echo $response->body; # A string containing everything in the response except for the headers - print_r($response->headers); # An associative array containing the response headers - -Which would display something like - - - - Google.com - - - Some more html... - - - - Array - ( - [Http-Version] => 1.0 - [Status-Code] => 200 - [Status] => 200 OK - [Cache-Control] => private - [Content-Type] => text/html; charset=ISO-8859-1 - [Date] => Wed, 07 May 2008 21:43:48 GMT - [Server] => gws - [Connection] => close - ) - -The CurlResponse class defines the magic [__toString()](http://php.net/__toString) method which will return the response body, so `echo $response` is the same as `echo $response->body` - - -### Cookie Sessions - -By default, cookies will be stored in a file called `curl_cookie.txt`. You can change this file's name by setting it like this - - $curl->cookie_file = 'some_other_filename'; - -This allows you to maintain a session across requests - - -### Basic Configuration Options - -You can easily set the referer or user-agent - - $curl->referer = 'http://google.com'; - $curl->user_agent = 'some user agent string'; - -You may even set these headers manually if you wish (see below) - - -### Setting Custom Headers - -You can set custom headers to send with the request - - $curl->headers['Host'] = 12.345.678.90; - $curl->headers['Some-Custom-Header'] = 'Some Custom Value'; - - -### Setting Custom CURL request options - -By default, the `Curl` object will follow redirects. You can disable this by setting: - - $curl->follow_redirects = false; - -You can set/override many different options for CURL requests (see the [curl_setopt documentation](http://php.net/curl_setopt) for a list of them) - - # any of these will work - $curl->options['AUTOREFERER'] = true; - $curl->options['autoreferer'] = true; - $curl->options['CURLOPT_AUTOREFERER'] = true; - $curl->options['curlopt_autoreferer'] = true; - - -## Testing - -Uses [ztest](http://github.com/jaz303/ztest), simply download it to `path/to/curl/test/ztest` (or anywhere else in your php include_path) - -Then run `test/runner.php` - - -## Contact - -Problems, comments, and suggestions all welcome: [shuber@huberry.com](mailto:shuber@huberry.com) \ No newline at end of file From 2aafa5b3c6b1b561f948c2b8fe76abd7970267af Mon Sep 17 00:00:00 2001 From: Rafael de Barcelos Maciel Date: Sat, 22 Mar 2014 20:38:53 -0300 Subject: [PATCH 08/10] Delete curl.php --- lib/curl.php | 279 --------------------------------------------------- 1 file changed, 279 deletions(-) delete mode 100644 lib/curl.php diff --git a/lib/curl.php b/lib/curl.php deleted file mode 100644 index b5d0991..0000000 --- a/lib/curl.php +++ /dev/null @@ -1,279 +0,0 @@ - -**/ -class Curl { - - /** - * The file to read and write cookies to for requests - * - * @var string - **/ - public $cookie_file; - - /** - * Determines whether or not requests should follow redirects - * - * @var boolean - **/ - public $follow_redirects = true; - - /** - * An associative array of headers to send along with requests - * - * @var array - **/ - public $headers = array(); - - /** - * An associative array of CURLOPT options to send along with requests - * - * @var array - **/ - public $options = array(); - - /** - * The referer header to send along with requests - * - * @var string - **/ - public $referer; - - /** - * The user agent to send along with requests - * - * @var string - **/ - public $user_agent; - - /** - * Stores resource handle for the current CURL request - * - * @var resource - * @access protected - **/ - protected $request; - - /** - * Stores the HTTP auth credentials - * - * @var $userpwd - * @access protected - **/ - protected $userpwd; - - /** - * Initializes a Curl object - * - * Sets the $cookie_file to "curl_cookie.txt" in the current directory - * Also sets the $user_agent to $_SERVER['HTTP_USER_AGENT'] if it exists, 'Curl/PHP '.PHP_VERSION.' (http://github.com/shuber/curl)' otherwise - **/ - function __construct() { - $this->cookie_file = dirname(__FILE__).DIRECTORY_SEPARATOR.'curl_cookie.txt'; - $this->user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Curl/PHP '.PHP_VERSION.' (http://github.com/shuber/curl)'; - } - - /** - * Makes an HTTP DELETE request to the specified $url with an optional array or string of $vars - * - * Returns a CurlResponse object if the request was successful, false otherwise - * - * @param string $url - * @param array|string $vars - * @return CurlResponse object - **/ - function delete($url, $vars = array()) { - return $this->request('DELETE', $url, $vars); - } - - /** - * Makes an HTTP GET request to the specified $url with an optional array or string of $vars - * - * Returns a CurlResponse object if the request was successful, false otherwise - * - * @param string $url - * @param array|string $vars - * @return CurlResponse - **/ - function get($url, $vars = array()) { - if (!empty($vars)) { - $url .= (stripos($url, '?') !== false) ? '&' : '?'; - $url .= (is_string($vars)) ? $vars : http_build_query($vars, '', '&'); - } - return $this->request('GET', $url); - } - - /** - * Makes an HTTP HEAD request to the specified $url with an optional array or string of $vars - * - * Returns a CurlResponse object if the request was successful, false otherwise - * - * @param string $url - * @param array|string $vars - * @return CurlResponse - **/ - function head($url, $vars = array()) { - return $this->request('HEAD', $url, $vars); - } - - /** - * Makes an HTTP POST request to the specified $url with an optional array or string of $vars - * - * @param string $url - * @param array|string $vars - * @return CurlResponse|boolean - **/ - function post($url, $vars = array(), $enctype = NULL) { - return $this->request('POST', $url, $vars, $enctype); - } - - /** - * Makes an HTTP PUT request to the specified $url with an optional array or string of $vars - * - * Returns a CurlResponse object if the request was successful, false otherwise - * - * @param string $url - * @param array|string $vars - * @return CurlResponse|boolean - **/ - function put($url, $vars = array()) { - return $this->request('PUT', $url, $vars); - } - - /** - * Makes an HTTP request of the specified $method to a $url with an optional array or string of $vars - * - * Returns a CurlResponse object if the request was successful, false otherwise - * - * @param string $method - * @param string $url - * @param array|string $vars - * @return CurlResponse|boolean - **/ - function request($method, $url, $vars = array(), $enctype = null) { - $this->request = curl_init(); - if (is_array($vars) && $enctype != 'multipart/form-data') $vars = http_build_query($vars, '', '&'); - - $this->set_request_method($method); - $this->set_request_options($url, $vars); - $this->set_request_headers(); - - $response = curl_exec($this->request); - if (!$response) { - throw new CurlException(curl_error($this->request), curl_errno($this->request)); - } - - $response = new CurlResponse($response); - - curl_close($this->request); - - return $response; - } - - /** - * Sets the user and password for HTTP auth basic authentication method. - * - * @param string|null $username - * @param string|null $password - * @return Curl - */ - function setAuth($username, $password=null) - { - if (null === $username) { - $this->userpwd = null; - return $this; - } - - $this->userpwd = $username.':'.$password; - return $this; - } - - /** - * Formats and adds custom headers to the current request - * - * @return void - * @access protected - **/ - protected function set_request_headers() { - $headers = array(); - foreach ($this->headers as $key => $value) { - $headers[] = $key.': '.$value; - } - curl_setopt($this->request, CURLOPT_HTTPHEADER, $headers); - } - - /** - * Set the associated CURL options for a request method - * - * @param string $method - * @return void - * @access protected - **/ - protected function set_request_method($method) { - switch (strtoupper($method)) { - case 'HEAD': - curl_setopt($this->request, CURLOPT_NOBODY, true); - break; - case 'GET': - curl_setopt($this->request, CURLOPT_HTTPGET, true); - break; - case 'POST': - curl_setopt($this->request, CURLOPT_POST, true); - break; - default: - curl_setopt($this->request, CURLOPT_CUSTOMREQUEST, $method); - } - } - - /** - * Sets the CURLOPT options for the current request - * - * @param string $url - * @param string $vars - * @return void - * @access protected - **/ - protected function set_request_options($url, $vars) { - curl_setopt($this->request, CURLOPT_URL, $url); - if (!empty($vars)) curl_setopt($this->request, CURLOPT_POSTFIELDS, $vars); - - # Set some default CURL options - curl_setopt($this->request, CURLOPT_HEADER, true); - curl_setopt($this->request, CURLOPT_RETURNTRANSFER, true); - curl_setopt($this->request, CURLOPT_USERAGENT, $this->user_agent); - if ($this->cookie_file) { - curl_setopt($this->request, CURLOPT_COOKIEFILE, $this->cookie_file); - curl_setopt($this->request, CURLOPT_COOKIEJAR, $this->cookie_file); - } - if ($this->follow_redirects) curl_setopt($this->request, CURLOPT_FOLLOWLOCATION, true); - if ($this->referer) curl_setopt($this->request, CURLOPT_REFERER, $this->referer); - if ($this->userpwd) { - curl_setopt($this->request, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); - curl_setopt($this->request, CURLOPT_USERPWD, $this->userpwd); - } else { - curl_setopt($this->request, CURLOPT_HTTPAUTH, false); - } - - # Set any custom CURL options - foreach ($this->options as $option => $value) { - curl_setopt($this->request, constant('CURLOPT_'.str_replace('CURLOPT_', '', strtoupper($option))), $value); - } - } - - /** - * Returns an associative array of curl options - * currently configured. - * - * @return array Associative array of curl options - */ - function get_request_options() { - return curl_getinfo( $this->request ); - } - -} \ No newline at end of file From 97e71473cde6df273bc800dd3deb9108457e9d4e Mon Sep 17 00:00:00 2001 From: Rafael de Barcelos Maciel Date: Sat, 22 Mar 2014 20:39:04 -0300 Subject: [PATCH 09/10] Delete curl_exception.php --- lib/curl_exception.php | 82 ------------------------------------------ 1 file changed, 82 deletions(-) delete mode 100644 lib/curl_exception.php diff --git a/lib/curl_exception.php b/lib/curl_exception.php deleted file mode 100644 index 9313fc0..0000000 --- a/lib/curl_exception.php +++ /dev/null @@ -1,82 +0,0 @@ - 'CURLE_ABORTED_BY_CALLBACK', - CURLE_BAD_CALLING_ORDER => 'CURLE_BAD_CALLING_ORDER', - CURLE_BAD_CONTENT_ENCODING => 'CURLE_BAD_CONTENT_ENCODING', - CURLE_BAD_FUNCTION_ARGUMENT => 'CURLE_BAD_FUNCTION_ARGUMENT', - CURLE_BAD_PASSWORD_ENTERED => 'CURLE_BAD_PASSWORD_ENTERED', - CURLE_COULDNT_CONNECT => 'CURLE_COULDNT_CONNECT', - CURLE_COULDNT_RESOLVE_HOST => 'CURLE_COULDNT_RESOLVE_HOST', - CURLE_COULDNT_RESOLVE_PROXY => 'CURLE_COULDNT_RESOLVE_PROXY', - CURLE_FAILED_INIT => 'CURLE_FAILED_INIT', - CURLE_FILE_COULDNT_READ_FILE => 'CURLE_FILE_COULDNT_READ_FILE', - CURLE_FILESIZE_EXCEEDED => 'CURLE_FILESIZE_EXCEEDED', - CURLE_FTP_ACCESS_DENIED => 'CURLE_FTP_ACCESS_DENIED', - CURLE_FTP_BAD_DOWNLOAD_RESUME => 'CURLE_FTP_BAD_DOWNLOAD_RESUME', - CURLE_FTP_CANT_GET_HOST => 'CURLE_FTP_CANT_GET_HOST', - CURLE_FTP_CANT_RECONNECT => 'CURLE_FTP_CANT_RECONNECT', - CURLE_FTP_COULDNT_GET_SIZE => 'CURLE_FTP_COULDNT_GET_SIZE', - CURLE_FTP_COULDNT_RETR_FILE => 'CURLE_FTP_COULDNT_RETR_FILE', - CURLE_FTP_COULDNT_SET_ASCII => 'CURLE_FTP_COULDNT_SET_ASCII', - CURLE_FTP_COULDNT_SET_BINARY => 'CURLE_FTP_COULDNT_SET_BINARY', - CURLE_FTP_COULDNT_STOR_FILE => 'CURLE_FTP_COULDNT_STOR_FILE', - CURLE_FTP_COULDNT_USE_REST => 'CURLE_FTP_COULDNT_USE_REST', - CURLE_FTP_PORT_FAILED => 'CURLE_FTP_PORT_FAILED', - CURLE_FTP_QUOTE_ERROR => 'CURLE_FTP_QUOTE_ERROR', - CURLE_FTP_SSL_FAILED => 'CURLE_FTP_SSL_FAILED', - CURLE_FTP_USER_PASSWORD_INCORRECT => 'CURLE_FTP_USER_PASSWORD_INCORRECT', - CURLE_FTP_WEIRD_227_FORMAT => 'CURLE_FTP_WEIRD_227_FORMAT', - CURLE_FTP_WEIRD_PASS_REPLY => 'CURLE_FTP_WEIRD_PASS_REPLY', - CURLE_FTP_WEIRD_PASV_REPLY => 'CURLE_FTP_WEIRD_PASV_REPLY', - CURLE_FTP_WEIRD_SERVER_REPLY => 'CURLE_FTP_WEIRD_SERVER_REPLY', - CURLE_FTP_WEIRD_USER_REPLY => 'CURLE_FTP_WEIRD_USER_REPLY', - CURLE_FTP_WRITE_ERROR => 'CURLE_FTP_WRITE_ERROR', - CURLE_FUNCTION_NOT_FOUND => 'CURLE_FUNCTION_NOT_FOUND', - CURLE_GOT_NOTHING => 'CURLE_GOT_NOTHING', - CURLE_HTTP_NOT_FOUND => 'CURLE_HTTP_NOT_FOUND', - CURLE_HTTP_PORT_FAILED => 'CURLE_HTTP_PORT_FAILED', - CURLE_HTTP_POST_ERROR => 'CURLE_HTTP_POST_ERROR', - CURLE_HTTP_RANGE_ERROR => 'CURLE_HTTP_RANGE_ERROR', - CURLE_LDAP_CANNOT_BIND => 'CURLE_LDAP_CANNOT_BIND', - CURLE_LDAP_INVALID_URL => 'CURLE_LDAP_INVALID_URL', - CURLE_LDAP_SEARCH_FAILED => 'CURLE_LDAP_SEARCH_FAILED', - CURLE_LIBRARY_NOT_FOUND => 'CURLE_LIBRARY_NOT_FOUND', - CURLE_MALFORMAT_USER => 'CURLE_MALFORMAT_USER', - CURLE_OBSOLETE => 'CURLE_OBSOLETE', - CURLE_OPERATION_TIMEOUTED => 'CURLE_OPERATION_TIMEOUTED', - CURLE_OUT_OF_MEMORY => 'CURLE_OUT_OF_MEMORY', - CURLE_PARTIAL_FILE => 'CURLE_PARTIAL_FILE', - CURLE_READ_ERROR => 'CURLE_READ_ERROR', - CURLE_RECV_ERROR => 'CURLE_RECV_ERROR', - CURLE_SEND_ERROR => 'CURLE_SEND_ERROR', - CURLE_SHARE_IN_USE => 'CURLE_SHARE_IN_USE', - CURLE_SSH => 'CURLE_SSH', - CURLE_SSL_CACERT => 'CURLE_SSL_CACERT', - CURLE_SSL_CERTPROBLEM => 'CURLE_SSL_CERTPROBLEM', - CURLE_SSL_CIPHER => 'CURLE_SSL_CIPHER', - CURLE_SSL_CONNECT_ERROR => 'CURLE_SSL_CONNECT_ERROR', - CURLE_SSL_ENGINE_NOTFOUND => 'CURLE_SSL_ENGINE_NOTFOUND', - CURLE_SSL_ENGINE_SETFAILED => 'CURLE_SSL_ENGINE_SETFAILED', - CURLE_SSL_PEER_CERTIFICATE => 'CURLE_SSL_PEER_CERTIFICATE', - CURLE_TELNET_OPTION_SYNTAX => 'CURLE_TELNET_OPTION_SYNTAX', - CURLE_TOO_MANY_REDIRECTS => 'CURLE_TOO_MANY_REDIRECTS', - CURLE_UNKNOWN_TELNET_OPTION => 'CURLE_UNKNOWN_TELNET_OPTION', - CURLE_UNSUPPORTED_PROTOCOL => 'CURLE_UNSUPPORTED_PROTOCOL', - CURLE_URL_MALFORMAT => 'CURLE_URL_MALFORMAT', - CURLE_URL_MALFORMAT_USER => 'CURLE_URL_MALFORMAT_USER', - CURLE_WRITE_ERROR => 'CURLE_WRITE_ERROR' - ); - - function __construct( $curl_error_message, $curl_error_code ) - { - if( ! array_key_exists( $curl_error_code, self::$curl_errors ) ) - throw new Exception( "Unknown \$curl_error_code: $curl_error_code" ); - - parent::__construct( self::$curl_errors[$curl_error_code].": $curl_error_message", $curl_error_code ); - } - -} \ No newline at end of file From 790d9dd5d52dc840535c4cec94f42f63624f4a5b Mon Sep 17 00:00:00 2001 From: Rafael de Barcelos Maciel Date: Sat, 22 Mar 2014 20:39:12 -0300 Subject: [PATCH 10/10] Delete curl_response.php --- lib/curl_response.php | 83 ------------------------------------------- 1 file changed, 83 deletions(-) delete mode 100644 lib/curl_response.php diff --git a/lib/curl_response.php b/lib/curl_response.php deleted file mode 100644 index a1b07b2..0000000 --- a/lib/curl_response.php +++ /dev/null @@ -1,83 +0,0 @@ - -**/ -class CurlResponse { - - /** - * The body of the response without the headers block - * - * @var string - **/ - public $body = ''; - - /** - * An associative array containing the response's headers - * - * @var array - **/ - public $headers = array(); - - /** - * Accepts the result of a curl request as a string - * - * - * $response = new CurlResponse(curl_exec($curl_handle)); - * echo $response->body; - * echo $response->headers['Status']; - * - * - * @param string $response - **/ - function __construct($response) { - # Headers regex - $pattern = '#HTTP/\d\.\d.*?$.*?\r\n\r\n#ims'; - - # Extract headers from response - preg_match_all($pattern, $response, $matches); - $headers_string = array_pop($matches[0]); - $headers = explode("\r\n", str_replace("\r\n\r\n", '', $headers_string)); - - # Inlude all received headers in the $headers_string - while (count($matches[0])) { - $headers_string = array_pop($matches[0]).$headers_string; - } - - # Remove all headers from the response body - $this->body = str_replace($headers_string, '', $response); - - # Extract the version and status from the first header - $version_and_status = array_shift($headers); - preg_match_all('#HTTP/(\d\.\d)\s((\d\d\d)\s((.*?)(?=HTTP)|.*))#', $version_and_status, $matches); - $this->headers['Http-Version'] = array_pop($matches[1]); - $this->headers['Status-Code'] = array_pop($matches[3]); - $this->headers['Status'] = array_pop($matches[2]); - - # Convert headers into an associative array - foreach ($headers as $header) { - preg_match('#(.*?)\:\s(.*)#', $header, $matches); - $this->headers[$matches[1]] = $matches[2]; - } - } - - /** - * Returns the response body - * - * - * $curl = new Curl; - * $response = $curl->get('google.com'); - * echo $response; # => echo $response->body; - * - * - * @return string - **/ - function __toString() { - return $this->body; - } - -} \ No newline at end of file