The HttpRequestHelper
class in JiFramework provides a simple and convenient way to perform HTTP requests within your application. It utilizes PHP's cURL extension to send GET, POST, and custom HTTP method requests to specified URLs. The class allows you to set custom headers, manage SSL verification, set timeouts, and retrieve response data along with HTTP status codes.
By using the HttpRequestHelper
, developers can interact with external APIs, web services, or any HTTP endpoints efficiently, handling both synchronous requests and basic error handling.
Usage:
// Option 1: Initialize the HttpRequestHelper through the App
use JIFramework\Core\App\App;
$app = new App();
$http = $app->httpRequest;
OR
// Option 2: Directly instantiate the HttpRequestHelper
use JIFramework\Core\Network\HttpRequestHelper;
$http = new HttpRequestHelper();
Method: httpPostRequest(string $url, array $postData = [], array $options = []): array|false
Description: Performs an HTTP POST request to a specified URL with optional data and configurations.
Parameters:
- $url (
string
): The URL to which the request will be sent. - $postData (
array
, optional): An associative array of data to be sent in the POST request body. - $options (
array
, optional): Additional options for the request, including: - 'headers' (
array
): An array of custom HTTP headers to include in the request. - 'ssl_verify' (
bool
): Whether to verify SSL certificates (true
by default). - 'timeout' (
int
): The maximum number of seconds to allow cURL functions to execute.
Returns: An associative array containing:
- 'status_code' (
int
): The HTTP status code returned by the server. - 'body' (
string
): The response body from the target URL.
Returns false
on failure.
Usage:
$url = 'https://api.example.com/login';
$postData = [
'username' => 'user123',
'password' => 'pass123',
];
$options = [
'headers' => [
'Content-Type: application/x-www-form-urlencoded',
],
'timeout' => 30,
];
$response = $http->httpPostRequest($url, $postData, $options);
if ($response !== false) {
echo 'Status Code: ' . $response['status_code'] . "\n";
echo 'Response Body: ' . $response['body'];
} else {
echo 'HTTP POST Request failed.';
}
Explanation:
- Initializes the
HttpRequestHelper
class. - Sets the URL and POST data.
- Specifies custom headers and timeout in options.
- Calls
httpPostRequest
to perform the POST request. - Checks if the response is not
false
, then processes the response. - If the request fails, outputs an error message.
Method: httpGetRequest(string $url, array $options = []): array|false
Description: Performs an HTTP GET request to a specified URL with optional configurations.
Parameters:
- $url (
string
): The URL from which the data will be retrieved. - $options (
array
, optional): Additional options for the request, including: - 'headers' (
array
): An array of custom HTTP headers to include in the request. - 'ssl_verify' (
bool
): Whether to verify SSL certificates (true
by default). - 'timeout' (
int
): The maximum number of seconds to allow cURL functions to execute.
Returns: An associative array containing:
- 'status_code' (
int
): The HTTP status code returned by the server. - 'body' (
string
): The response body from the target URL.
Returns false
on failure.
Usage:
$url = 'https://api.example.com/users';
$options = [
'headers' => [
'Accept: application/json',
],
'timeout' => 20,
];
$response = $http->httpGetRequest($url, $options);
if ($response !== false) {
echo 'Status Code: ' . $response['status_code'] . "\n";
echo 'Response Body: ' . $response['body'];
} else {
echo 'HTTP GET Request failed.';
}
Explanation:
- Initializes the
HttpRequestHelper
class. - Sets the URL to perform the GET request.
- Provides custom headers and timeout in options.
- Calls
httpGetRequest
to perform the GET request. - Checks if the response is not
false
, then processes the response. - If the request fails, outputs an error message.
Method: httpRequest(string $method, string $url, array $data = [], array $options = []): array|false
Description: Performs an HTTP request with a custom method (e.g., PUT, DELETE) to a specified URL with optional data and configurations.
Parameters:
- $method (
string
): The HTTP method to use (e.g., 'GET', 'POST', 'PUT', 'DELETE'). - $url (
string
): The URL to which the request will be sent. - $data (
array
, optional): An associative array of data to send with the request. - $options (
array
, optional): Additional options for the request, including: - 'headers' (
array
): An array of custom HTTP headers to include in the request. - 'ssl_verify' (
bool
): Whether to verify SSL certificates (true
by default). - 'timeout' (
int
): The maximum number of seconds to allow cURL functions to execute.
Returns: An associative array containing:
- 'status_code' (
int
): The HTTP status code returned by the server. - 'body' (
string
): The response body from the target URL.
Returns false
on failure.
Usage:
$method = 'PUT';
$url = 'https://api.example.com/users/123';
$data = [
'email' => '[email protected]',
];
$options = [
'headers' => [
'Content-Type: application/json',
'Authorization: Bearer your_token_here',
],
'ssl_verify' => true,
'timeout' => 25,
];
$response = $http->httpRequest($method, $url, $data, $options);
if ($response !== false) {
echo 'Status Code: ' . $response['status_code'] . "\n";
echo 'Response Body: ' . $response['body'];
} else {
echo 'HTTP Request failed.';
}
Explanation:
- Initializes the
HttpRequestHelper
class. - Sets the HTTP method, URL, and data to send.
- Provides custom headers, enables SSL verification, and sets a timeout.
- Calls
httpRequest
to perform the custom HTTP request. - Checks if the response is not
false
, then processes the response. - If the request fails, outputs an error message.
Example 1: Simple GET Request
$response = $http->httpGetRequest('https://api.example.com/data');
if ($response !== false) {
echo 'Response: ' . $response['body'];
} else {
echo 'Failed to retrieve data.';
}
Explanation:
- Performs a simple HTTP GET request without any additional options.
- Processes the response body if the request is successful.
Example 2: POST Request with JSON Data
$url = 'https://api.example.com/create';
$postData = json_encode([
'name' => 'New Item',
'description' => 'Description of the new item',
]);
$options = [
'headers' => [
'Content-Type: application/json',
],
'ssl_verify' => false, // Disable SSL verification (not recommended in production)
];
$response = $http->httpPostRequest($url, $postData, $options);
if ($response !== false) {
echo 'Item created successfully.';
} else {
echo 'Failed to create item.';
}
Explanation:
- Sends a POST request with JSON-encoded data.
- Sets the
Content-Type
header toapplication/json
. - Disables SSL verification (use with caution).
Example 3: DELETE Request with Custom Headers
$method = 'DELETE';
$url = 'https://api.example.com/items/456';
$options = [
'headers' => [
'Authorization: Bearer your_token_here',
],
];
$response = $http->httpRequest($method, $url, [], $options);
if ($response !== false && $response['status_code'] === 204) {
echo 'Item deleted successfully.';
} else {
echo 'Failed to delete item.';
}
Explanation:
- Performs a DELETE request to remove an item.
- Includes an
Authorization
header with a bearer token. - Checks for a
204 No Content
status code to confirm deletion.
Additional Information:
Options Parameter
The $options
parameter in each method allows you to customize the HTTP request further. Available options include:
- 'headers' (
array
): Custom HTTP headers to send with the request. - 'ssl_verify' (
bool
): Controls SSL certificate verification. true
(default): SSL certificates are verified.false
: SSL certificates are not verified (not recommended for production).- 'timeout' (
int
): Sets the maximum time in seconds for the request to complete.
SSL Verification
- By default, SSL verification is enabled for security.
- Disabling SSL verification (
'ssl_verify' => false
) is not recommended, especially in production environments, as it makes the request susceptible to man-in-the-middle attacks.
Error Handling
- If a cURL error occurs during the request (e.g., network issues, DNS resolution failure), the method returns
false
. - The methods do not throw exceptions; they return
false
on failure. - To get detailed error information, you may modify the methods to capture
curl_error($curl)
and handle it accordingly.
HTTP Status Codes
- The response array includes the
'status_code'
key, which contains the HTTP status code returned by the server. - Use the status code to determine the outcome of the request (e.g.,
200 OK
,404 Not Found
,500 Internal Server Error
).
Data Encoding
- For POST and custom methods, data is encoded using
http_build_query()
by default. - If sending JSON data, encode the data manually using
json_encode()
and set the appropriateContent-Type
header.