Home » Php » How to specify to use a specific PHP version when running "composer install"?

How to specify to use a specific PHP version when running "composer install"?

Posted by: admin February 25, 2020 Leave a comment

Questions:

In a server we have a few of webapp and actually have both 7.2 and 7.4 installed.

When running composer install, it use the PHP setup as default in the system, actually the 7.4.

In fact,

$ which php
/usr/bin/php

$ php -v
PHP 7.4.2 (cli) ...

$ ls -la /usr/bin/php
lrwxrwxrwx 1 root root 21 Nov 20 11:20 /usr/bin/php -> /etc/alternatives/php

$  ls -la /etc/alternatives/php
lrwxrwxrwx 1 root root 15 Feb 12 11:08 /etc/alternatives/php -> /usr/bin/php7.4

The app were I must execute composer install is a PHP 7.2, so I need the composer respect this.

I am sure it trying to use PHP 7.4 because it is complaining about php7.4-mbstring missing. But it’s installed and enabled for PHP 7.2.

How to&Answers:

There is more than one issue here.

First, you most likely don’t really need to tell composer to use one interpreter or another. If you know that the platform requirements are going to be correct at runtime, but the runtime executable is not the same than the install executable, you can simply say:

composer install --ignore-platform-reqs

This way composer won’t check that the runtime and extensions match what you declared on composer.json (but you’ll need to make sure that these requirements are fulfilled on the server where the project actually runs).


But if you really want to execute composer with a different runtime…

composer uses shebang + env to determine which PHP executable is going to use.

Basically it uses #!/usr/bin/env php to find which php executable is available, same as you were doing.

If you want to use a different executable, you just need to be explicit about it.

E.g. if your PHP 7.2 is installed at /usr/bin/php7.2 and composer at /usr/local/bin/composer, you just need to do:

# /usr/bin/php7.2 /usr/local/bin/composer install