Website Vidya
Linux & ServersStep-by-Step Guide

How to Install and Use PHP Composer on Ubuntu 24.04

Learn how to install and use Composer on Ubuntu 24.04 LTS with PHP prerequisites, SHA-384 verification, global setup, and package commands.

RR
Rajesh RayLead Systems Educator
Published:
5 min read
PDF Cheat Sheet
How to Install and Use PHP Composer on Ubuntu 24.04
AI Executive SummaryWebsiteVidya AI

5 min read

Learn how to install and use Composer on Ubuntu 24.04 LTS with PHP prerequisites, SHA-384 verification, global setup, and package commands.

Key Highlights
  • Prerequisites and Supported Releases
  • Step 1: Installing PHP CLI and Required Extension Dependencies
  • Step 2: Downloading the Official Composer Installer Script
Grounded in full engineering runbookWebsiteVidya AI Engine

Modern PHP development relies on a modular architecture where libraries, web frameworks (such as Laravel and Symfony), and testing utilities are integrated as decoupled external packages. When you install and use composer on ubuntu 24.04, you equip your server or workstation with the industry-standard dependency manager, which automatically resolves package compatibility, downloads required source trees, and generates optimized PSR-4 class autoloaders.

Deploying Composer on Ubuntu 24.04 requires configuring PHP CLI runtime extensions, securely fetching the official installer script, verifying its cryptographic SHA-384 checksum, and placing the resulting executable in your system-wide execution path. This tutorial walks you through every step of global deployment and demonstrates essential everyday project workflows.

Prerequisites and Supported Releases

This guide is thoroughly verified on Ubuntu 24.04 LTS (Noble Numbat) & Ubuntu 22.04 LTS. The instructions apply cleanly to cloud instances (AWS EC2, Google Compute Engine, DigitalOcean, Hetzner), bare-metal servers, and local virtual machines.

Advertisement

Before proceeding, ensure you have the following requirements satisfied:

  • An active installation of Ubuntu 24.04 LTS (Desktop or Server).
  • A user account with active sudo administrative privileges.
  • PHP 8.2 or PHP 8.3 CLI installed on the system.
  • Basic command-line familiarity and an active Internet connection.

Step 1: Installing PHP CLI and Required Extension Dependencies

The php-zip and unzip packages are critical because Composer downloads package releases from GitHub and Packagist as zip archives to dramatically accelerate installation times compared to cloning git histories.

# Refresh package lists and install PHP CLI with required extensions
sudo apt update
sudo apt install -y php-cli php-mbstring php-xml php-curl php-zip unzip curl git

Step 2: Downloading the Official Composer Installer Script

Composer provides an automated PHP installer script. Download this setup script directly into your temporary or home directory using curl.

# Navigate to your home directory and fetch the installer script
cd ~
curl -sS https://getcomposer.org/installer -o composer-setup.php

Step 3: Cryptographically Verifying the Installer SHA-384 Hash

If the script outputs Installer verified, the installer is authentic and intact. If it reports Installer corrupt, the file will be deleted automatically; inspect your network connection and re-run the download.

Advertisement
# Fetch the official current installer signature
HASH="$(curl -sS https://composer.github.io/installer.sig)"

# Verify the installer script against the signature
php -r "if (hash_file('sha384', 'composer-setup.php') === '$HASH') { echo 'Installer verified' . PHP_EOL; } else { echo 'Installer corrupt' . PHP_EOL; unlink('composer-setup.php'); exit(1); }"

Step 4: Installing Composer Globally into /usr/local/bin

To allow all system users to run the composer command without typing full path prefixes, execute the installer with the --install-dir and --filename flags pointing to /usr/local/bin.

# Install Composer globally as an executable binary named 'composer'
sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

# Clean up the installer script
rm composer-setup.php

Verifying the Global Composer Installation

Test that Composer is accessible and displays its version information and command help menu:

# Verify the Composer installation
composer --version

# Sample output:
# Composer version 2.7.7 2024-06-10 22:11:12
# PHP version 8.3.6 (/usr/bin/php8.3)
# Run the "diagnose" command to get more details

Step 5: Initializing a New PHP Project with composer.json

The interactive wizard prompts you for package name, description, author, minimum stability, and license. Once completed, it generates a standard composer.json file.

# Create and navigate into a sample project folder
mkdir ~/demo-php-project && cd ~/demo-php-project

# Initialize the project interactively
composer init

Step 6: Requiring and Managing Packages

Composer inspects dependency constraints, resolves compatible sub-dependencies, creates a composer.lock lockfile pinning exact versions, and downloads the package files into a local vendor/ directory.

Advertisement
# Install the Guzzle HTTP client package
composer require guzzlehttp/guzzle

Autoloading Classes in Your PHP Code

Composer automatically generates a unified class autoloader in vendor/autoload.php. Include this single file at the entrypoint of your application to instantly use any installed library without manual require statements:

<?php
require __DIR__ . '/vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();
$response = $client->request('GET', 'https://api.github.com');

echo "HTTP Status: " . $response->getStatusCode() . PHP_EOL;

Step 7: Updating Dependencies and Managing composer.lock

Understanding the distinction between composer install and composer update is fundamental to preventing production deployment anomalies. Running composer install on a production server guarantees that every server instance, container build, and continuous integration pipeline runs identical library binaries byte-for-byte based on composer.lock.

Conversely, running composer update should be reserved for local development environments where code can undergo thorough unit and regression testing prior to committing updated lockfiles to version control.

# Install exact locked dependencies on production/CI servers
composer install --no-dev --optimize-autoloader

# Update packages to the latest versions matching composer.json constraints
composer update

# Install development-only tools (e.g. PHPUnit)
composer require --dev phpunit/phpunit

# Self-update the global Composer binary to the newest release
sudo composer self-update
CommandAction on composer.lockUse CaseEnvironment
composer installStrictly obeys existing lockfileReproducible builds and deploymentsProduction, CI/CD, Team onboarding
composer updateRecalculates dependencies and updates lockfileUpgrading packages within semantic constraintsLocal development testing
composer require <pkg>Adds package, updates lockfileIntroducing new project capabilitiesDevelopment workspace
composer dump-autoload -oGenerates optimized class mapProduction performance tuningProduction deployment artifact build

Troubleshooting and Common Errors

When configuring Ubuntu servers, unexpected permission errors, network timeouts, or lock contention can occur. Review these common issues and verified resolutions:

Fatal error: Allowed memory size of X bytes exhausted.

Cause: Complex dependency trees can exceed the default PHP CLI memory limit.

Resolution: Temporarily disable the memory limit using the COMPOSER_MEMORY_LIMIT environment variable.

COMPOSER_MEMORY_LIMIT=-1 composer update

GitHub API rate limit exceeded when fetching packages.

Cause: GitHub throttles unauthenticated requests from busy networks or cloud IP addresses.

Resolution: Create a GitHub personal access token and configure it in Composer: composer config --global github-oauth.github.com YOUR_TOKEN.

composer config --global github-oauth.github.com <TOKEN>

Your requirements could not be resolved to an installable set of packages.

Cause: Conflicting version constraints or missing required PHP extensions on the host.

Resolution: Check for missing PHP extensions (e.g. php-intl, php-gd) and review package version compatibility in composer.json.

php -m

Security Best Practices and Hardening

Never run composer install or composer update as the root user; Composer packages contain install lifecycle scripts that execute with root privileges if run under sudo.

Always manage project dependencies as a standard unprivileged user.

Audit project dependencies for known security vulnerabilities regularly using composer audit or integrate security scanners into your automated CI pipelines.

Commit composer.lock to your version control repository to prevent unauthorized or unexpected upstream package upgrades during production deployments.

Deepen your Linux system administration skills with our related production-tested guides:

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
No. Never commit the vendor/ directory to version control. Add /vendor/ to your .gitignore file. Instead, commit composer.json and composer.lock; other developers can reproduce your exact environment by running composer install.
composer install reads composer.lock and installs the exact versions recorded there, ensuring deterministic deployments. composer update checks composer.json, resolves the newest allowed package versions, downloads them, and updates composer.lock.
Run sudo composer self-update to automatically fetch and verify the newest stable Composer executable.
Yes. Run php composer-setup.php without --install-dir. This generates a local composer.phar file that you can execute directly with php composer.phar.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout