Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔴 Advanced  ·  Lesson 32

PHP cURL – API Requests

In this lesson: Call APIs from PHP using cURL — GET, POST JSON, headers, timeouts and error handling — ready-to-use code.

What is cURL

cURL lets a PHP script send requests to other websites and APIs, and read what comes back. Whenever your site needs to talk to a payment gateway, an SMS service, or a weather API, cURL is the usual tool. Every cURL call follows four steps: init, set options, execute, close.

💡 The four steps: curl_init() → curl_setopt() → curl_exec() → curl_close().

A GET request

Fetch data from a URL and get it back as a string.

<?php
  $ch = curl_init("https://api.example.com/data");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($ch);
  curl_close($ch);

  echo $response;
?>

CURLOPT_RETURNTRANSFER is the key line — it makes curl_exec return the response so you can store it in $response instead of printing it straight away.

A POST request

Send data to a server, for example to submit a form or create a record.

<?php
  $ch = curl_init("https://api.example.com/save");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, [
      "name" => "Aman",
      "class" => 12
  ]);
  $response = curl_exec($ch);
  curl_close($ch);
?>

CURLOPT_POST switches to POST, and CURLOPT_POSTFIELDS holds the data you send in the body.

Sending JSON

Most modern APIs expect JSON. Encode the data and set the header.

<?php
  $data = json_encode(["name" => "Aman"]);
  $ch = curl_init("https://api.example.com/save");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Content-Type: application/json"
  ]);
  $response = curl_exec($ch);
  curl_close($ch);
?>

The Content-Type: application/json header tells the server your body is JSON. Decode the reply with json_decode($response, true).

Checking for errors

<?php
  $response = curl_exec($ch);
  if (curl_errno($ch)) {
      echo "Error: " . curl_error($ch);
  }
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  echo "Status: $code";   // e.g. 200
  curl_close($ch);
?>
Status: 200

Always check for connection errors and the HTTP status code (200 means OK, 404 not found, 500 server error), so your app can respond properly.

Common mistakes

  • Forgetting CURLOPT_RETURNTRANSFER. Without it the response is printed, not returned, so $response is empty.
  • Not setting the JSON header. Many APIs reject JSON without Content-Type: application/json.
  • Ignoring the status code. A request can "work" but return a 404 or 500 — always check.
  • Not closing the handle. Call curl_close() when done.

Summary

  • cURL sends requests to other sites and APIs from PHP.
  • Four steps: init, set options, execute, close.
  • CURLOPT_RETURNTRANSFER makes the response come back as a string.
  • Use CURLOPT_POST + CURLOPT_POSTFIELDS for POST; add a JSON header for JSON.
  • Check curl_error and the HTTP status code for problems.

Next, read the JSON you receive with PHP JSON, or build your own endpoint with PHP REST API.

Frequently Asked Questions

What is cURL used for in PHP?
cURL lets your PHP script talk to other websites and APIs — to fetch data, send data, or log in to a service. It is how you connect to payment gateways, SMS services, weather APIs and more.
What is the difference between GET and POST in cURL?
GET asks for data and puts parameters in the URL. POST sends data in the request body, used for creating or submitting something. Set POST with curl_setopt($ch, CURLOPT_POST, true).
Why do I need CURLOPT_RETURNTRANSFER?
By default cURL prints the response directly. Setting CURLOPT_RETURNTRANSFER to true makes curl_exec return the response as a string instead, so you can store and process it.
How do I send JSON with cURL?
Set the body with CURLOPT_POSTFIELDS to your json_encoded data, and add a Content-Type: application/json header with CURLOPT_HTTPHEADER.
How do I check if a cURL request failed?
After curl_exec, check curl_error($ch) for connection problems, and the HTTP status code with curl_getinfo($ch, CURLINFO_HTTP_CODE) to see if the server returned an error.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicPassword Hashing Your progress: 32 / 50 (64%) · Lesson 33 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free