HTTP Requests and Email

Back

Loading concept...

📬 PHP HTTP Requests & Email: Your Digital Messenger!

Imagine you’re a delivery person. You pick up packages (data), travel to different houses (servers), drop off or pick up things, and sometimes send letters (emails). That’s exactly what PHP does when talking to the internet!


🎯 What We’ll Learn

Today we’re going to learn how PHP can:

  • Talk to other websites (like asking a friend for information)
  • Send and receive data (like passing notes in class)
  • Send emails (like mailing a birthday card)

Let’s start our adventure! 🚀


🌀 cURL: Your Super Delivery Truck

cURL stands for “Client URL” - think of it as a super-powered delivery truck that can go anywhere on the internet!

🔧 cURL Initialization

Before our truck can go anywhere, we need to start the engine!

// Start the cURL truck engine!
$ch = curl_init();

// Or give it a destination right away
$ch = curl_init("https://api.example.com");

What’s happening?

  • curl_init() = Turn on the truck
  • $ch = Our truck’s “handle” (like a steering wheel)

💡 Simple Rule: Always start with curl_init() before doing anything else!


⚙️ cURL Options

Now let’s program our GPS (tell the truck where to go and how to behave)!

$ch = curl_init();

// Where are we going?
curl_setopt($ch, CURLOPT_URL,
  "https://api.example.com/data");

// Bring back what you find!
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Wait max 30 seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

Common Options Explained:

Option What It Does Like…
CURLOPT_URL Where to go The address
CURLOPT_RETURNTRANSFER Bring back data Taking photos
CURLOPT_TIMEOUT Max wait time Patience limit
CURLOPT_FOLLOWLOCATION Follow redirects Following signs
CURLOPT_HTTPHEADER Extra info ID badge

🎯 Pro Tip: Always set CURLOPT_RETURNTRANSFER to true or you won’t get any data back!


🚗 cURL Execution

Time to send our truck on its journey!

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
  "https://jsonplaceholder.typicode.com/posts/1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// GO! Send the truck!
$response = curl_exec($ch);

// Park the truck (close connection)
curl_close($ch);

// See what we got!
echo $response;

The Journey:

graph TD A["🔧 curl_init"] --> B["⚙️ curl_setopt"] B --> C["🚗 curl_exec"] C --> D["📦 Get Response"] D --> E["🅿️ curl_close"]

⚠️ Important: Always call curl_close() when done - like turning off your car!


📥 cURL GET Requests

GET requests are like asking a question - “Hey, can you give me some information?”

function getData($url) {
    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPGET => true
    ]);

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

    return json_decode($result, true);
}

// Use it!
$users = getData("https://api.example.com/users");
print_r($users);

Real Example - Get Weather:

$city = "London";
$url = "https://api.weather.com/city=" .
  urlencode($city);

$weather = getData($url);
echo "Temperature: " . $weather['temp'];

💡 GET = “Give me info!” - You’re just looking, not changing anything.


📤 cURL POST Requests

POST requests are like sending a package - you’re giving information TO the server!

function postData($url, $data) {
    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json'
        ]
    ]);

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

    return json_decode($result, true);
}

// Create a new user
$newUser = [
    'name' => 'Alice',
    'email' => 'alice@example.com'
];

$response = postData(
  "https://api.example.com/users",
  $newUser
);

GET vs POST:

GET POST
📖 Reading a book ✏️ Writing in a book
Safe, no changes Creates/changes data
Data in URL Data in body

🚨 cURL Error Handling

What if our truck gets lost or breaks down? We need to handle problems!

$ch = curl_init();

curl_setopt_array($ch, [
    CURLOPT_URL => "https://api.example.com/data",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10
]);

$response = curl_exec($ch);

// Did something go wrong?
if ($response === false) {
    $errorNumber = curl_errno($ch);
    $errorMessage = curl_error($ch);

    echo "Oops! Error #$errorNumber: $errorMessage";
} else {
    // Check HTTP status
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($httpCode >= 200 && $httpCode < 300) {
        echo "Success! Got: $response";
    } else {
        echo "Server said no! Code: $httpCode";
    }
}

curl_close($ch);

Common Error Codes:

HTTP Code Meaning Emoji
200 All good!
404 Not found 🔍
500 Server broke 💥
401 Not allowed 🚫

🛡️ Always check for errors! Things can and will go wrong.


🌊 Stream Context: The Simple Alternative

Sometimes you don’t need a big truck - a bicycle will do! Stream context is simpler for basic requests.

// Create options (like packing a small bag)
$options = [
    'http' => [
        'method' => 'GET',
        'header' => "Accept: application/json\r\n",
        'timeout' => 10
    ]
];

// Create the context (get your bicycle ready)
$context = stream_context_create($options);

// Go fetch!
$response = file_get_contents(
    "https://api.example.com/data",
    false,
    $context
);

echo $response;

POST with Stream Context:

$data = json_encode(['name' => 'Bob']);

$options = [
    'http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/json\r\n",
        'content' => $data
    ]
];

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

When to use what?

cURL Stream Context
Complex requests Simple requests
Need full control Quick and easy
File uploads Basic GET/POST
Better error info Less code

📧 The mail() Function: Sending Letters

Finally, let’s send emails with PHP’s built-in mail() function!

Basic Email

$to = "friend@example.com";
$subject = "Hello from PHP!";
$message = "This is my first email from PHP!";
$headers = "From: me@example.com";

// Send it!
$sent = mail($to, $subject, $message, $headers);

if ($sent) {
    echo "Email sent! 📬";
} else {
    echo "Oops, couldn't send email 😢";
}

The 4 Parts of an Email:

graph TD A["📧 mail function"] --> B["To: Who gets it?"] A --> C[Subject: What's it about?] A --> D["Message: The letter itself"] A --> E["Headers: Extra info"]

HTML Email

$to = "friend@example.com";
$subject = "Pretty HTML Email!";

$message = "
<html>
<body>
    <h1>Hello!</h1>
    <p>This is a <b>fancy</b> email!</p>
</body>
</html>
";

$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: me@example.com\r\n";

mail($to, $subject, $message, $headers);

Multiple Recipients

// Send to many friends at once!
$to = "alice@example.com, bob@example.com";

// Or use CC/BCC
$headers = "From: me@example.com\r\n";
$headers .= "Cc: manager@example.com\r\n";
$headers .= "Bcc: secret@example.com\r\n";

mail($to, $subject, $message, $headers);

⚠️ Reality Check: The basic mail() function is good for learning, but for real apps, use libraries like PHPMailer or SwiftMailer - they’re much more reliable!


🎯 Quick Summary

Task Tool Key Function
HTTP requests cURL curl_init(), curl_exec()
Simple requests Stream stream_context_create()
Send emails mail() mail($to, $subj, $msg)

🏆 You Did It!

Now you know how PHP can:

  • ✅ Start and configure cURL
  • ✅ Make GET and POST requests
  • ✅ Handle errors like a pro
  • ✅ Use stream context for simple stuff
  • ✅ Send emails to anyone!

Think of it this way:

  • cURL = Your super delivery truck 🚛
  • Stream Context = Your quick bicycle 🚴
  • mail() = Your postal service 📮

You’re now ready to make PHP talk to the whole internet! 🌐🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.