PHP cURL


cURL stands for Client URL. The cURL extension in PHP provides functionality for your scripts to initiate HTTP requests with external servers and APIs such as RESTful services and form submissions. ).

 

 

  • Initialize: curl_init()
  • Set options: curl_setopt()
  • Execute request: curl_exec()
  • Close session: curl_close()
php-curl

GET Request

<?php
$ch = curl_init("https://api.example.com/data");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response instead of output
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?> 

POST Request

<?php
$data = ["name" => "Alice", "email" => "alice@example.com"];
$jsonData = json_encode($data);

$ch = curl_init("https://api.example.com/users");

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Content-Length: ' . strlen($jsonData)
]);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?> 

PUT Request

<?php
$data = ["name" => "Updated Name"];
$jsonData = json_encode($data);

$ch = curl_init("https://api.example.com/users/1");

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Content-Length: ' . strlen($jsonData)
]);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?> 

DELETE Request

<?php
$ch = curl_init("https://api.example.com/users/1");

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?> 

Useful cURL

Option Purpose
CURLOPT_URL Set the request URL
CURLOPT_RETURNTRANSFER Return response as string
CURLOPT_POST Perform HTTP POST
CURLOPT_CUSTOMREQUEST Use PUT, DELETE, etc.
CURLOPT_HTTPHEADER Set custom headers
CURLOPT_POSTFIELDS Send request body
CURLOPT_TIMEOUT Set timeout in seconds



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.