Topic 36 of 48 · Full Stack Essentials

Using Libraries in PHP

Lesson TL;DRTopic 8: Using Libraries in PHP 📖 6 min read · 🎯 Advanced · 🧭 Prerequisites: registrationformdbconnect, tagslist Why this matters Here's the thing — when you start building real PHP projects, you'l...
6 min read·advanced·php · composer · libraries · guzzle

Topic 8: Using Libraries in PHP

📖 6 min read · 🎯 Advanced · 🧭 Prerequisites: registration-form-db-connect, tags-list

Why this matters

Here's the thing — when you start building real PHP projects, you'll quickly hit moments where you need to send an email, make an HTTP request, or work with dates. You could write all that code yourself, but someone already did it better, and Composer lets you pull it straight into your project. That's what PHP libraries are for. Today we're looking at three that you'll use over and over: Guzzle for HTTP requests, PHPMailer for sending emails, and Carbon for working with dates in plain, readable code. No reinventing the wheel.

What You'll Learn

  • Install and initialize Composer, PHP's dependency manager
  • Install third-party libraries with composer require and understand the vendor/ directory
  • Use Guzzle to make HTTP GET requests to a public API
  • Use PHPMailer to send HTML emails over SMTP
  • Use Carbon to add, subtract, and format dates and times

The Analogy

Think of a PHP project as a kitchen. You could grow every vegetable, mill every grain, and press every olive yourself — but a professional chef walks into a stocked pantry, grabs what they need, and focuses on the dish. Composer is the pantry manager: you hand it a shopping list (composer.json), and it sources every ingredient from Packagist (the public registry), places them neatly in the vendor/ shelf, and updates the list so your whole team orders the exact same versions. Guzzle is the delivery phone line, PHPMailer is the postal service, and Carbon is the kitchen clock — specialized tools, ready to use the moment you reach for them.

Chapter 1: Why Use Libraries?

Rolling your own HTTP client, mail handler, or date utility is time-consuming and error-prone. Libraries solve this by offering code that is:

  • Efficient — reuse thousands of hours of community work with a single command
  • Reliable — well-tested, actively maintained, and battle-hardened in production
  • Functional — advanced features (SMTP auth, timezone-aware dates, connection pooling) without building them from scratch

The PHP ecosystem publishes and discovers libraries through Packagist, and Composer is the tool that bridges your project to that registry.

Chapter 2: Composer — The Dependency Manager for PHP

Step 1: Installing Composer

On Windows: Download and run Composer-Setup.exe from the official website.

On macOS / Linux: Run these three commands in your terminal:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
php -r "unlink('composer-setup.php');"

Verify the installation succeeded:

composer --version

You should see output like Composer version 2.x.x.

Step 2: Initializing a Composer Project

Create a fresh project directory and run the interactive setup wizard:

mkdir my_project
cd my_project
composer init

Follow the prompts — you'll name the package, set a description, and define your PHP version constraint. When finished, Composer writes a composer.json file that records everything your project needs.

Step 3: Installing Libraries with composer require

To add a library, pass its Packagist name to composer require:

composer require guzzlehttp/guzzle

Composer resolves the dependency tree, downloads packages into a vendor/ directory, and generates (or updates) composer.lock — a snapshot of exact versions so every developer on the team gets identical code.

flowchart LR
    A[composer require package/name] --> B[Packagist registry]
    B --> C[Download to vendor/]
    C --> D[Update composer.json]
    D --> E[Generate composer.lock]
    E --> F[vendor/autoload.php ready]

The single file vendor/autoload.php is all you ever need to include in your PHP scripts — Composer handles loading every installed class automatically.

Chapter 3: Using Guzzle to Make HTTP Requests

Guzzle is a popular, production-grade HTTP client for PHP.

Install

composer require guzzlehttp/guzzle

Create index.php

<?php

require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();

$response = $client->request('GET', 'https://jsonplaceholder.typicode.com/posts/1');

echo $response->getBody();

?>

Run the built-in PHP server

php -S localhost:8000

Open your browser and navigate to http://localhost:8000. You should see the JSON response from the JSONPlaceholder API:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae..."
}

$client->request('GET', $url) returns a PSR-7 response object. Call ->getBody() to read the response body, ->getStatusCode() for the HTTP status, and ->getHeader('Content-Type') for headers.

Chapter 4: Using PHPMailer to Send Emails

PHPMailer is the standard library for sending emails in PHP, supporting SMTP authentication and HTML content.

Install

composer require phpmailer/phpmailer

Create send_email.php

<?php

require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->SMTPDebug = 0;                               // Enable verbose debug output
    $mail->isSMTP();                                    // Set mailer to use SMTP
    $mail->Host       = 'smtp.example.com';             // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                           // Enable SMTP authentication
    $mail->Username   = 'your_email@example.com';       // SMTP username
    $mail->Password   = 'your_password';                // SMTP password
    $mail->SMTPSecure = 'tls';                          // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 587;                            // TCP port to connect to

    // Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('to@example.com', 'Recipient');   // Add a recipient

    // Content
    $mail->isHTML(true);                                // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

?>

Run the email script

php send_email.php

Key configuration options at a glance:

PropertyPurpose
$mail->isSMTP()Switch from PHP's mail() to SMTP
$mail->SMTPSecure'tls' (port 587) or 'ssl' (port 465)
$mail->SMTPAuthRequire username/password authentication
$mail->AltBodyPlain-text fallback for clients that block HTML
new PHPMailer(true)Pass true to enable exceptions

Chapter 5: Using Carbon for Date and Time Manipulation

Carbon extends PHP's native DateTime class with a fluent, human-readable API for all date and time operations.

Install

composer require nesbot/carbon

Create date_example.php

<?php

require 'vendor/autoload.php';

use Carbon\Carbon;

$now = Carbon::now();
echo "Current Date and Time: " . $now->toDateTimeString() . "\n";

$tomorrow = Carbon::now()->addDay();
echo "Tomorrow's Date and Time: " . $tomorrow->toDateTimeString() . "\n";

$lastWeek = Carbon::now()->subWeek();
echo "Last Week's Date and Time: " . $lastWeek->toDateTimeString() . "\n";

?>

Run the date script

php date_example.php

Sample output:

Current Date and Time: 2026-05-21 10:34:07
Tomorrow's Date and Time: 2026-05-22 10:34:07
Last Week's Date and Time: 2026-05-14 10:34:07

Carbon's most useful methods:

  • Carbon::now() — current date/time in server timezone
  • ->addDay() / ->addDays(n) — move forward by days
  • ->subWeek() / ->subMonths(n) — move backward
  • ->toDateTimeString() — format as YYYY-MM-DD HH:MM:SS
  • ->diffForHumans() — human-readable diff, e.g. "3 days ago"

🧪 Try It Yourself

Task: Build a single PHP script that combines all three libraries. Using Guzzle, fetch the post at https://jsonplaceholder.typicode.com/posts/1. Then use Carbon to record the current timestamp. Print both the post title and the fetch time in a formatted string.

Success criterion: Running php combined.php in your terminal prints something like:

[2026-05-21 10:34:07] Fetched post: "sunt aut facere repellat provident..."

Starter snippet:

<?php

require 'vendor/autoload.php';

use GuzzleHttp\Client;
use Carbon\Carbon;

$client = new Client();
$response = $client->request('GET', 'https://jsonplaceholder.typicode.com/posts/1');

$post = json_decode($response->getBody(), true);
$fetchedAt = Carbon::now()->toDateTimeString();

// TODO: print $fetchedAt and $post['title'] in one formatted line

Make sure you have run composer require guzzlehttp/guzzle nesbot/carbon before running the script.

🔍 Checkpoint Quiz

Q1. What is the role of vendor/autoload.php in a Composer-managed PHP project?

A) It lists all installed packages in JSON format
B) It bootstraps PHP's class autoloader so you can use any installed library without manual require calls
C) It connects your project to the Packagist registry at runtime
D) It stores your SMTP credentials securely

Q2. Given this snippet, what will be printed?

<?php
require 'vendor/autoload.php';
use Carbon\Carbon;

$date = Carbon::now()->subWeek()->addDays(3);
echo $date->diffForHumans();

A) A date 4 days from now
B) A date 4 days ago
C) A date 3 days ago
D) The current date and time

Q3. What is the bug in the following PHPMailer setup?

$mail->isSMTP();
$mail->Host       = 'smtp.example.com';
$mail->SMTPAuth   = true;
$mail->Username   = 'user@example.com';
$mail->Password   = 'secret';
$mail->SMTPSecure = 'tls';
$mail->Port       = 465;

A) SMTPAuth should be false when using TLS
B) Port 465 is for SSL; TLS encryption should use port 587
C) isSMTP() is not a valid PHPMailer method
D) SMTPSecure should be set to 'ssl' when using port 465 — this is actually valid, not a bug

Q4. You need your PHP application to call a third-party REST API and parse the JSON response. Which library would you install, and what composer require command starts the process?

(Open-ended — write the command and explain your choice.)

A1. B — vendor/autoload.php is generated by Composer and registers a PSR-4 autoloader. Including it once at the top of your script makes every installed package's classes available via use statements without any manual file includes.

A2. B — subWeek() moves back 7 days, then addDays(3) moves forward 3, landing 4 days in the past. diffForHumans() returns a string like "4 days ago".

A3. B — Port 465 is the traditional SSL port. When SMTPSecure = 'tls' (STARTTLS), the correct port is 587. To use port 465, change SMTPSecure to 'ssl'. Mixing tls with 465 will cause a connection failure.

A4. Install Guzzle with composer require guzzlehttp/guzzle. Guzzle provides a clean, PSR-7-compliant HTTP client with support for GET/POST/PUT/DELETE requests, middleware, and streaming. After installing, use $client->request('GET', $url) and json_decode($response->getBody(), true) to parse the response.

🪞 Recap

  • Composer is PHP's standard dependency manager — composer require installs libraries into vendor/ and tracks versions in composer.lock.
  • vendor/autoload.php is the single include that makes every installed library's classes available in your scripts.
  • Guzzle provides a production-ready HTTP client for making GET, POST, and other requests to external APIs.
  • PHPMailer handles SMTP authentication, TLS encryption, HTML email bodies, and plain-text fallbacks for sending email from PHP.
  • Carbon wraps PHP's DateTime with a fluent API — methods like addDay(), subWeek(), and diffForHumans() make date arithmetic readable and reliable.

📚 Further Reading

Like this topic? It’s one of 48 in Full Stack Essentials.

Block your seat for ₹2,500 and join the next cohort.