Skip to content

HTTP Class Documentation

Benyamin Khalife edited this page Jul 12, 2023 · 2 revisions

The Http class provides a set of methods for sending HTTP requests. It supports POST and GET requests, as well as sending JSON data.

Methods

post($url, $params = [], $customCurl = null)

Sends a POST request to the specified URL with optional parameters.

  • $url (string): The URL to send the request to.
  • $params (array): Optional parameters to include in the request. Default is an empty array.
  • $customCurl (callable|null): A custom function that can be used to modify the CURL options before the request is sent. Default is null.

Example usage:

$response = Http::post('https://example.com/api', ['name' => 'John', 'age' => 25]);

get($url, $params = [], $customCurl = null)

Sends a GET request to the specified URL with optional parameters.

  • $url (string): The URL to send the request to.
  • $params (array): Optional parameters to include in the request. Default is an empty array.
  • $customCurl (callable|null): A custom function that can be used to modify the CURL options before the request is sent. Default is null.

Example usage:

$response = Http::get('https://example.com/api', ['id' => 123]);

json($url, $params = [])

Sends a JSON request to the specified URL.

  • $url (string): The URL to send the request to.
  • $params (array): Optional parameters to include in the request. Default is an empty array.

Example usage:

$response = Http::json('https://example.com/api', ['name' => 'John', 'age' => 25]);

ip()

Retrieves the client's IP address.

Example usage:

$clientIp = Http::ip();

Example

Here's an example that demonstrates how to use the Http class:

// Sending a POST request
$result = Http::post('https://example.com/api', ['name' => 'John', 'email' => 'john@example.com']);
echo $result;

// Sending a GET request
$result = Http::get('https://example.com/api', ['id' => 123]);
echo $result;

// Sending a JSON request
$result = Http::json('https://example.com/api', ['name' => 'John', 'age' => 25]);
echo $result;

// Getting the client's IP address
$clientIp = Http::ip();
echo "Client IP: $clientIp";

Certainly! Here's an example of using the $customCurl parameter to customize the CURL options before sending a request:

// Send a POST request with custom CURL options
$response = Http::post('https://example.com/api', ['name' => 'John'], function ($ch) {
  // Set timeout to 10 seconds
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);

  // Enable verbose output
  curl_setopt($ch, CURLOPT_VERBOSE, true);
});
echo $response;

In this example, the $customCurlOptions function sets an additional CURL option to set the timeout to 10 seconds and enable verbose output. This custom function is passed as the third argument to the post method.

Please note that the Http class requires the cURL extension to be enabled in your PHP installation.