How To Install Composer On Ubuntu

Last Updated: Apr. 11th 2023 at 10:35am Tags: blog codeigniter laravel php slim symfony ubuntu yii

Composer is a package manager for PHP.
Most PHP frameworks and projects utilize its feature for updates. Learn more at Composer’s official website.

Requirements

You need curl to download composer and you need php to run composer.

sudo apt update && sudo apt upgrade -y
sudo apt install php-cli php-curl php-xml curl

Extras

wget and apt-utils have nothing to do with composer, but I commonly use them in these tutorials, now would be a good time to install them. Feel free to skip this step.

sudo apt-get install -y wget apt-utils git php-intl

Install composer

Installing composer is really easy, you just need to run the following one liner:

sudo curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

Download’s the installer from the official website and installs it to the global bin directory as just ‘composer’. It requires root permissions for install.

Using Composer

To list available commands for composer use list:

composer list

To install the defined dependencies for your project, run the install command.

composer install

Find Packages

You can see packages available for download by going to Packagist.

Bash script

# Check if composer is installed and install it if not
if ! command -v composer &> /dev/null
then
    echo "Composer not found, installing..."
    EXPECTED_CHECKSUM="$(curl -s https://composer.github.io/installer.sig)"
    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    ACTUAL_CHECKSUM="$(php -r "echo hash_file('sha384', 'composer-setup.php');")"

    if [ "$EXPECTED_CHECKSUM" != "$ACTUAL_CHECKSUM" ]
    then
        >&2 echo 'ERROR: Invalid installer checksum'
        rm composer-setup.php
        exit 1
    fi

    php composer-setup.php --quiet
    RESULT=$?
    rm composer-setup.php
    sudo mv composer.phar /usr/local/bin/composer

    if [ $RESULT -eq 0 ]
    then
        echo "Composer installed successfully"
    else
        echo "Error installing Composer"
        exit 1
    fi
fi

Reference

Comments

You need to login to comment.