HTTP Request/Response Package for PHP 5.4+
Use example.php to test:
// load HTTP package files
require_once './lib/Http/Request.php';
require_once './lib/Http/Response.php';
try
{
// create new HTTP request object
$req = new \Http\Request('htp://www.example.com/');
// set request params example:
$req->param('var1', 'value_1');
$req->param('var2', 'value_2');
// set HTTP Response object with HTTP GET request
$res = $req->get();
if($res->is_success) // 200/OK
{
echo 'Response code: ' . $res->getResponseCode() . ', '; // ex: 200
echo 'Response headers: ' . print_r($res->getHeaders(), true) . ', '; // array of headers
echo 'Total seconds taken: ' . $res->getElapsedTime() . ', '; // total seconds for request
echo 'Response string: ' . $res->getResponseString();
}
else if($res->is_error) // print error
{
echo 'Error: ' . $res->error;
}
}
catch(\Exception $ex)
{
echo 'Exception: ' . $ex->getMessage();
}
For a HTTP POST request example simply change the call method to:
...
// set HTTP Response object with HTTP POST request
$res = $req->post();
...
For a HTTP HEAD request example simply change the call method to:
...
// set HTTP Response object with HTTP HEAD request
$res = $req->head();
...
The HTTP Response class has several other helpful methods
This method returns the headers in an objects so header data can be accessed like:
$headers = $res->getHeadersObject();
echo 'Server type: ' . $headers->server;
Gets the original request URL with query string (if relates to request method type)
This method can be used to check the count of any value or regex pattern in the response string, for example:
echo 'Match count: ' . $res->match('keyword'); // total count
// or use regex pattern like /x/
echo 'Match count: ' . $res->match('/keyword/i'); // total count
This method is used to extract data from the response string based on regex pattern, for example:
// get array of all strings that have 'keyword' and end with '.'
$extracted_data = $res->extract('/keyword[^\.]+\./i');
// and can use callback to modify array strings, like removing all HTML tags from strings:
$extracted_clean = $res->extract('/keyword[^\.]+\./i', function($v) { return strip_tags($v); });
HTTP Request properties can be used to change HTTP request options
A custom referer can be set using:
$req->referer = 'http://www.example.com';
The request timeout (in seconds) can be modified using:
$req->timeout_seconds = 10;
By default the HTTP package uses the file_get_contents() function for HTTP requests, this can be change to use the cURL library using the option:
$req->use_curl = true;
A custom user agent can be set using:
$req->user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8';