Articles on: cPanel

How do I use PHP Composer?

Composer is a powerful dependency management tool for PHP, allowing you to install and manage libraries easily. This guide explains how to use Composer, whether through a SSH (shell access) or a PHP script.


Option 1: Using Composer with Shell Access


If you have SSH/Terminal access through a Business or Reseller package, you can directly run Composer commands in the terminal.


  1. Open Terminal / SSH Session:
  • cPanel -> Advanced -> Terminal
  • or connect via SSH using your username


  1. Navigate to your application directory, eg


cd /home/username/public_html/my_php_app


  1. Run Composer Commands:


  • For example, to install dependencies from composer.json:
composer install


For further commands and options, refer to the list of commands below.


Option 2: Using Composer via PHP Script


If shell access is unavailable, you can run Composer commands using a PHP script.


Example PHP script:


Save the following code in a .php file (e.g., composer_run.php)


<?php

// Set the COMPOSER_HOME environment variable
putenv('COMPOSER_HOME=' . getenv('HOME') . '/.composer');

// Run the Composer command
$output = shell_exec('/opt/cpanel/composer/bin/composer install 2>&1');

// Display the output
echo "<pre>$output</pre>";


  1. Create the composer_run.php file


  • Save the script in your project directory, alongside your composer.json file.
  • Adjust "composer install" command as required, refer to the list of commands below.


  1. Access the Script



  1. Verify the output


The script will display the output of the composer install command. Check for any errors and ensure the vendor directory is created.


Composer Commands


  • To install dependencies from composer.json:
composer install


  • To add a new package (e.g., monolog/monolog):


composer require monolog/monolog


  • To update all dependencies:


composer update


Troubleshooting


If you receive a message similar to "Your Composer dependencies require a PHP version ">= 8.1.0"


This indicates that the current PHP version does not meet the requirements specified in your project's composer.json file. To resolve this issue, you will need to update the PHP version set for your account.


Please refer to the following article for detailed instructions: How do I set the PHP version, extensions, and options in cPanel?

Updated on: 21/11/2024

Was this article helpful?

Share your feedback

Cancel

Thank you!