Skip to Content
Course content

35: Making HTTP Requests with cURL

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Up until now, we've mostly been thinking about PHP as the thing that receives requests from a browser. But in the real world, your server often needs to be the one making the request. Maybe you're pulling shipping rates from FedEx, fetching a user's profile from a separate microservice, or hitting a payment gateway. That's where cURL comes in.

How do I actually start a cURL request and get a response back?

The basic workflow of cURL in PHP is a bit "procedural." You initialize a session, set your options, execute the request, and then close the session. If you forget the "return transfer" option, PHP will just dump the response directly to the browser screen, which is almost never what you want when you're trying to process data in your code.

<?php
// I'll use the PokeAPI here because it's free and requires no keys
$ch = curl_init();

// Set the URL we want to hit
curl_setopt($ch, CURLOPT_URL, "https://pokeapi.co/api/v2/pokemon/pikachu");

// This is the crucial part: tell cURL to return the response as a string 
// instead of echoing it immediately to the page.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}

curl_close($ch);

echo $response;
?>

What if I need to send data, like a POST request?

Getting data is easy, but sending it requires a few more options. You have to tell cURL explicitly that you're doing a POST request and provide the data you want to send. I usually recommend passing an array to CURLOPT_POSTFIELDS; cURL will handle the encoding for you.

<?php
$url = "https://jsonplaceholder.typicode.com/posts";
$data = [
    'title'  => 'Learning cURL',
    'body'   => 'This is a test post from my PHP script.',
    'userId' => 1
];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

echo $response;
?>

One quick tip: I used http_build_query() above. If you pass a raw array to CURLOPT_POSTFIELDS, cURL sends it as multipart/form-data. If you use http_build_query(), it sends it as application/x-www-form-urlencoded. Most APIs prefer the latter unless you're uploading a file.

How do I handle JSON responses?

Almost every modern API you touch will send back JSON. Since curl_exec just gives you one giant string, you'll need to decode that string into a PHP array or object to actually use it. This is where json_decode() becomes your best friend.

<?php
$ch = curl_init("https://pokeapi.co/api/v2/pokemon/pikachu");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

// Decode the JSON string into an associative array
$data = json_decode($result, true);

// Now you can actually use the data in your HTML
echo "<h1>" . ucfirst($data['name']) . "</h1>";
echo "<p>Weight: " . $data['weight'] . "Pokémon units</p>";
?>

How do I add API keys or custom headers?

You'll rarely find a professional API that lets you in for free without a key. Most of the time, you'll need to pass this key in the HTTP headers (like a Bearer token). You do this by passing an array of strings to CURLOPT_HTTPHEADER.

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

$headers = [
    "Authorization: Bearer YOUR_SECRET_TOKEN_HERE",
    "Content-Type: application/json",
    "Accept: application/json"
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

Just be careful not to hardcode your API keys directly in your scripts if you're pushing to GitHub. Use environment variables or a config file that's ignored by git. I've seen way too many people accidentally leak their AWS or Stripe keys this way.




📋 Practical Task

Exercise: Build a GitHub User Profile Fetcher

Your task is to create a PHP script that fetches public information about a GitHub user using the GitHub REST API.

  • The Endpoint: Use https://api.github.com/users/{username} (replace {username} with any valid GitHub handle, like 'octocat').
  • The Requirement: GitHub's API requires a User-Agent header. If you don't provide one, the request will fail. Add a header like "User-Agent: PHP-Course-Learning-Script".
  • The Goal: Use cURL to fetch the data, decode the JSON response, and display the user's name, bio, and public_repos count in a clean HTML list.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.