Topic 8: Using Libraries in PHP
📖 6 min read · 🎯 intermediate · 🧭 Prerequisites: http, react-router
Why this matters
Here's the thing — when you're building something in PHP, you don't have to write everything from scratch. Someone has already solved the hard stuff. Need to send an email? There's a library for that. Need to make HTTP requests or work with dates without going crazy? Libraries again. Today we're going to learn Composer — PHP's tool for pulling in these ready-made libraries — and then actually use three of the most popular ones: Guzzle for HTTP calls, PHPMailer for sending emails, and Carbon for handling dates like a pro.
What You'll Learn
- Install and configure Composer, PHP's dependency manager
- Use
composer requireto add third-party libraries to a project - Make HTTP requests with the Guzzle HTTP client
- Send emails programmatically using PHPMailer and SMTP
- Manipulate dates and times fluently with Carbon
The Analogy
Think of your PHP project as a professional kitchen. You could mill your own flour, churn your own butter, and forge your own knives — but you'd never cook a single meal. Libraries are your pre-stocked pantry and professional-grade equipment: Guzzle is the industrial mixer that handles HTTP in seconds, PHPMailer is the commercial oven built specifically for email delivery, and Carbon is a precision timer that never lies about what day it is. Composer is the supplier that delivers everything to your kitchen door so you can focus on the recipe that matters.
Chapter 1: Why Use Libraries?
Before touching a terminal, it's worth knowing what you're getting out of the deal.
- Efficiency — Reuse existing, battle-tested code to save time and effort instead of reinventing the wheel.
- Reliability — Popular libraries are actively maintained and tested by large communities; edge cases are already handled.
- Functionality — Access advanced features (HTTP connection pooling, MIME email encoding, timezone-aware date math) without building them from scratch.
Every library you'll see today is pulled from Packagist, the central repository for PHP packages, via Composer.
Chapter 2: Composer — The Dependency Manager for PHP
Composer is the standard tool for managing dependencies in PHP. You declare which libraries your project needs, and Composer downloads, installs, and autoloads them for you.
Installing Composer
On Windows, download and run Composer-Setup.exe from the official website.
On macOS/Linux, run these 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 a version string like Composer version 2.x.x.
Initializing a Project
Create a fresh project directory and scaffold it with Composer:
mkdir my_project
cd my_project
composer init
Follow the interactive prompts (package name, description, author, license). When finished, Composer writes a composer.json file — the manifest that records every dependency your project declares.
Installing a Library
Use composer require <vendor>/<package> to pull in any Packagist package:
composer require guzzlehttp/guzzle
Composer creates two important things:
vendor/— the directory where all library code livescomposer.json— your dependency manifest (commit this)composer.lock— the exact resolved versions (also commit this)
Your PHP files load everything from vendor/ with a single line:
require 'vendor/autoload.php';
Chapter 3: Guzzle — HTTP Requests Made Easy
Guzzle is the most widely used HTTP client library in the PHP ecosystem. It handles connection pooling, redirects, streaming, and async requests behind a clean API.
Install
composer require guzzlehttp/guzzle
Example: GET Request to a Public API
Create index.php in your project directory:
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('GET', 'https://jsonplaceholder.typicode.com/posts/1');
echo $response->getBody();
?>
Start PHP's built-in server:
php -S localhost:8000
Open your browser and navigate to http://localhost:8000. You should see the JSON response from the JSONPlaceholder API — a post object with userId, id, title, and body fields.
sequenceDiagram
participant Browser
participant PHP as PHP (index.php)
participant API as jsonplaceholder.typicode.com
Browser->>PHP: GET http://localhost:8000
PHP->>API: GET /posts/1 (via Guzzle)
API-->>PHP: 200 OK { id: 1, title: ... }
PHP-->>Browser: echo response body
Chapter 4: PHPMailer — Sending Email via SMTP
PHPMailer is the go-to library for sending emails from PHP. It supports SMTP authentication, TLS/SSL encryption, HTML email bodies, attachments, and more.
Install
composer require phpmailer/phpmailer
Example: Sending an HTML Email
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'; // 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'; // 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 script directly from the terminal (no web server needed):
php send_email.php
Key configuration points to note:
SMTPSecure = 'tls'withPort = 587is the modern standard;sslwith port465is the legacy alternative.AltBodyprovides a plain-text fallback for email clients that don't render HTML.- Wrapping the whole operation in a
try/catchwithPHPMailer\PHPMailer\Exceptiongives you clean error reporting via$mail->ErrorInfo.
Chapter 5: Carbon — Elegant Date and Time Manipulation
Carbon wraps PHP's native DateTime class with an expressive, chainable API. No more manual strtotime gymnastics.
Install
composer require nesbot/carbon
Example: Working with Dates
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 it:
php date_example.php
You'll see output like:
Current Date and Time: 2026-05-21 14:32:00
Tomorrow's Date and Time: 2026-05-22 14:32:00
Last Week's Date and Time: 2026-05-14 14:32:00
Carbon's chainable methods (addDay(), subWeek(), startOfMonth(), diffInHours(), etc.) cover virtually every date-math operation you'll encounter — all timezone-aware.
🧪 Try It Yourself
Task: Build a single PHP script that combines Guzzle and Carbon together.
- Fetch the post at
https://jsonplaceholder.typicode.com/posts/1using Guzzle. - Decode the JSON response body with
json_decode(). - Print the post title.
- Use Carbon to print how many days ago January 1, 2024 was.
Success criteria: Running php combined.php in your terminal should print both the post title from the API and a line like "Jan 1, 2024 was 506 days ago" (exact number will vary by today's date).
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);
echo "Post title: " . $post['title'] . "\n";
$jan2024 = Carbon::create(2024, 1, 1);
$daysAgo = $jan2024->diffInDays(Carbon::now());
echo "Jan 1, 2024 was {$daysAgo} days ago\n";
?>
🔍 Checkpoint Quiz
Q1. What is the role of the vendor/autoload.php file that Composer generates?
A) It lists all packages available on Packagist
B) It registers an autoloader so you can use any installed class without manually require-ing each file
C) It stores your SMTP credentials securely
D) It initializes a new Git repository for the project
Q2. Given this code, what will be printed to the browser?
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
$d = Carbon::create(2024, 3, 15)->addDays(10);
echo $d->toDateString();
?>
A) 2024-03-15
B) 2024-03-25
C) 2024-04-15
D) 2024-03-05
Q3. What is the bug in this PHPMailer setup?
$mail->SMTPSecure = 'tls';
$mail->Port = 465;
A) tls should be written as TLS in uppercase
B) Port 465 is the legacy SSL port; TLS encryption should use port 587
C) There is no bug — this is a valid combination
D) SMTPSecure must be set after Port
Q4. You're building a dashboard that pulls live weather data from a third-party REST API every time a page loads. Which library would you reach for, and what single command installs it?
A1. B — Composer's generated autoloader maps every installed package's namespaces to file paths, so a use statement is all you need to pull in any class.
A2. B — Carbon::create(2024, 3, 15)->addDays(10) moves 10 days forward from March 15, landing on March 25, 2024. toDateString() formats it as YYYY-MM-DD.
A3. B — Port 465 is the legacy implicit-SSL port. When using SMTPSecure = 'tls' (STARTTLS), the correct port is 587. Mismatching them causes a connection failure or timeout.
A4. Guzzle — the HTTP client library. Install it with composer require guzzlehttp/guzzle. It handles the GET/POST requests to the weather API, and $response->getBody() gives you the JSON payload to decode.
🪞 Recap
- Composer is PHP's standard dependency manager;
composer require <vendor>/<package>downloads any Packagist library into yourvendor/directory. require 'vendor/autoload.php'is the single line that makes every installed library available viausestatements.- Guzzle provides a clean, reliable API for making HTTP requests — GET, POST, and beyond — against external services.
- PHPMailer handles the full complexity of SMTP-authenticated, TLS-encrypted HTML email delivery with a straightforward object interface.
- Carbon wraps PHP's
DateTimewith expressive, chainable methods likeaddDay(),subWeek(), anddiffInDays()for readable date math.
📚 Further Reading
- Composer Official Docs — the source of truth on dependency management,
composer.jsonschema, and versioning constraints - Guzzle Documentation — full reference for async requests, middleware, streaming, and connection options
- PHPMailer GitHub — examples, SMTP configuration guides, and troubleshooting for common mail issues
- Carbon Documentation — complete API reference for date creation, comparison, formatting, and localization
- ⬅️ Previous: React Router
- ➡️ Next: Hooks