FastSitePHP\Net\HttpClient

HTTP Client

This class provides a simple and secure API and wraps either CURL or PHP Stream Context depending on what is available. Common HTTP requests can be made with one line of code using static helper functions.

Source Code

GitHub

Example Code

Using the HTTP Client

// The HttpClient can be used to simplify communication with other Web Services,
// HTTP API’s, and works great for calling and returning the result of local
// services – for example an AI/ML (Artificial Intelligence / Machine Learning)
// Service written in Python with TensorFlow or scikit-learn.

// Perform a simple HTTP GET Request and check the result
$res = \FastSitePHP\Net\HttpClient::get($url);
if ($res->error) {
    // An error would be returned in the event of a major failure such as
    // a timeout or SSL Cert Error. A 404 or 500 Response from the server
    // would be handled by checking the [status_code].
    $error = $res->error;
} else {
    $status_code = $res->status_code; // 200, 404, 500, etc
    $headers = $res->headers; // Array of Response Headers
    $content = $res->content; // Response Content as a String - HTML, Text, etc
    $info = $res->info; // Array of Info such as Time Stats
}

// Perform an HTTP GET Request and read the JSON Result. If the Response
// Content-Type is 'application/json' then [$res->json] will contain an array
// otherwise null. Request Headers can be passed an optional paramater.
$headers = [
    'X-API-Key' => 'ab82050cf5907934fa1d0f6f66284642a01d1ba2280656870c',
    'X-Custom-Header' => 'Test',
];
$res_json = \FastSitePHP\Net\HttpClient::get($url, $headers);
$json = $res->json;
$text = $res->content;

// Submit a HTTP POST Request as JSON and also as a Form.
// Data can be either an Array or Object and Headers are optional.
$data = [
    'text' => 'test',
    'num' => 123,
];
$res_post = \FastSitePHP\Net\HttpClient::postJson($url, $data, $headers);
$res_form = \FastSitePHP\Net\HttpClient::postForm($url, $data);

// When using PHP 5.5 or later 'multipart/form-data' Form Posts are supported
// with the PHP built-in class [CURLFile]:
/*
$data = [
    'field1' => 'test',
    'file' => new \CURLFile($file_path),
];
*/

// Save the Response Content as a File Download
// Just like [postJson()] and [postForm()] Request Headers are optional.
$res_file = \FastSitePHP\Net\HttpClient::downloadFile($url, $save_path, $headers);
$saved_path = $res_file->content;

// The above code demo shows the 4 helper static functions [get(), postJson(),
// postForm(), and downloadFile()], additional options are available when using
// the HttpClient as an object with the [request()] method.

// Submit a PUT Request with a file as the Request Body
$http = new \FastSitePHP\Net\HttpClient();
$res_put = $http->request($url, [
    'method' => 'PUT',
    'headers' => $headers,
    'send_file' => $file_path,
]);

Properties

Name Data Type Default Description
cainfo_path string
(Static)
__DIR__ . '/cacert.pem' Some OS's (often Windows and Mac) will not support HTTPS by default unless a file is downloaded and [php.ini] is updated outside of PHP. The downloaded file handles [HTTPS] validation. A copy of the file [cacert.pem] is included in this directory in case it doesn't exist on the OS, however the file needs to be updated from time to time to keep current. This property allows an app to specify it's own version of the file in another directory.
allow_insecure bool
(Static)
false Allow HTTPS to be ignored. This should only be used as last resort in trusted environments as it breaks security. Instead it is better to set [HttpClient::$cainfo_path].

Methods

get($url, array $headers = null)

Static Function

Submit a GET Request and optionally specify an array of Request Headers.

Returns: HttpResponse

postJson($url, $data, array $headers = null)

Static Function

Submit a POST Request with JSON Data as the Request Body.

Returns: HttpResponse

postForm($url, $fields, array $headers = null)

Static Function

Submit a POST Request with Form Data. If sending a form with files and form type 'multipart/form-data' use the PHP class CURLFile. See examples for more.

Returns: HttpResponse

downloadFile($url, $path, array $headers = null)

Static Function

Submit a GET Request and save the Response Body to a file. [HttpResponse->content] will contain the saved file path.

Returns: HttpResponse

request($url, array $options = null)

Submit a Request and return an HttpResponse object.

Options:
  'mode' = null or 'curl' or 'php'
      Defaults to null which uses curl. This option is defined for unit testing. Leaving the default works best.
  'method' = 'GET', 'POST', 'PUT', etc
      Defaults to 'GET'
  'headers' = Array of Request Headears [key => value]
  'json' = Array or Object of Data to send with the Request
  'form' = Array or Object of Form Data, see additional comments in [postForm()]
  'send_file' = Full path of a file to send as the Request Body
  'save_file' = Full path where to save the response, if set then [HttpResponse->content] will contain the saved file path
  'timeout' = Timeout in Seconds
      Defaults to 0 which means the code stops until the request completes.
      When using curl mode this value applies to both the inital connection and the curl request.
  'parse_json' = true/false - By default if a JSON response is returned the [$res->content]
      will be parsed to [$res->json] as an Associative Array. It can be turned off by setting this to false

Returns: HttpResponse

certPath()

Return the location for the [cacert.pem] file (the name can vary from system to system). Also see comments in for static property [cainfo_path].

Returns: string