How to Install Composer on Ubuntu: A Step-by-Step Guide

Composer is a widely used dependency management tool for PHP, designed to simplify the installation and updating of project dependencies. It analyzes the dependencies of a given project and installs the necessary packages using the correct versions based on project requirements. Composer is often used to initiate new projects based on popular PHP frameworks like Symfony and Laravel.

This tutorial provides a step-by-step guide on installing and using Composer on Ubuntu 22.04.2.

Installing PHP and Additional Dependencies

Before installing Composer, you must ensure that PHP and a few additional dependencies are installed on your system. If you already have these installed, skip to the next section. Otherwise, follow these steps:

1. Open a terminal window on your Ubuntu system.
2. To update the package list, enter the following command:

sudo apt update

3. Enter the command below to install PHP and any additional dependencies:

sudo apt-get install -y php8.1-cli php8.1-common php8.1-mysql php8.1-zip php8.1-gd php8.1-mbstring php8.1-curl php8.1-xml php8.1-bcmath unzip curl

You may also refer to the “Complete PHP Installation Guide” for further details.

Installing Composer

Once you have PHP and its dependencies installed, you can proceed with the installation of Composer.
1. Use the following command to download the Composer to your current directory:

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

2. To verify the SHA-384 checksum of the installer, use this command:

php -r "if (hash_file('sha384', 'composer-setup.php') === '55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

If the verification is successful, you will receive a message similar to this:

Installer verified

3. Run the installer by entering the following command:

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

This command will download and install Composer as a system-wide command named composer in the /usr/local/bin directory.

4. Remove the installer by executing the following command:

php -r "unlink('composer-setup.php');"

5. To check if the installation was successful, run:

composer

If the installation was successful, you should see a screen similar to this: