Debian update php version

How to install/update PHP 8.0 (Debian/Ubuntu)

PHP 8.0 brings several new features and improvements in performance, syntax, security, and stability. Installing PHP 8.0 on just about any sort of server/development setup is made easy with pre-compiled packages available in all currently supported Debian and Ubuntu versions.

Extensions and Dependency Changes in PHP 8.0

Despite the massive amount of changes, there are not many changes in PHP 8.0 in its dependencies and extension structure.

  1. JSON extension is now always available, and there is no compile flag to exclude it. This means there is no need to explicitly install php-json packages anymore.
  2. xmlrpc extension is moved to PECL with good reasons. Software repositories mentioned in this post does not include xmlrpc extension for PHP 8.0.

In addition, the GD extension has its name changed from php_gd2.dll to php_gd.dll in Windows that will be covered in a separate article.

INI changes in PHP 8.0

There are few INI file changes as well.

Due to new features and changes in PHP 8.0,

  • The new JIT feature in PHP 8.0 adds several new INI directives.
  • zend.exception_string_param_max_len INI setting due to Configurable exception stack trace string length

Installing PHP 8.0 on Ubuntu and Debian is made easy by the great efforts of Ondřej Surý. He maintains a PHP PPA that contains PHP 8.0 and several popular PECL extensions ready to install on any current Debian/Ubuntu system.

1. List existing PHP packages

If you are updating from an existing PHP version to 8.0, it’s important to get a list of existing PHP packages. Albeit the small extension changes, installing the PHP 8.0 counterpart packages is the easiest way to make sure the upgrade is smooth and covers the same packages from the current PHP version.

dpkg -l | grep php | tee packages.txt

This command will list all the packages containing name php , and writes it to a file named packages.txt , which can be referred anytime.

Читайте также:  Дата и время

2. Add ondrej/php PPA

sudo add-apt-repository ppa:ondrej/php # Press enter when prompted. sudo apt-get update
sudo apt install apt-transport-https lsb-release ca-certificates wget -y sudo wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg sudo sh -c 'echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list' sudo apt update

Steps above will add the PPA as a source of packages, that contains all PHP packages and their dependencies such as argon2 and libzip .

3. Install PHP 8.0 and extensions

All PHP 8.0 packages follow php8.0-NAME pattern, and php8.0-common package includes a sensible set default of extensions (such as `php8.0-).

Install PHP 8.0 with CLI

sudo apt install php8.0-common php8.0-cli -y

This command will install several PHP extensions due to php8.0-common , and the CLI for PHP 8.0.

You can confirm the installation by running:

php -v # Show PHP version. php -m # Show PHP modules loaded.

Additional extensions

You can install additional extensions from the same php8.0-NAME pattern. Refer to the packages.txt file to see a list of existing packages if you are upgrading an existing system.

Note that you do not need to install php8.0-json as it is now included by default.

An example to install a few more useful extensions:

For development environments, code coverage tools or the Xdebug debugger can be installed as well.

sudo apt install php8.0-pcov # PCOV code coverage tool sudo apt install php8.0-xdebug # Xdebug debugger

Install Server APIs

Depending on the web server you use, you will need to install additional packages to integrate with the web server.

For Apache using mpm_event , Nginx, Litespeed, etc., php8.0-fpm package provides integration with PHP 8.0 via FPM.

sudo apt install php8.0-fpm

For Apache using mod_php , install libapache2-mod-php8.0 .

sudo apt install libapache2-mod-php8.0

Note that the Apache2Handler is renamed to php_module from php7_module in PHP 8.0. The libapache2-mod-php8.0 package automatically configures the Apache module location, but if you are updating from an existing PHP setup, you might need to update configuration files; in particularly blocks.

4. Test PHP 8.0 installation

To test the PHP installation and the extensions, run the following commands:

# php -v PHP 8.0.0-dev (cli) (built: Oct 4 2020 14:04:36) ( NTS ) Copyright (c) The PHP Group Zend Engine v4.0.0-dev, Copyright (c) Zend Technologies # php -m [PHP Modules] Core ctype curl . 

Purge old PHP versions

If the new installation is working as expected, you can remove the old PHP packages from the system.

This assumes you are using PHP 7.4 as the previous version. Change php7.4 part of the command above with the appropriate PHP version.

Running PHP 8.0 with Other Versions

Instead of removing old PHP versions, it is also possible to run multiple PHP versions side-by-side.

The PHP 8.0 CLI will be installed at /usr/bin/php8.0 location by default. Similarly, other PHP binary files will be located in the same directory ( /usr/bin/php7.4 , /usr/bin/php7.3 , etc). The default php name will be symlinked to the latest PHP version by default, but it is possible to change where the default php command links to.

Читайте также:  Php mysql select table names

The update-alternatives command provides an easy way to switch between PHP versions for PHP CLI.

sudo update-alternatives --config php

This brings up a prompt to interactively select the alternative PHP binary path that php points to.

There are 2 choices for the alternative php (providing /usr/bin/php). Selection Path Priority Status ------------------------------------------------------------ * 0 /usr/bin/php8.0 80 auto mode 1 /usr/bin/php7.4 74 manual mode 2 /usr/bin/php8.0 80 manual mode Press to keep the current choice[*], or type selection number:

To set the path without the interactive prompt:

update-alternatives --set php /usr/bin/php7.4

What’s new and changed in PHP 8.0

For a complete list of changes in PHP 8.0, see What’s new and changed in PHP 8.0

PHP 8 logo is by Vicent PONTIER. Debian and Ubuntu icons are from Strongicon and ProGlyphes.

Recent Articles on PHP.Watch

How to extend lifetime of legacy PHP applications

How to extend lifetime of legacy PHP applications

As PHP continue to evolve with new breaking changes, and while that is great for most PHP applications, there are legacy applications that can’t justify the human and financial cost of keeping up. Here is a guide on how to extend the lifetime of legacy PHP applications with security updates and maintenance.

PHP 8.2 Highlights: What

PHP 8.2 Highlights: What’s New and Changed

How to install/upgrade PHP 8.2 on Debian and Ubuntu systems

How to install/upgrade PHP 8.2 on Debian and Ubuntu systems

You will receive an email on last Wednesday of every month and on major PHP releases with new articles related to PHP, upcoming changes, new features and what’s changing in the language. No marketing emails, no selling of your contacts, no click-tracking, and one-click instant unsubscribe from any email you receive.

© 2018-2023 PHP.Watch, with ❤ from Ayesh • About PHP.Watch

Источник

Как установить/обновить PHP 8.0 (Debian/Ubuntu/Mint)

Как установить/обновить PHP 8.0 (Debian/Ubuntu/Mint)

PHP 8.0 содержит много новых функций и улучшений производительности, синтаксиса, безопасности и стабильности. Установка PHP 8.0 практически на любой сервер упрощается благодаря предварительно скомпилированным пакетам, доступным во всех поддерживаемых в настоящее время версиях Debian и Ubuntu.

Изменения расширений и зависимостей в PHP 8.0

Несмотря на огромное количество изменений в PHP 8.0, в принципе было произведено не так много изменений в его зависимостях и структуре расширений.

Расширение JSON теперь всегда доступно , и нет флага компиляции для его исключения. Это означает, что больше нет необходимости явно устанавливать пакет php-json.

Расширение xmlrpc перемещено в PECL по уважительным причинам. Репозитории программного обеспечения, упомянутые в этом посте, не включают xmlrpc расширения для PHP 8.0.

Кроме того, в Windows название расширения GD было изменено с php_gd2.dll на php_gd.dll.

Читайте также:  Run java program in jar file

Изменения в файле INI PHP 8.0

Также есть несколько изменений в файле INI.

  • По умолчанию утверждения вызывают исключения — ( assert.exception=1)
  • Отображение ошибок по умолчанию установлено на E_ALL — ( error_reporting=-1)
  • При запуске теперь по умолчанию ошибки включены — ( display_startup_errors=1)
  • Новая функция JIT в PHP 8.0 добавляет несколько новых директив INI.
  • Параметр zend.exception_string_param_max_len для настраиваемой длины строки трассировки стека исключений

Установка PHP 8

1. Необходимо добавить репозиторий ondrej/phpPPA

sudo apt-get install software-properties-common 
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt install apt-transport-https lsb-release ca-certificates wget -y 
sudo wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
sudo sh -c 'echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list'
sudo apt update

Приведенные выше шаги добавят PPA в качестве источника пакетов, который содержит все пакеты PHP и их зависимости, такие как argon2 и libzip.

2. Установите PHP 8.0 и нужные расширения

Все пакеты PHP 8.0 следуют шаблону php8.0-имя_расширения , и пакет php8.0-common включает необходимый набор расширений по умолчанию.

sudo apt install php8.0-common

Установите PHP 8.0 CLI для работы в консоли

sudo apt install php8.0-cli

Вы можете установить дополнительные расширения по тому же шаблону php8.0-имя_расширения. Обратите внимание, что вам не нужно устанавливать, так php8.0-json, так как теперь он включен по умолчанию.

Пример установки еще нескольких полезных расширений:

Для разработки также могут быть установлены инструменты покрытия кода или отладчик Xdebug.

sudo apt install php8.0-pcov # PCOV code coverage tool 
sudo apt install php8.0-xdebug # Xdebug debugger

Установка PHP8 fpm

В зависимости от используемого веб-сервера вам необходимо будет установить дополнительные пакеты для интеграции с веб-сервером.

Для использования Apache mpm_event, Nginx, Litespeed и т. д. нужно будет установить php8.0-fpm

sudo apt install php8.0-fpm

Для использования Apache mod_php установите libapache2-mod-php8.0

sudo apt install libapache2-mod-php8.0

Чтобы проверить установку PHP и расширений, выполните следующие команды:

# php -v 
PHP 8.0.0 (cli) (built: Nov 26 2020 18:04:36) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.0, Copyright (c) Zend Technologies

# php -m
[PHP Modules]
Core
ctype
curl
.

Если вам потребуется удалить старые пакеты PHP, можно воспользоваться командой

Это предполагает, что вы используете PHP 7.4 в качестве предыдущей версии. Но будьте осторожны, сначала сто раз проверьте что вы больше не используете старые версии в своих проектах.

Смена установленной версий PHP по умолчанию.

Если вдруг вас не устраивает новая установленная версия PHP, вы можете сменить другую версию по умолчанию, командой:

sudo update-alternatives --config php
Есть 7 вариантов для альтернативы php (предоставляет /usr/bin/php). 

Выбор Путь Приор Состояние
------------------------------------------------------------
0 /usr/bin/php8.0 80 автоматический режим
1 /usr/bin/php5.6 56 ручной режим
2 /usr/bin/php7.0 70 ручной режим
3 /usr/bin/php7.1 71 ручной режим
4 /usr/bin/php7.2 72 ручной режим
5 /usr/bin/php7.3 73 ручной режим
* 6 /usr/bin/php7.4 74 ручной режим
7 /usr/bin/php8.0 80 ручной режим

Press to keep the current choice[*], or type selection number: 6

И введя номер нужной вам предыдущей версии PHP.

Источник

Оцените статью