Join my Laravel for REST API's course on Udemy 👀

Use Composer with a specific PHP version

May 28, 2022  ‐ 2 min read

Are you using different PHP versions on your local development machine just like me? Then you might have encountered the following error when installing packages with composer, again, just like me.

$ composer require intervention/image:^2.7
...
Your requirements could not be resolved to an installable set of packages.

Problem 1
  - Root composer.json requires php ^7.4 but your php version (8.1.5) does not satisfy that requirement.
...

Composer defaults to the default PHP version. That is, the shebang comment at the top of the executable composer file indicates that the php binary should be used.

#!/usr/bin/env php

You can find out which version this is by running php --version on your terminal.

Now, in order to use the PHP version of your preference you should run the composer binary with the desired php binary. For this you need the exact path to the composer binary. On my machine the composer binary is located at /usr/local/bin/composer.

Thus the command would look the following for me. Using PHP version 7.4.

php7.4 /usr/local/bin/composer require intervention/image:2.7.2

To find out where composer is installed on your machine you can run which composer in your terminal:

$ which composer
/usr/local/bin/composer

To make this a bit easier you can make this a one step process as well.

$ php7.4 $(which composer) require intervention/image:2.7.2

If you are required to run this command often then you might want to make it an alias in your shell.