The Show This class is modeled after the Guzzle HTTP Client library since it is one of the more widely used libraries. Where possible, the syntax has been kept the same so that if your application needs something a little more powerful than what this library provides, you will have to change very little to move over to use Guzzle. Note This class requires the cURL Library to be installed in your version of PHP. This is a very common library that is typically available but not all hosts will provide it, so please check with your host to verify if you run into problems. Config for CURLRequestSharing OptionsDue to historical reasons, by default, the CURLRequest shares all the options between requests. If you send more than one request with an instance of the class, this behavior may cause an error request with unnecessary headers and body. You can change the behavior by editing the following config parameter value in app/Config/CURLRequest.php to <?php namespace Config; use CodeIgniter\Config\BaseConfig; class CURLRequest extends BaseConfig { public $shareOptions = false; // ... } Note Before v4.2.0, the request body is not reset even if Loading the LibraryThe library can be loaded either manually or through the Services class. To load with the Services class call the <?php $client = \Config\Services::curlrequest(); You can pass in an array of default options as the first parameter to modify how cURL will handle the request. The options are described later in this document: <?php $options = [ 'baseURI' => 'http://example.com/api/v1/', 'timeout' => 3, ]; $client = \Config\Services::curlrequest($options); Note When When creating the class manually, you need to pass a few dependencies in. The first parameter is an instance of the <?php $client = new \CodeIgniter\HTTP\CURLRequest( new \Config\App(), new \CodeIgniter\HTTP\URI(), new \CodeIgniter\HTTP\Response(new \Config\App()), $options ); Working with the LibraryWorking with CURL requests is simply a matter of creating the Request and getting a Response object back. It is meant to handle the communications. After that you have complete control over how the information is handled. Making RequestsMost communication is done through the <?php $client = \Config\Services::curlrequest(); $response = $client->request('GET', 'https://api.github.com/user', [ 'auth' => ['user', 'pass'], ]); Note When Since the response is an instance of <?php echo $response->getStatusCode(); echo $response->getBody(); echo $response->getHeader('Content-Type'); $language = $response->negotiateLanguage(['en', 'fr']); While the <?php $client->get('http://example.com'); $client->delete('http://example.com'); $client->head('http://example.com'); $client->options('http://example.com'); $client->patch('http://example.com'); $client->put('http://example.com'); $client->post('http://example.com'); Base URIA <?php $client = \Config\Services::curlrequest([ 'baseURI' => 'https://example.com/api/v1/', ]); // GET http:example.com/api/v1/photos $client->get('photos'); // GET http:example.com/api/v1/photos/13 $client->delete('photos/13'); When a relative URI is provided to the
Using ResponsesEach You can get the status code and reason phrase of the response: <?php $code = $response->getStatusCode(); // 200 $reason = $response->getReason(); // OK You can retrieve headers from the response: <?php // Get a header line echo $response->getHeaderLine('Content-Type'); // Get all headers foreach ($response->getHeaders() as $name => $value) { echo $name . ': ' . $response->getHeaderLine($name) . "\n"; } The body can be retrieved using the <?php $body = $response->getBody(); The body is the raw body provided by the remote server. If the content type requires formatting, you will need to ensure that your script handles that: <?php if (strpos($response->getHeader('content-type'), 'application/json') !== false) { $body = json_decode($body); } Request OptionsThis section describes all of the available options you may pass into the constructor, the allow_redirectsBy default, cURL will follow all “Location:” headers the remote servers send back. The If you set the value to <?php $client->request('GET', 'http://example.com', ['allow_redirects' => false]); Setting it to <?php $client->request('GET', 'http://example.com', ['allow_redirects' => true]); /* * Sets the following defaults: * 'max' => 5, // Maximum number of redirects to follow before stopping * 'strict' => true, // Ensure POST requests stay POST requests through redirects * 'protocols' => ['http', 'https'] // Restrict redirects to one or more protocols */ You can pass in array as the value of the <?php $client->request('GET', 'http://example.com', ['allow_redirects' => [ 'max' => 10, 'protocols' => ['https'], // Force HTTPS domains only. ]]); Note Following redirects does not work when PHP is in safe_mode or open_basedir is enabled. authAllows you to provide Authentication details for HTTP Basic and Digest and authentication. Your script may
have to do extra to support Digest authentication - this simply passes the username and password along for you. The value must be an array where the first element is the username, and the second is the password. The third parameter should be the type of authentication to use, either <?php $client->request('GET', 'http://example.com', ['auth' => ['username', 'password', 'digest']]); bodyThere are two ways to set the body of the request for request types that support them, like PUT, OR POST. The first way is to use the <?php $client->setBody($body)->request('put', 'http://example.com'); The second method is by passing a <?php $client->request('put', 'http://example.com', ['body' => $body]); certTo specify the location of a PEM formatted
client-side certificate, pass a string with the full path to the file as the <?php $client->request('get', '/', ['cert' => ['/path/server.pem', 'password']]); connect_timeoutBy default, CodeIgniter does not impose a limit for cURL to attempt to connect to a website. If you need to modify this value, you can do so by passing the amount of time in seconds with the <?php $client->request('GET', 'http://example.com', ['connect_timeout' => 0]); cookieThis specifies the filename that CURL should use to read cookie values from, and to save cookie values to. This is done using the CURL_COOKIEJAR and CURL_COOKIEFILE options. An example: <?php $client->request('GET', 'http://example.com', ['cookie' => WRITEPATH . 'CookieSaver.txt']); debugWhen <?php $client->request('GET', 'http://example.com', ['debug' => true]); You can pass a filename as the value for debug to have the output written to a file: <?php $client->request('GET', 'http://example.com', ['debug' => '/usr/local/curl_log.txt']); delayAllows you to pause a number of milliseconds before sending the request: <?php // Delay for 2 seconds $client->request('GET', 'http://example.com', ['delay' => 2000]); form_paramsYou can send form data in an application/x-www-form-urlencoded POST request by passing an associative array in the <?php $client->request('POST', '/post', [ 'form_params' => [ 'foo' => 'bar', 'baz' => ['hi', 'there'], ], ]);
Note
http_errorsBy
default, CURLRequest will fail if the HTTP code returned is greater than or equal to 400. You can set <?php $client->request('GET', '/status/500'); // Will fail verbosely $res = $client->request('GET', '/status/500', ['http_errors' => false]); echo $res->getStatusCode(); // 500 jsonThe <?php $response = $client->request('PUT', '/put', ['json' => ['foo' => 'bar']]); Note This option does not allow for any customization of the multipartWhen you need to send files and other data via a POST request, you can use the <?php $post_data = [ 'foo' => 'bar', 'userfile' => new \CURLFile('/path/to/file.txt'), ]; Note
queryYou can pass along data to send as query string variables by passing an associative array
as the <?php // Send a GET request to /get?foo=bar $client->request('GET', '/get', ['query' => ['foo' => 'bar']]); timeoutBy default, cURL functions are allowed to run as long as they take, with no time limit. You can modify this with the <?php $client->request('GET', 'http://example.com', ['timeout' => 5]); user_agentAllows specifying the User Agent for requests: <?php $client->request('GET', 'http://example.com', ['user_agent' => 'CodeIgniter Framework v4']); verifyThis option describes the SSL certificate verification behavior. If the <?php // Use the system's CA bundle (this is the default setting) $client->request('GET', '/', ['verify' => true]); // Use a custom SSL certificate on disk. $client->request('GET', '/', ['verify' => '/path/to/cert.pem']); // Disable validation entirely. (Insecure!) $client->request('GET', '/', ['verify' => false]); versionTo set the HTTP protocol to use, you can pass a string or float with the version number (typically either 1.0 or 1.1, 2.0 is currently unsupported.): <?php // Force HTTP/1.0 $client->request('GET', '/', ['version' => 1.0]); |