linux change php version
How To Switch Between Multiple PHP Versions In Ubuntu
This brief tutorial walks you through the steps to switch between multiple PHP versions in Ubuntu Linux and its derivatives. This guide is officially tested on Ubuntu 18.04 LTS server edition. It may work on other older or newer Ubuntu versions as well.
Introduction
Sometimes, the most recent version of an installed package might not work as you expected. Your application may not compatible with the updated package and support only a specific old version of package.
In such cases, you can simply downgrade the problematic package to its earlier working version in no time. Refer our old guides on how to downgrade a package in Ubuntu and its variants here and how to downgrade a package in Arch Linux and its derivatives here.
In some situations, you need not to downgrade the problematic packages. In Linux, we can use multiple versions of the same package at the same time, side by side.
For instance, let us say you are testing a PHP application in LAMP stack deployed in Ubuntu 18.04 LTS. After a while you find out that the application worked fine in PHP 5.6, but not in PHP 7.2 (Ubuntu 18.04 LTS installs PHP 7.x by default).
Are you going to reinstall PHP or the whole LAMP stack again? Not necessary.
You don’t even have to downgrade the PHP to its earlier version. You can simply switch to the previous working PHP version in couple minutes.
1. Switch Between Multiple PHP Versions
Let us check the default installed version of PHP using command:
Sample output:
As you can see, the installed version of PHP is 7.2.7.
After testing your application for couple days, you find out that your application doesn’t support PHP 7.2. In that case, it is a good idea to have both PHP 5.x version and PHP 7.x version, so that you can easily switch between any supported version at any time.
You don’t need to remove PHP 7.x or reinstall LAMP stack. You can use both PHP 5.x and 7.x versions together.
I assume you didn’t uninstall php 5.6 in your system yet. Just in case, you removed it already, you can install it again using a PPA like below.
You can install PHP 5.6 from a PPA:
1.1. Switch from PHP 7.x to PHP 5.x
1.1.1 First disable PHP 7.2 module using command:
Sample output:
1.1.2. Next, enable PHP 5.6 module:
1.1.3 Set PHP 5.6 as default version using command:
1.1.4. Alternatively, you can run the following command to set which system wide version of PHP you want to use by default.
1.1.5. Enter the selection number to set it as default version or simply press ENTER to keep the current choice.
1.1.6. If you have installed other PHP extensions, set them as default as well.
1.1.7. Finally, restart your Apache web server:
Now, check if PHP 5.6 is the default version or not:
Sample output:
2. Switch from PHP 5.x to PHP 7.x
Likewise, you can switch from PHP 5.x to PHP 7.x version by running the following commands one after another.
A word of caution:
If you want prevent PHP to be automatically upgraded in future, refer the following guide.
How can I change php-cli version on Ubuntu 14.04?
I am new to using Linux and I broke some php settings while tampering.
I want to have both versions match.
How can i fix my command line PATH to also use php 5.6?
7 Answers 7
From PHP 7.1 => PHP 5.6
From PHP 5.6 => PHP 7.1
You can change the versions as you want.
You can check this tutorial
This explanation is based on Ubuntu 16.04 but is expected to work for other versions too
Most answers here manipulate the php-version by using the command
While the command is quite useful it’s never explained what it does exactly. Here comes the explanation, including backup and some options:
Get the Information
Finally we still want to know which php-versions we can link. The following command shows a list of the currently available php-versions in /usr/bin/ :
Backup the information
if you like you still can add the result of the command ls like shown above:
. and the available PHP-versions:
Change the PHP-version for commandline
Control
Checking the change:
The change was accepted and the used version is an older one now.
This means the PHP-version is consistent with the man-page and the command man php returns the right descriptions for the current php-version and no manual adjustments concerning the man-page have been required.
Here is more interactive way:
You’ll see the list of all available versions and select one of them
You can try setting the path to the correct php version on the terminal command line:
Modify the path to match your own path to PHP 5.6 (ie. if it was installed first, it might be something like «/usr/bin/php»).
The «$PATH» at the end appends the current path value, so don’t forget to use it.
check what you have before changing
change everything to php 7.2
Plesk
Just to say, if your server is managed using Plesk (like mine is at the time of searching through this question) then you may not have later PHP versions in /usr/bin
In this case, your PHP versions will be located in /opt/plesk/php so you can instead use the following command as a super user (run su first if you’re not a super user) to set your PHP CLI version (to 7.3 in this example):
Switch php versions on commandline ubuntu 16.04
I have installed php 5.6 and and php 7.1 on my Ubuntu 16.04
I know with Apache as my web server, I can do
When I disable php7.1 in Apache modules and enable php 5.6, Apache recognizes the change and uses php 5.6 interpreter as expected.
But when I run internal php web server from the commandline:
18 Answers 18
Interactive switching mode
Manual Switching
From PHP 5.6 => PHP 7.1
Default PHP 5.6 is set on your system and you need to switch to PHP 7.1.
From PHP 7.1 => PHP 5.6
Default PHP 7.1 is set on your system and you need to switch to PHP 5.6.
should work for all ubuntu versions after 16.04 (18.04 and 20.04)
This is what you should see as a response
Choose the appropriate version
To list all available versions and choose from them :
I think you should try this
From php5.6 to php7.1
From php7.1 to php5.6
You can create a script to switch from versions: sudo nano switch_php then type this:
exit and save make it executable: sudo chmod +x switch_php
That’s it you can now easily switch form PHP7 to PHP 5.6!
In that case you can switch between the PHP versions to suit your requirements.
Switch From PHP 5.6 => PHP 7.2
And vice-versa, Switch From PHP 7.2 => PHP 5.6
in ubuntu 20.04 switching between PHP 8.0 and PHP 7.4 version:
DOWNGRADE PHP 8.0 to PHP 7.4
UPGRADE PHP 7.4 to PHP 8.0
PHP 8.0.3 (cli) (built: Mar 5 2021 07:54:13) ( NTS ) Copyright (c) The PHP Group Zend Engine v4.0.3, Copyright (c) Zend Technologies with Zend OPcache v8.0.3, Copyright (c), by Zend Technologies
PHP 7.4.16 (cli) (built: Mar 5 2021 07:54:38) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies with Zend OPcache v7.4.16, Copyright (c), by Zend Technologies
Как изменить версию php в консоли
Если у вас установлено несколько версий php в системе, то при вызове команды php в консоли, будет использоваться одна из них. Иногда необходимо для каких-то скриптов или сервисов управлять версией php в консоли. Я расскажу, как ее изменить.
Посмотрим, где располагается сам бинарник php:
Оказывается, что /usr/bin/php является символьной ссылкой. Посмотрим, куда она ведет:
Это еще одна символьная ссылка. Смотрим, куда ведет она:
На седьмую версию php. Заменим ее на 5.6, которая у меня установлена по адресу /usr/local/bin/php. Редактируем символьную ссылку:
Проверяем текущую версию php в консоли:
Все получилось. Теперь в консоли по-умолчанию будет использоваться нужная версия php. Можно проверять скрипты, не указывая полный путь к нужной версии.
Директории проверяются в том порядке, как они перечислены. Где будет найдено первое совпадение, тот файл и будет использоваться. В моем случае директория /usr/bin, где жила символьная ссылка на php7.0 стоит раньше, чем /usr/local/bin, где расположена php5.6. Можно было просто поменять местами эти директории в PATH и версия по-умолчанию станет 5.6, так как ее бинарник php будет найден раньше.
Более гибко управлять версиями php в системе можно с помощью программы update-alternatives. Она может делать в том числе и то, что мы сейчас проделали, только автоматически, в зависимости от своих настроек. С ее помощью можно более гибко управлять версиями, задавать приоритеты использования той или иной версии, быстро их переключать в полуавтоматическом режиме.
Онлайн курс по Kubernetes
Онлайн-курс по Kubernetes – для разработчиков, администраторов, технических лидеров, которые хотят изучить современную платформу для микросервисов Kubernetes. Самый полный русскоязычный курс по очень востребованным и хорошо оплачиваемым навыкам. Курс не для новичков – нужно пройти вступительный тест.
Жонглируем версиями PHP в системе
Проблема “ хочу новую версию %software% на моем стареньк … стабильном Debian/CentOS…” так же стара, как *nix-мир. Способов добиться желаемого хватает. Есть масса решений как притащить в систему несколько версий одного и того же софта. Но дальше хочется не просто иметь ещё одну версию, но и управлять тем, какая из версий доступна в системе по умолчанию, для конкретных приложений или пользователей.
Что делать, если хочется сменить системную версию PHP на одну из кастомных сборок? Давайте отталкиваться от того, что у вас на сервере уже установлено несколько версий PHP и вы хотите, чтобы в консоли команда php была конкретной версии, отличающаяся от той, что шла с системой. В этой статье я расскажу, как правильно это настроить, чтобы не было проблем с будущими пакетными обновлениями.
В качестве примера возьмём сервер на CentOS 7, где установлен родной PHP:
Также на сервере установлен наш Plesk с парой своих сборок PHP:
Допустим, мы хотим переключить систему на использование PHP 5.6 по умолчанию (переключать глобально PHP с версии 5.4 на 7 как-то сс… страшно — чему-то в системе может поплохеть от такого). Бинарь PHP 5.6 лежит у нас тут:
Как же сделать так, чтобы система использовала эту, нужную нам, версию PHP?
Сначала посмотрим на системную переменную PATH
В ней перечислен список директорий, в которых ищутся программы по имени. Главный нюанс — поиск в директориях происходит последовательно и используется первый найденный результат. Текущий путь до текущего бинарника PHP мы можем увидеть с помощью команды:
Теперь, давайте зарегистрируем все доступные версии PHP с помощью этой команды:
Цифры 10, 20 и 30 — это приоритет. Он работает для автоматического выбора, если администратор сам не выбрал конкретную версию. Самое большое число определяет выбор «по умолчанию».
Проверим, что php теперь указывает на созданную командой симлинку:
Давайте разберемся, что же update-alternatives сделала для нас:
Как видно, она создала цепочку симлинок и теперь по требованию просто меняет промежуточную симлинку на нужный нам бинарь.
Давайте переключимся на PHP версии 5.6, которая идет в поставке с Plesk’ом:
Проверяем, что переключение произошло:
Все отлично работает. Теперь в системе используется нужная нам версия PHP и я не опасаюсь, что эта настройка слетит при следующих пакетных обновлениях.
С помощью update-alternatives можно выбирать не только версию PHP, но и многие другие вещи, например разные версии phpunit или редактор по умолчанию в системе. Подход этот универсален для различных систем. Не изобретая своего велосипеда, используя существующие инструменты, вы можете быть уверенным, что не устроили для ваших коллег квеста “Ну почему оно так работает?!”. Настраивайте свою систему правильно.