How to Install Composer on Ubuntu

Composer is the standard dependency manager for PHP, handling library installation, version constraints, and automatic class loading for modern PHP projects. Specifically, it reads a composer.json file to determine which packages your application needs, then resolves dependency conflicts automatically, and ensures every developer on a team uses identical library versions.

This guide walks through two installation methods on Ubuntu: the repository package for simplicity, and the official installer script for the latest release. By the end, you will have a working Composer installation, understand how to verify and update it, and know the essential commands for managing PHP dependencies in real projects.

Choose Your Composer Installation Method

Ubuntu provides Composer through its default repositories, offering a stable version that updates alongside system packages. Alternatively, the official getcomposer.org installer script always delivers the newest release directly from upstream. The table below summarizes the key differences:

MethodSourceVersionBest For
Ubuntu RepositoryAPT PackageDistribution-tested (may lag upstream)Most users preferring stability and automatic updates
Source ScriptOfficial UpstreamLatest stable releaseDevelopers needing the newest features immediately

For most users, the Ubuntu repository method is recommended because APT handles updates automatically during regular system maintenance. However, APT package versions can lag behind upstream by several minor releases, especially on older LTS versions. Choose the source script if your workflow requires specific newer features or you frequently collaborate on projects specifying recent Composer versions.

Method 1: Install Composer via Ubuntu Repository

The simplest approach uses Ubuntu’s default repositories, which provide a stable Composer version tested against your release’s PHP version. This method integrates with APT for seamless updates during normal system maintenance.

First, refresh your package index to ensure APT has the latest available package information:

sudo apt update

Next, install Composer along with its PHP dependencies:

sudo apt install composer

As a result, APT automatically installs PHP CLI and required extensions as dependencies. Once the installation completes, verify it by checking the version:

composer --version

The expected output varies by Ubuntu release. For example, on Ubuntu 26.04 LTS:

Composer version 2.8.8 2025-04-04 16:56:46
PHP version 8.4.11 (/usr/bin/php8.4)
Run the "diagnose" command to get more detailed diagnostics output.

The version number confirms Composer is installed and accessible. From this point forward, you can use composer commands directly from any directory.

Method 2: Install Composer via Source Script (Latest Version)

When you need the absolute latest release, the official installer script from getcomposer.org provides the newest stable version with all recent security patches and features. This method involves downloading the installer, verifying its cryptographic signature, and placing the binary in a system-wide location.

Install Required PHP Dependencies

Before proceeding, Composer requires several PHP extensions to function. Therefore, update your package index and install the prerequisites:

sudo apt update
sudo apt install curl php-cli php-zip php-curl php-mbstring git unzip

Each package serves a specific purpose: php-cli runs PHP from the command line, php-zip and unzip extract downloaded packages, php-curl and curl fetch data from URLs, php-mbstring handles multibyte strings (required by many libraries), and git enables Composer to clone repositories directly.

Download the Composer Installer

Now, download the official installer script to your temporary directory using curl. The -sS flags suppress progress output while still showing errors:

curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php

Verify the Installer Integrity

Before running third-party scripts, always verify their integrity. Composer publishes a SHA-384 hash of the installer, allowing you to confirm the file was not corrupted or tampered with during download.

First, fetch the expected hash from Composer’s signature page and store it in a shell variable:

HASH=$(curl -sS https://composer.github.io/installer.sig)

Optionally, display the hash to confirm it downloaded correctly (it should be a 96-character hexadecimal string):

echo $HASH

Next, compare the downloaded installer’s hash against the expected value. This PHP one-liner computes the file’s actual SHA-384 hash and checks it against the stored variable:

php -r "if (hash_file('SHA384', '/tmp/composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('/tmp/composer-setup.php'); } echo PHP_EOL;"

Consequently, a successful verification displays:

Installer verified

However, if the verification fails and outputs “Installer corrupt,” the script automatically deletes the compromised file. In that case, re-download the installer and repeat the verification steps.

Install Composer Globally

With a verified installer, now run it with sudo to place Composer in /usr/local/bin, thereby making the command accessible system-wide from any directory:

sudo php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer

Subsequently, the installer displays confirmation when finished:

All settings correct for using Composer
Downloading...

Composer (version 2.9.2) successfully installed to: /usr/local/bin/composer
Use it: php /usr/local/bin/composer

Verify Composer Installation

Finally, confirm the installation succeeded by checking the version:

composer --version

Expected output:

Composer version 2.9.2 2025-11-19 21:57:25
PHP version 8.4.11 (/usr/bin/php8.4)
Run the "diagnose" command to get more detailed diagnostics output.

Alternatively, running composer without arguments displays the full command list and usage guide, along with the ASCII logo.

Clean Up the Installer

After successful installation, remove the installer script as it is no longer needed:

rm /tmp/composer-setup.php

Install Composer Per Project (Optional)

Alternatively, some workflows prefer a project-local Composer installation rather than a global one. This approach ensures each project uses a specific Composer version, which can then be committed to version control.

To install Composer locally, run the installer without sudo and specify your current directory. The $PWD variable automatically expands to your present working directory:

curl -sS https://getcomposer.org/installer | php -- --install-dir=$PWD --filename=composer.phar

Afterwards, run Composer using PHP directly:

php composer.phar --version

Note that this one-liner skips the hash verification step for convenience. For production environments where security is paramount, instead follow the full download-and-verify process described earlier, then move the resulting composer.phar to your project directory. Ultimately, this approach lets teams pin specific Composer versions per repository.

Update Composer

How you update Composer depends on your installation method.

Update APT-Installed Composer

The repository version updates through normal APT operations:

sudo apt update
sudo apt install --only-upgrade composer

Generally, updates arrive whenever Ubuntu’s package maintainers push new versions, which may lag behind upstream releases.

Update Source-Installed Composer

In contrast, Composer installed from the official script updates itself directly. Since the binary lives in /usr/local/bin (a root-owned directory), you must use sudo:

sudo composer self-update

If you are already running the latest version, the output confirms:

You are already using the latest available Composer version 2.9.2 (stable channel).

Run this command periodically to receive security fixes and new features. Composer’s stable channel receives updates frequently.

Basic Composer Usage

With Composer installed, you can now manage PHP dependencies efficiently. The following sections cover the essential commands for everyday use.

Initialize a New Project

Create a new project by generating a composer.json file interactively. Navigate to your project directory and run:

composer init

This wizard prompts for project name, description, author, licensing, and initial dependencies. Alternatively, for quick setup, add the -n flag to accept defaults.

Add Dependencies

Install packages with the require command. For example, to add Monolog (a popular logging library):

composer require monolog/monolog

As a result, Composer resolves dependencies, downloads the packages, and updates your project files:

Using version ^3.8 for monolog/monolog
./composer.json has been created
Running composer update monolog/monolog
Loading composer repositories with package information
Updating dependencies
Lock file operations: 2 installs, 0 updates, 0 removals
  - Locking monolog/monolog (3.8.1)
  - Locking psr/log (3.0.2)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
  - Installing psr/log (3.0.2): Extracting archive
  - Installing monolog/monolog (3.8.1): Extracting archive
Generating autoload files

During this process, Composer creates or updates three key items in your project:

  • composer.json records your declared dependencies and their version constraints
  • composer.lock pins the exact installed versions, ensuring identical installations across machines
  • vendor/ directory contains all downloaded packages and the autoloader

Use Autoloading in PHP Scripts

Composer generates an autoloader that handles class loading automatically. Include it once at the top of your PHP scripts:

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

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Create a log channel
$log = new Logger('app');
$log->pushHandler(new StreamHandler('app.log', Logger::WARNING));

// Add log entries
$log->warning('This is a warning message');
$log->error('This is an error message');

Next, save this as script.php and execute it:

php script.php

Consequently, the script creates an app.log file containing entries like:

[2025-01-15T12:34:56.123456+00:00] app.WARNING: This is a warning message [] []
[2025-01-15T12:34:56.123789+00:00] app.ERROR: This is an error message [] []

In this way, the autoloader eliminates the need for individual require statements for each dependency.

Update Dependencies

Keep your project’s packages current with the update command, which checks for newer versions matching your constraints:

composer update

Alternatively, to update a single package while leaving others unchanged:

composer update monolog/monolog

Afterwards, commit the modified composer.lock file so other team members receive the same versions.

Troubleshoot Composer Installation Issues

Fix Signature Verification Failures

Signature mismatches typically mean the installer downloaded incompletely or a cached version is outdated. Remove the existing file, re-download, and verify again:

rm -f /tmp/composer-setup.php
curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php
HASH=$(curl -sS https://composer.github.io/installer.sig)
php -r "if (hash_file('SHA384', '/tmp/composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('/tmp/composer-setup.php'); } echo PHP_EOL;"

If failures persist, additionally check your network connection and ensure no proxy is modifying downloaded content.

Resolve PHP Version or Extension Errors

Composer requires PHP 7.2.5 or newer plus the CLI, cURL, ZIP, and mbstring extensions. If the installer reports “PHP not found” or “Missing ext-zip,” verify your PHP setup:

php -v
php -m | grep -E 'curl|zip|mbstring'

The expected output should show your PHP version and list the required extensions. If any are missing, install them accordingly:

sudo apt install php-cli php-zip php-curl php-mbstring

Handle Permission Denied in /usr/local/bin

If the installer cannot write to /usr/local/bin, install Composer to your home directory first, then move it with elevated privileges:

php /tmp/composer-setup.php --install-dir=$HOME --filename=composer
sudo install -m 755 $HOME/composer /usr/local/bin/composer
rm $HOME/composer

This approach avoids running the PHP installer with sudo while still placing the final binary in the system directory.

Remove Composer

If you no longer need Composer, remove it using the method matching your original installation.

Remove APT Installation

Uninstall the repository-installed package with APT:

sudo apt remove composer

Since Composer installed many PHP dependencies automatically, remove orphaned packages no longer required by other software:

sudo apt autoremove

This cleans up PHP extensions and libraries that were installed solely as Composer dependencies.

Remove Source Installation

For the manually installed binary, simply delete it from /usr/local/bin:

sudo rm /usr/local/bin/composer

Additionally, if you installed PHP extensions specifically for Composer and no other applications use them, clean up with:

sudo apt autoremove

Remove Composer Cache and Configuration

Furthermore, Composer stores cached packages and configuration in your home directory. To remove all traces, delete these directories:

Warning: The following commands permanently delete Composer’s cached packages and global configuration. If you have global Composer packages installed or custom configuration, back them up first.

rm -rf ~/.composer
rm -rf ~/.cache/composer
rm -rf ~/.config/composer

Finally, after removal, verify Composer is no longer available:

which composer

No output confirms the binary is gone.

Conclusion

With Composer installed, your Ubuntu system now handles PHP dependency management automatically. Specifically, the tool resolves version conflicts, downloads packages from Packagist (the PHP package repository), and generates autoloaders that simplify including libraries in your code. Whether you chose the stable APT package or the latest upstream release, you can now manage PHP projects with proper dependency isolation and reproducible builds using composer.lock files.

Leave a Comment