Как обновить php на windows 10

I'm trying to get my Laravel project to work. But when I use composer update it says the following: This package requires php >=5.6.4 but your PHP version (5.5.12) does not satisfy that requiremen...

I’m trying to get my Laravel project to work. But when I use composer update it says the following:

This package requires php >=5.6.4 but your PHP version (5.5.12) does not satisfy that requirement.

I’m using WAMP which runs php version 7.0.4 this is also confirmed in the browser if I echo the php version. But when I use php -v in the console it shows that I’m using PHP version 5.5.12 (cli).

I’ve searched a bit around on google and I found out that it uses my windows PHP version instead of my webserver’s version. But I couldn’t find out how to update my PHP version on Windows.

My PATH contents are as shown in the following image

enter image description here

worldofjr's user avatar

worldofjr

3,8088 gold badges35 silver badges49 bronze badges

asked Sep 9, 2016 at 17:49

ThomH's user avatar

4

You can uninstall composer, and while re-installing it will ask you to point at your PHP directory which is going to be C:wamp64binphp (usually) at that point you can choose which PHP version you would want to use. good luck.

enter image description here

Jquestions's user avatar

Jquestions

1,6001 gold badge21 silver badges29 bronze badges

answered Oct 27, 2017 at 6:55

Moe Ismail Alhakeem's user avatar

3

This means you have yet another installation of PHP in your system. Check your Programs in Control Panel and remove such installation.

However, you can modify your PATH environment variable as well. Procedure

Just remove the path that points to any PHP installation directory.

Else, otherwise, if you are unsure about changing the PATH variable (which can lead to serious problems if not set well), you can just delete the directory that the PATH variable points to…. (I mean the PHP directory)

The totally better solution is to add the path of your PHP7 bin directory at the beginning of the PATH variable. You should also make available composer in this PHP7 bin directory.

Such as, replace the C:php in your path with C:wampbinphp7 or whatever the location of the PHP7 path is..

answered Sep 9, 2016 at 17:56

Huzaib Shafi's user avatar

Huzaib ShafiHuzaib Shafi

1,1239 silver badges24 bronze badges

3

To update PHP on Windows 10.

You must put the folder of the new PHP version in the same folder as the old.
You rename the old folder or you delete it, prefer rename the old folder,
now you write in a terminal console

php - v

PHP automatically check for a new version

answered Oct 18, 2020 at 14:27

Julien J's user avatar

1

if you had installed before xampp/wampp and composer globally you might had added php to you environment path to call it where ever you want, and now you want that composer use the new xampp with php the you recently installed, so go to system>advance tab> environment variable> maybe in PATH then search if you have something like C:xamppphp and edit to your new php location.

I had multiple versions off xampp for testing and composer globaly instaled for php 7.2

hello_world's user avatar

hello_world

7781 gold badge10 silver badges26 bronze badges

answered Jul 20, 2018 at 14:28

alexanderesmar's user avatar

Trying to upgrade PHP on windows? We can help you with it.

Here at Bobcares, we have seen several such Windows related queries as part of our Server Management Services for web hosts and online service providers.

Today we’ll see how to upgrade PHP on Windows.

How to upgrade PHP on windows

Now let’s take a look at how to upgrade the PHP in Windows.

1. First, make sure that Web Platform Installer is present in IIS. For that, open the Internet Information Systems and click on the server name. If Web Platform Installer is not present then click on the “Get New Web Platform Components”.

2. Now click on the “Install this extension” option on the web browser window that is opened. Then accept the license agreement and follow the prompts to install that Web Platform Installer.

3. Now re-open the IIS and click on the Server Name then Double-Click on the Web Platform Installer.

4. At the top-right of the Web Platform Installer, you can find a Search Window where you need to type “PHP”.

5. Then select the PHP version that you wish to install and click “Add” and “Install”. Also, ensure that you select the 64-bit or 32-bit, depending on the server environment.

6. Finally, now you have successfully upgraded the PHP installation. Then open the command prompt and enter the command iisreset to apply the new settings or you can simply reboot the server to apply the changes.

Selecting and Upgrading PHP on a Plesk server is as simple as selecting the version of your choice from a drop-down menu.

Upgrade PHP on Windows manually

1. First, open the Control Panel >> click on Programs and Features >> Turn Windows features on or off. Under the Internet Information Services, World Wide Web Services, Application Development Features, make sure that option CGI is checked. This will enable both the CGI and FastCGI services, which are recommended for PHP applications.

2. For Windows, download PHP from the below link.

http://windows.php.net/download/

We are using PHP as FastCGI. So we shall use the 64-bit Non-Thread Safe (NTS) version (i.e., php-7.1.1-nts-Win32-VC14-x64.zip).

3. Extract the file php-7.1.1-nts-Win32-VC14-x64.zip to its own folder.

4. Copy current PHP7 installation from v7.0 and rename the copy to v7.1.

5. Then copy all files from the PHP7 zip folder to the new renamed v7.1 folder.

6. Now edit the php.ini (C:Program FilesPHPv7.1php.ini) to reflect the new version (7.1) under [WebPIChanges]:

error_log=C:WINDOWStempPHP71x64_errors.log
extension_dir=”C:Program FilesPHPv7.1ext”
;extension=php_mysql.dll
extension=php_mysqli.dll
[PHP_WINCACHE]
extension=php_wincache.dll

MySQL extension was deprecated on PHP version 5.5 and removed on version 7. If it’s not excluded, you’ll see the following error:

PHP Warning: PHP Startup: Unable to load dynamic library ‘C:Program FilesPHPv7.1extphp_mysql.dll’ – The specified module could not be found.

in Unknown on line 0

7. Now open the IIS Manager and click on FastCGI Settings.

8. Then double-click on the PHP 7.0 settings and copy all the property values including the Environment Variables (PHP_FCGI_MAX_REQUESTS, PHPRC) and Advanced Settings. We are now going to reuse all the values from the existing installation instead of starting from scratch.

Once done, click the Cancel button.

9. Now from the FastCGI Settings window, click on Add Application… on the Actions pane on the right.

10. Then type in C:Program FilesPHPv7.1php-cgi.exe on the Full Path box.

11. Now enter all the values that you have copied from the Steps 8, except for the PHPRC where you want to update the value to 7.1 (i.e., C:Program FilesPHPv7.1).

After completion, click on OK.

12. Then go back to IIS Manager and click on Handler Mappings.

13. Search for PHP_via_FastCGI and double-click on it.

14. Now locate the new php-cgi.exe and change the value on the Executable (optional): accordingly. Click Yes when there is a dialog box asking you to create a FastCGI application for this executable.

Finally, click OK and exit the IIS Manager.

[Need any further assistance with Windows queries? – We are here to help you.]

Conclusion

In today’s writeup, we saw how our Support Engineers upgrade PHP on Windows.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

На чтение 4 мин. Опубликовано 10.06.2021

Рано или поздно придется обновлять софт, чтобы все функционировало на сервере или на одном лишь небольшом ПК исправно. Но не каждый пользователь понимает, как обновлять те или иные компоненты – сложная ситуация попадается время от времени.

Ввиду этого, придется пользователям воспользоваться руководством, в котором и будет вся основная информация по поводу обновления PHP на Windows, а также о том, что делать перед проведением такой процедуры.

Как обновить версию PHP на Windows?

Обновление PHP удобнее всего произвести в Linux, но в Windows такая же ситуация бывает. А следовательно, пользователям предстоит произвести алгоритм, позволяющий непосредственно сделать задуманное, чтобы достичь новейшей версии и исключить баги, а также прочие ошибки в языке скриптов для интернета.

Алгоритм не сложный и не такой уж большой:

  1. Для Windows необходимо перейти по специальной ссылке – windows.php.net/download/. Там будет предоставлено несколько вариантов загрузки, но рекомендуется обращать внимание исключительно на то, что поддерживается системой пользователя. Если ОС устарела и более не может работать с новыми версиями софта, то увы, самый последний релиз человек не установит. В любом случае, нужно сверять параметры перед загрузкой;
  2. Далее, когда файл уже есть, останется произвести несколько действий, позволяющих обновить PHP для сервера на Windows-компьютере. Первая – удаление директории ПО, чтобы поставить язык как новый;
  3. Когда все пусто, следует произвести «чистую» установку. То есть, новая версия PHP будет установлена не поверх старой, а как оригинальная – на уже «расчищенное» место. Однако, если человек не делал настройки, то тогда придется все настроить в php.ini – там содержатся параметры для правильной работы сервера.

А когда желаемая версия будет установлена, пользователю останется исключительно начать работать с обновленным языком программирования, который теперь поддерживается и функционирует без проблем.

Однако, стоит учитывать несколько моментов, что требуется сделать перед тем, как устанавливать. Это производится во избежание каких-либо внезапных проблем, связанных с потерей данных и самостоятельной настройкой. Об этом как раз-таки и пойдет сейчас речь.

Что сделать перед обновлением?

Немаловажный момент во время установки с нуля – резервное копирование важных данных. Их немного, но зато если их перенести в безопасное место, которое не будет затронуто, то пользователь получит впоследствии обновленный элемент ПО – PHP, так еще и с сохраненными параметрами.

Основной документ, который подвергнется копированию и дополнительному сохранению – php.ini. В нем хранится все, что касается сетей. Если же такой момент опустить, то пользователям придется после установки заново все настраивать. Это долго и далеко не каждому по душе. Следовательно, лучше заранее хранить резервную копию где-либо.

Второе, что требуется проверить – не было ли каких-то ошибок при работе. Возможно, с этим виноват не PHP, но лучше всего заранее продиагностировать сервер. Ведь может быть такой вариант событий, что пользователи просто не будут понимать, что не в порядке – сайт или же программа для скриптов сайта. Следовательно, перед установкой требуется, желательно, проверить полную работоспособность интернет-сервера.

Обновление информации в базе данных. Оператор Update

Иногда также бывает необходимость не только обновлять PHP сервера, но и в базу данных вносить некоторые корректировки. Для этого служит оператор Update. Как правило, в таблице указывается столбец (название его), а также строка со своим же наименованием. Также, для изменения значений, указывается новое число или буквы.

Выглядит это примерно так:

UPDATE<название таблицы с данными в SQL>SET
Cost=10000
WHERE Number=4

Number Present Cost
1 Laptop 20000
2 Smartphone 8000
3 Tablet 15000
4 Watch 10000

Главное, соблюдать данные таблицы – тогда все будет отлично. И такими элементами таблицы возможно управлять без проблем в SQL. А скрипты PHP с обновленной версией смогут это без проблем реализовать. Поэтому, рекомендуется использовать исключительно новые версии программного обеспечения – сервера смогут работать стабильно. Возможно, даже со временем станут появляться новые функции для лучшего взаимодействия.

It provides all the steps required to update and upgrade the PHP version to PHP 8 in XAMPP on Windows 10.

XAMPP is a complete package to install the Apache Web Server, MySQL, PHP, Perl, FTP Server, and phpMyAdmin for Linux, Solaris, Windows, and Mac OS X. It also provides an interface to admin Apache Web Server, MySQL, and PHP. Though XAMPP is being released frequently, it might be required to use the most recent version of PHP till XAMPP include it in its distribution. This tutorial provides all the steps required to update or upgrade the PHP version to PHP 8 in XAMPP.

You can also follow the tutorials How To Install XAMPP On Windows and How To Install PHP 8 On Windows to install the most recent version of XAMPP and PHP on Windows.

Step 1 — Open XAMPP Control Panel

Open the XAMPP Control Panel as shown in Fig 1.

XAMPP Control Panel

Fig 1

Step 2 — Open Apache Config Panel

Click the Config Button next to apache. It will show the configuration options as shown in Fig 2.

XAMPP Apache Config

Fig 2

Step 3 — Open Config File

Choose the option Apache(httpd-xampp.conf) as highlighted in Fig 2. It will open the configuration file httpd-xampp.conf as shown in Fig 3.

XAMPP PHP Config

Fig 3

Step 4 — Update PHP Installation Path

I have highlighted some of the PHP configurations in Fig 3. I have installed the most recent version of PHP i.e. PHP 7.4.0 while writing this tutorial by following How To Install PHP 7 On Windows. Also, I have updated the PHP installation path as highlighted in Fig 4.

Upgrade PHP to PHP 8 in XAMPP On Windows 10 - Apache Configuration

Fig 4

Step 5 — Save Configuration and Start Apache

Now save the changes and start the Apache Web Server. It will show the Apache status as shown in Fig 5.

Upgrade PHP to PHP 8 in XAMPP On Windows 10 - Apache Restarted

Fig 5

Step 6 — Verify PHP

In this step, we will verify the PHP version used by XAMPP. Open the Browser and type the URL http://localhost. It will show the XAMPP Dashboard. Now click the PHPInfo Link to open the PHP info page as shown in Fig 6.

Upgrade PHP to PHP 8 in XAMPP On Windows 10 - Apache PHP Info

Fig 6

It reflects the most recent version of PHP i.e. PHP 8.0.3.

Summary

In this tutorial, we have discussed using the multiple versions of PHP using XAMPP by configuring the apache configuration file. I have provided all the steps required to upgrade the PHP distributed by XAMPP to the most recent version of PHP i.e. PHP 8.0.3.

Я пытаюсь заставить мой проект Laravel работать. Но когда я использую обновление композитора, он говорит следующее:

Этот пакет требует php> = 5.6.4, но ваша версия PHP (5.5.12) не удовлетворяет этому требованию.

Я использую WAMP, который запускает версию php 7.0.4, это также подтверждается в браузере, если я повторяю версию php. Но когда я использую php -v в консоли это показывает, что я использую PHP версии 5.5.12 (cli).

Я немного искал в Google и обнаружил, что он использует мою версию PHP для Windows вместо версии моего веб-сервера. Но я не мог узнать, как обновить мою версию PHP на Windows.

Содержимое моего PATH показано на следующем рисунке

введите описание изображения здесь

7

Решение

Вы можете удалить composer, и при переустановке он попросит вас указать каталог PHP, который будет C: wamp64 bin php (обычно), в этот момент вы можете выбрать, какую версию PHP вы хотите использовать. , удачи.

введите описание изображения здесь

8

Другие решения

Это означает, что у вас есть еще одна установка PHP в вашей системе. Проверьте свои Programs в Control Panel и удали такую ​​установку.

Тем не менее, вы можете изменить свой PATH переменная окружения, а также. Процедура

Просто удалите путь, который указывает на любой PHP установочный каталог.

Иначе, если вы не уверены в изменении PATH переменной (которая может привести к серьезным проблемам, если она не установлена ​​правильно), вы можете просто удалить каталог, который PATH переменная указывает на …. (я имею в виду PHP каталог)

Совершенно лучшее решение — добавить путь к вашему PHP7 каталог bin в начале PATH переменная. Вы также должны сделать доступным composer в этом PHP7 каталог bin.

Например, заменить C:php на вашем пути с C:wampbinphp7 или где бы то ни было PHP7 путь есть ..

1

если вы устанавливали до xampp / wampp и composer глобально, вы могли бы добавить php в путь к своей среде, чтобы вызывать его где угодно, и теперь вы хотите, чтобы composer использовал новый xampp с php недавно установленным вами, поэтому перейдите в system> вкладка «Дополнительно»> переменная окружения> возможно, в «PATH», тогда ищите, если у вас есть C:xamppphp и отредактируйте к своему новому местоположению php.

У меня было несколько версий от xampp для тестирования и composer globaly для php 7.2

0

PHP7.4 has been released with a handful of new features — like the arrow function array_map(fn (Foo $foo) => $foo->id, $foo), typed properties and array spread operator ['foo', ...$foo, ...$bar]; — and that it’s also faster compared to PHP7.3.

So if you’re thinking to update PHP on your machine, take a look at the following post in which I’ll show you how to do so in several ways.

10 PHP Frameworks For Developers – Best of

10 PHP Frameworks For Developers – Best of

PHP, known as the most popular server-side scripting language in the world, has evolved a lot since the… Read more

Shortcuts to:

  • Upgrade PHP in macOS
  • Upgrade PHP in Windows
  • Upgrade PHP in Ubuntu
  • Upgrade PHP in Docker

Upgrading PHP in macOS

To begin with, you’ll have to check the PHP version that’s currently installed in your system by typing the following command line:

php -v

As we can see below, we are currently using PHP 7.3.7 on our macOS.

php version macos

Arguably the easiest way to install and update PHP on your macOS machine is by using Homebrew. Homebrew is a package manager for macOS though it is now also available in Linux and Windows too. With Homebrew, you can type the following command.

brew upgrade php

The process may take a bit long, however, once it’s done you can run the php -v command again. You should now see that the version is updated:

php74

Upgrading PHP in Windows

If you’re using Windows, it’s much easier to run your PHP application on a pre-packaged localhost environments such as WAMP or MAMP. These applications comes with PHP pre-installed and configured. You will just need to update them to their latest version or install it using the built-in tool to get the latest PHP version.

In addition to that, both WAMP and MAMP provide an option within the application to switch PHP easily.

php and mamp

Upgrading PHP in Ubuntu

As mentioned previously, you should first check the PHP version that’s in your Ubuntu machine.

php and ubuntu

As you can see above, currently I have PHP7.3 installed. In Ubuntu, the PHP package can be installed from the ondrej/php respository. First, run the following command to tap the repository.

sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

Then, we can run the following commands which will install PHP7.4, some PHP extensions and packages, and the PHP CLI.

sudo apt-get install php7.4 php7.4-common php7.4-cli

That’s all. Your Ubuntu machine will successfully be running PHP7.4 and you can confirm by running the php -v command again.

php ubuntu

Upgrading PHP in Docker

The latest PHP version is also available as an official Docker image. Docker is compatible in several different platforms including macOS, Windows, and Linux so you should be able to follow the same procedure for all these operating systems.

To do so, first I’d like to see if I have the Docker image for PHP7.4 in my machine.

php docker images

It looks like that I don’t have it yet. Let’s type the following command to download the image. This command will download the Docker image for PHP7.4 in the Alpine Linux flavour which smaller than the Debian-based image thus also faster to download. You can find the full list of the Docker image available in Docker Hub.

docker pull php:7.4-fpm-alpine

Once downloaded, we could run it as standalone container with this command below:

docker run --rm -i -t php:7.4-fpm-alpine sh

The container should be up and running in a second and immediately creates a Shell session inside the container. If we run the php -v, we should be seeing that it is the PHP7.4 within the Docker container.

php docker run

Wrapping Up

That’s all how to install and update PHP version to the latest. It’s not as complicated as you’d expected, isn’t it? Finally, PHP core development is progressing at a rapidly with PHP8 aimed for the next release by the end of this year with, of course, some interesting features and improvements. It’s an exciting time to be a PHP developer.

Сразу предупреждаем, что если у вас есть сайт, который работает на какой-либо версии PHP – не спешите его обновлять, потому что есть риск, что некоторые страницы сайта после такого обновления перестанут работать. Это – проблема практически любого языка программирования, потому что после обновления версии ломаются какие-либо зависимости, и все перестает работать. А вот для начинающих разработчиков изучать PHP стоит сразу с самой свежей+стабильной версии, потому что в процессе изучения PHP вы будете пользоваться самыми новыми «фишечками» языка. Ниже – о том, как обновить PHP вашего «ручного» сайта. Кроме того, в самом конце мы дадим простой совет тем, кто занимается разработкой сайтов и хочет проапгрейдить PHP до самой свежей версии.

Обновление для популярных CMS

Актуальная версия PHP

Вообще, максимальная версия, которая сейчас используется для создания сайтов – это PHP 8, вышедшая в конце 2021 года. Но восьмая версия еще не получила статус стабильной – до сих пор фиксятся баги в вносятся улучшения.

Самая свежая, и при этом стабильная версия – PHP 7.

Возможности PHP 7

Здесь мы вкратце перечислим основные фичи, которые появились в PHP 7:

  • Скалярные типы можно объявлять принудительно, в этом случае значение будет в обязательном порядке приводиться к объявленному типу.
  • Появилась возможность указания типа возвращаемого функцией значения.
  • Появился синтактический сахар для тернарного выражения, если оно в одном из случае возвращает null: с помощью ?? вы можете задать возврат либо указанного значения (если оно существует), либо null.
  • Новый оператор сравнения <=> возвращает значение -1/0/1 в зависимости от того, что больше – правая часть/равны/левая часть (1 <=> 2 вернет -1).
  • Массивы с константами теперь объявляются через define.
  • По аналогии с анонимными функциями (лямбдами) были добавлены анонимные классы.
  • Появилось задание символов Unicode через шестнадцатеричный код.
  • Появились более надежные и удобные инструменты для сериализации/десериализации и замыканий.
  • Работа с Unicode пополнилась новыми функциями вроде возвращения шестнадцатеричного кода символа.
  • Появилась улучшенная версия assert – ожидания.
  • Теперь не нужно перечислять каждый класс, который вы хотите использовать в namespace – можно объединить схожие в одном use.
  • Генератор теперь может возвращать окончательное значение через return – возвращается, когда все итерации генератора были выполнены. Полезно для отслеживания окончания работы генератора.
  • Генераторы теперь могут напрямую передавать данные другим генераторам.
  • Теперь можно открывать сессии с другими, отличными от стандартного конфига, параметрами.
  • Регулярные выражения теперь можно группировать в массив для более быстрой обработки вызовов.
  • Улучшены функции, отвечающие за генерацию ключей безопасности.
  • Функция создания списка теперь правильно обрабатывает поданные ей на вход массивы.

Обновить PHP на Win

Если вы решили изучать программирование на PHP, то у вас скорее всего установлен какой-либо локальный сервер вроде WAMP или XAMPP, возможно вы самостоятельно поднимали какой-нибудь «серьезный» сервер – nginx или apache. Во всех этих случаях вам нужно обновлять сервер, а не PHP – версия PHP сама обновится до текущей, когда вы обновите сервер. Инструкции по обновлению несколько различаются от сервера к серверу, но общий принцип у них одинаков:

  1. Сохраняете локально на компьютере все исходники вашего сайта (обычно – все то, что лежит в папке www).
  2. Заходите в админку сервера, останавливаете все службы.
  3. Удаляете сервер через «Установку и удаление приложений».
  4. Скачиваете нужную вам версию сервера.
  5. Устанавливаете новый сервер, заливаете на локальный хостинг все исходники сайта.

Естественно, после этого вам некоторое время придется повозиться со слетевшими зависимостями и всплывшими после миграции багами – от этого никуда не деться.

Обновить PHP на Ubuntu

В этом случае вам нужно тянуть новую версию из репозитория PHP. Поскольку репозиторий – частный, сначала вам нужно установить дополнительный пакет, который упрощает работу с частными репозиториями:

sudo apt-get install software-properties-common python-software-properties

После того, как все установится, вам нужно будет «стянуть» все версии PHP:

sudo add-apt-repository ppa:ondrej/php

Теперь установка зависит от типа вашего сервера. Если вы используете Apache, то:

sudo apt-get install php7.0-mysql //перепривязываем язык программирования и базу данных mysql
sudo apt-get install php7.0 //ставим сам PHP

Если вы используете nginx, то все немного сложнее:

  • sudo apt-get install php7.0-fpm //и тут перепривязываем язык
  • открываем через nano файл конфига nginx;
  • ищем переменную fastcgi_pass;
  • меняем в ней php5-fpm.sock на php/php7.0-fpm.sock.

Обновить PHP на Debian

Сначала обязательно делаем apt update и apt upgrade. После этого нужно подключить пользовательские репозитории:

wget -q https://packages.sury.org/php/apt.gpg -O- | sudo apt-key add –

echo "deb https://packages.sury.org/php/ stretch main" | sudo tee /etc/apt/sources.list.d/php.list

sudo apt-get install ca-certificates apt-transport-https

Последнее нужно делать только в том случае, если консоль выдала предупреждение о том, что не хватает каких-то зависимостей.

А дальше все просто:

apt-y install php php-common

после чего версия обновится.

Обновление для популярных CMS

Для всех CMS обновление происходит одинаково. Если у вас локальный сервер, на котором установлена система управления контентом – вы заходите в настройки CMS, ищете «версия PHP» и выставляете нужную. Если ваш сайт лежит на хостинге с системой управления контентом – вы сначала заходите в настройки хостинга, ищете версию ПХП и выставляете нужную.

После этого, если ЦМС не обновилась сама – вы заходите уже в ее настройки и выставляете нужную версию PHP.

Зачем обновлять

Как мы уже говорили выше, обновляться в первую очередь нужно тем, кто учит PHP – для изучения синтаксиса желательно иметь самые свежие функции, доступные в языке. К тому же это сильно влияет на основы программирования, которые вы будете учить – те же анонимные функции и классы, которые сильно упрощают разработку сложных приложений, могут быть недоступны в старых версиях. По поводу совместимости можете не переживать – все свежие CMS без проблем принимают и PHP 7, и PHP 8.

Отличия версий

Если смотреть на эволюцию версий, то отличий – гигантское количество, все их мы здесь перечислять не будем (если вам очень интересно – в этой статье они детально расписаны). Мы же покажем, сколько запросов в секунду могут отрабатывать различные CMS на разных версиях языка:

PHP 5

PHP 7

WordPress

96

204

Drupal

182

316

Magento

41

69

Laravel

285

485

Zend Framework

250

489

SugarCRM

127

270

Естественно, точные числа зависят от конкретного железа, но вы можете проследить динамику: за счет новых функций и оптимизаций языка разработчики систем управления контентом могут повысить продуктивность бэк-энда сайта на 50-100%.

Что почитать по теме

  • Официальный мануал по установке и обновлению PHP. Не самый информативный, но есть множество комментариев от пользователей – будет полезно, если столкнетесь с ошибкой.
  • Краткая сводка обновлений 8.1. На случай, если вы подумываете обновиться до самой-самой свежей версии.

FAQ

Как безопасно обновиться, если есть живой рабочий сайт?

Дважды подумайте перед тем, как начинать обновление – здесь работает хороший принцип «работает – не трогай». Если обновиться все же надо – напишите в саппорт вашего хостинга и попросите инструкцию по обновлению. Обычно у саппорта такие инструкции есть, и в них учтены мелочи, которые критичны для конкретного хостинга.

Стоит ли начинать учить PHP на восьмой версии?

Мы бы все же советовали 7-ю. Версии языка – это вещь довольно инертная, даже если вы сейчас начнете учить PHP с нуля, скорее всего к тому моменту, как вы выйдете на свою первую работу, PHP 7 еще будет доминирующим. Поэтому есть смысл учить именно его – если вы начнете с PHP 8, многие его «фишки» будут вам недоступны на реальных проектах.

Подведем итоги

Тезисно:

  • Стабильная версия ПХП на текущий момент – 7-я.
  • Дважды подумайте перед тем, как обновляться на новую вервию при наличии рабочего сайта – с высокой вероятностью что-нибудь сломается.
  • Локальные сервера обновляются переустановкой пакета (Windows) или стягиванием пакетов из пользовательских репозиториев с дальнейшим обновлением (UNIX).
  • PHP 7 – существенно более быстрая, чем PHP 5. Если хотите обновиться на хостинге – лучше попросите инструкцию у вашего саппорта.

This setup should only be used as PHP development environment on Windows as it has not been tested on production.

If you followed the steps from the previous post on PHP installation on Windows using Web Platform Installer, you will now have PHP 7.0 to do your web development.

The problem using Web Platform Installer (WPI) is that most likely you won’t be using the latest version of PHP (at the time of this writing, it’s 7.0.15 and 7.1.1 and WPI only gives you version 7.0.9).

Fortunately, if you want to upgrade to the latest version, you can do it manually in a few simple steps described below.

Before we start, please keep in mind that this installation is for a local PHP server on IIS, not Apache web server.

Steps to Upgrade PHP to 7.1

  1. Open Control Panel, click on Programs and Features, and then Turn Windows features on or off. Under Internet Information Services, World Wide Web Services, Application Development Features, make sure that option CGI is checked. This enables both the CGI and FastCGI services, which is recommended for PHP applications.

    Control Panel CGI

  2. Download PHP for Windows. Since we’re using PHP as FastCGI, we’ll use the 64-bit Non-Thread Safe (NTS) version (i.e., php-7.1.1-nts-Win32-VC14-x64.zip).

  3. Copy your current PHP7 installation from v7.0 and rename the copy to v7.1.

    Copy original PHP 7.0 to 7.1 folder

  4. Copy all files from the PHP7 zip folder (Step 3) to the new renamed v7.1 folder (Step 4).

  5. Edit the php.ini (C:Program FilesPHPv7.1php.ini) to reflect the new version (7.1) under [WebPIChanges] as shown below (see highlighted changes):

    [WebPIChanges]
    error_log=C:WINDOWStempPHP71x64_errors.log
    upload_tmp_dir=C:WINDOWStemp
    session.save_path=C:WINDOWStemp
    cgi.force_redirect=0
    cgi.fix_pathinfo=1
    fastcgi.impersonate=1
    fastcgi.logging=0
    max_execution_time=300
    date.timezone=Australia/Melbourne
    extension_dir="C:Program FilesPHPv7.1ext"
    
    [ExtensionList]
    ;extension=php_mysql.dll
    extension=php_mysqli.dll
    extension=php_mbstring.dll
    extension=php_gd2.dll
    extension=php_gettext.dll
    extension=php_curl.dll
    extension=php_exif.dll
    extension=php_xmlrpc.dll
    extension=php_openssl.dll
    extension=php_soap.dll
    extension=php_pdo_mysql.dll
    extension=php_pdo_sqlite.dll
    extension=php_imap.dll
    extension=php_tidy.dll
    
    [PHP_WINCACHE]
    extension=php_wincache.dll
    

    php.ini File Update

    Please note the change in line 1857. Although it’s not related to PHP upgrade, you need to double check that the extension=php_mysql.dll is either commented out or deleted.

    MySQL extension was deprecated on PHP version 5.5 and removed on version 7. If it’s not excluded, you’ll see the following error:

    PHP Warning:  PHP Startup: Unable to load dynamic library 'C:Program FilesPHPv7.1extphp_mysql.dll' - The specified module could not be found.
    
    in Unknown on line 0
    

    Line 1872-1873 are for WinCache setting. Just make sure it’s there or else you will also encounter an error.

  6. Open IIS Manager and click on FastCGI Settings.

    IIS Manager FastCGI Settings

  7. Double-click on the PHP 7.0 settings and copy all the property values including the Environment Variables (PHP_FCGI_MAX_REQUESTS, PHPRC) and Advanced Settings. We’re just going to reuse all the values from the existing installation instead of starting from scratch.

    Click Cancel button after you’re done.

    IIS Manager FastCGI Properties

    EnvironmentVariables PHP_FCGI_MAX_REQUESTS Properties

    EnvironmentVariables PHPRC Properties

  8. Now from FastCGI Settings window, click on Add Application… on the Actions pane on the right.

    IIS Manager FastCGI Settings Add Application

  9. Type in C:Program FilesPHPv7.1php-cgi.exe on the Full Path box.

  10. Enter all values you copied from Step 8, except for PHPRC where you want to update the value to 7.1 (i.e., C:Program FilesPHPv7.1).

    Once completed, just click OK.

  11. Go back to IIS Manager and click on Handler Mappings.

    IIS Manager Handler Mappings

  12. Look for PHP_via_FastCGI and double-click on it.

    IIS Manager PHP_via_FastCGI

  13. Locate the new php-cgi.exe and change the value on the Executable (optional): accordingly. Click Yes when there’s a dialog box asking you to create a FastCGI application for this executable.

    Click OK and exit IIS Manager.

    IIS Manager Handler Mappings PHP FastCGI

Update WinCache Extension for PHP

Once PHP is upgraded to version 7.1 you may run into another issue with your WinCache PHP extension with an error message as follow.

PHP Warning:  PHP Startup: wincache: Unable to initialize module
Module compiled with module API=20151012
PHP    compiled with module API=20160303
These options need to match

in Unknown on line 0

This error was caused by an outdated version of WinCache. PHP 7.1 requires a new WinCache binaries. Look for them in the PECL packages or you can download it directly from this link.

WinCache PHP Extension PECL download

Installation should be straightforward. Just extract the zip file and follow the instructions.

Update Windows Environment Variables

Finally, we need to update the path of the new PHP in Windows Environment Variables.

  1. Click on the Windows start button and type in “system” and click on System Control panel.

    Windows System Control Panel

  2. In System window, click on Advanced system settings and on System Properties window, make sure you have Advanced tab opened. And you can follow the path shown in the picture to complete the rest of the steps.

    Control Panel System Environment Variables

  3. Click on Environment Variables… button.

  4. Under System Variables, click on Path and Edit… button.

  5. Click on where the current PHP is located and double-click it or click on Edit button.

  6. Change the value to the location of the new PHP (i.e., C:Program FilesPHPv7.1)

  7. Click OK button on each window to close.

That’s all there is. Now you can test your PHP installation by creating a test.php file with this PHP code.

<?php phpinfo(); ?>

Run it from your browser (i.e., http://localhost/test.php). If PHP is installed with the correct version, you will see something similar to this:

phpinfo 7.1.1

Compared with previous version of PHP installation on Windows:

phpinfo 7.0.9 displayed on a page

Further Reading

How to Install PHP on Windows 10 Using Web Platform Installer
How to Upgrade to PHP 7.2 on IIS (Windows 10)
FastCGI
Difference between PHP thread safe and non thread safe binaries
Using FastCGI to Host PHP Applications on IIS 7
WinCache Extension for PHP

Download

Download PHP For Windows: Binaries and sources Releases
WinCache 2.0.0.8 PHP Extension Direct Download
Microsoft Visual C++ 2015 Redistributable Update 3

Понравилась статья? Поделить с друзьями:
  • Как обновить windows 10 ltsc до версии 20h2
  • Как обновить wddm на windows 10
  • Как обновить pci контроллер simple communications для windows 10
  • Как обновить visual studio code windows
  • Как обновить paint на windows 10