Fellipe Sanches' website

Category: PHP

  • Installing Composer the right way

    If you search online for ways to install Composer on Ubuntu, you’ll probably find suggestions like:

    sudo apt install composer

    It looks simple… but it’s actually one of the worst ways to install Composer.
    Here’s why:

    • It almost always installs an outdated version of Composer.
    • Composer adapts quickly to new PHP versions — Ubuntu packages don’t.
    • apt installs Composer system-wide, which requires sudo even though Composer doesn’t need root privileges.
    • You lose access to composer self-update, because you must wait until Ubuntu updates the package (which often never happens).

    So… let’s install Composer the right way.

    Install Composer in Your Project Root

    In the root of your project run:

    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    php -r "if (hash_file('sha384', 'composer-setup.php') === 'c8b085408188070d5f52bcfe4ecfbee5f727afa458b2573b8eaaf77b3419b0bf2768dc67c86944da1544f06fa544fd47') { echo 'Installer verified'.PHP_EOL; } else { echo 'Installer corrupt'.PHP_EOL; unlink('composer-setup.php'); exit(1); }"
    php composer-setup.php
    php -r "unlink('composer-setup.php');"

    This installs Composer directly from the official source.

    At this point, Composer works, but only if you run: php composer.phar.

    Pretty annoying, right?

    Let’s make it easier.

    Create a Local Composer Command (Project Only)

    So, let’s improve this, putting a symlink to your project uses its own composer command.

    In the same folder where composer.phar is located, create a blank file named composer, and edit it:

    touch composer
    vim composer

    Add this content and save it.

    #!/usr/bin/env bash
    php "$(dirname "$0")/composer.phar" "$@"
    

    Back to the shell, make it executable:

    chmod +x composer

    Now your project has its own composer executable…

    s$ ls -l
    total 3416
    -rw-r--r--  1 fellipe fellipe     841 Nov 10 23:01 README.md
    -rwxr-xr-x  1 fellipe fellipe      61 Nov 21 11:38 composer
    -rw-r--r--  1 fellipe fellipe     315 Nov 10 20:27 composer.json
    -rw-r--r--  1 fellipe fellipe  165048 Nov 10 20:27 composer.lock
    -rwxr-xr-x  1 fellipe fellipe 3281618 Nov 20 21:42 composer.phar
    drwxr-xr-x 10 fellipe fellipe    4096 Nov 20 19:46 vendor

    …and you can just run ./composer

    $ ./composer --version
    Composer version 2.9.2 2025-11-19 21:57:25
    PHP version 8.4.15 (/usr/bin/php8.4)

    Summary

    • You don’t put anything in $HOME/bin.
    • You don’t modify your global PATH.
    • You don’t need sudo.
    • You create a small wrapper script that works only inside this project.
    • You gain the flexibility to use different Composer versions per project, and you avoid any security risk from installing system-wide packages as root.

    Nice, right?