PHP HTTP CURL request example

When building APIs in PHP application, you need to send request to external server. To send request to external servers, there are several methods. If your response contains json response or you want to send async request, then you will need CURL to send request.

CURL is tool to transfer data using various network protocols. In this article, we will see examples of CURL request methods.

GET request

Get is simple type request compare to other request. To send get request in CURL, create curl variable.

Example:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://hackthestuff.com/api/auth' . '?id=1&name=hackthestuff'); // set query data here with the url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);

// checking error
if (curl_errno($ch)) {
    $error_message = curl_error($ch);
}

curl_close($ch);

print_r($response);

POST request

Post request is secure method and used to save form data to remote server.

$status_headers = [
    'Accept: application/json'
];

$url = 'https://hackthestuff.com/test/environment/';

$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    $error_message = curl_error($ch);
}

curl_close ($ch);

$status_data = json_decode($response, true);

Find PHP Documentation on how to add more configurations on method.

Tags: