We’ve talked about how to install composer on Windows. But your website which uses composer packages in php is typically on a Linux server. So, today we will present you with a composer installation guide that teaches you how to install composer in Linux. The interesting part is you never download an executable program in the whole installation process. So the following composer installation commands will work on all kinds of linux such as ubuntu and debian. I will install composer on CentOS7. Run the following commands in bash to install composer in Linux:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" php -r "if (hash_file('sha384', 'composer-setup.php') === '55ce33d7678c5a611085589f1f3ddf8b3c52d662cd01d4ba75c0ee0459970c2200a51f492d557530c71c15d8dba01eae') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" php composer-setup.php php -r "unlink('composer-setup.php');"
Before installing composer, cd to the directory where you want to install composer in bash. This is typically the root directory of your website. The first step is to download composer-setup.php to current directory. The second step is to check if the downloaded file is corrupted. The third step is to execute the downloaded script to download another script composer.phar to current directory. The composer.phar is the main file of composer although it is just a php script that is run by php.
After installing composer, how to use composer to install library? Now, you are in the root directory of your website, execute the following command to install a package:
php composer.phar require xxx/yyy
This command will install the latest version of package xxx/yyy to the vendor directory under your current directory. If you want to use composer to install specific version of a package, you need to create a file composer.json to include the following content:
{ "require": { "xxx/yyy": "~1.0" } }
Then run the following command:
php composer.phar update --no-plugins --no-scripts
This will install xxx/yyy version 1.o to your system. Check the content of composer.json carefully. If you type something wrong, you may get the error:
./composer.json does not contain valid json
Now, you installed composer, used composer require to install packages you want. How to use the composer package in php? Using composer package in php project is easy. You just need to add the following line in your php file in current directory before using the classes/functions of the installed package:
require "vendor/autoload.php";
You do not need to manually include the php files of the package and other packages it relies on. All necessary files will be loaded by vendor/autoload.php.