Как узнать версию php на windows

Загрузить PDF

Загрузить PDF

Если на веб-сайт нужно добавить новые функции или найти ошибку, узнайте версию PHP вашего сервера. Для этого запустите простой PHP-файл на своем веб-сервере. Также можно выяснить версию PHP на компьютере — это можно сделать с помощью командной строки или терминала.

  1. Step 1  Откройте текстовый редактор или редактор кода.

    Воспользуйтесь Notepad++, Блокнотом или TextEdit. Не пользуйтесь мощными текстовыми редакторами, такими как Microsoft Word.

  2. Step 2  Введите следующий код.

    Этот небольшой код отобразит версию PHP, если запустить его на веб-сервере.[1]

    <?php
    echo 'Current PHP version: ' . phpversion();
    ?>
    
  3. Step 3  Сохраните файл в формате PHP.

    Нажмите «Файл» > «Сохранить как», а затем введите имя файла. Добавьте расширение .php в конец имени файла. Введите простое имя, например, version.php.

  4. Step 4  Узнайте подробную информацию (если хотите).

    Приведенный выше код отобразит версию PHP, но если вы хотите получить дополнительные данные, например, информацию о системе, дату сборки, доступные команды, информацию об API и так далее, используйте команду phpinfo (). Сохраните файл как info.php.

  5. Step 5  Загрузите файл(ы) на веб-сервер.

    Возможно, вам придется использовать FTP-клиент, или воспользуйтесь панелью управления сервера. Скопируйте файл(ы) в корневой каталог веб-сервера.

    • Прочитайте эту статью, чтобы научиться загружать файлы на веб-сервер.
  6. Step 6  Откройте файл в веб-браузере.

    Когда вы загрузите файл на сервер, откройте файл в браузере. Найдите файл на сервере. Например, если вы скопировали файл в корневой каталог, перейдите на www.yourdomain.com/version.php.

    • Чтобы просмотреть полную информацию, перейдите на www.yourdomain.com/info.php.

    Реклама

  1. Step 1 Откройте командную строку или терминал.

    Чтобы узнать версию PHP на компьютере, воспользуйтесь командной строкой или терминалом. Это метод можно применить, если вы пользуетесь SSH, чтобы удаленно подключаться к серверу через командную строку.

    • В Windows нажмите Win+R и введите cmd.
    • В Mac OS X откройте терминал из папки «Утилиты».
    • В Linux откройте терминал на панели инструментов или нажмите Ctrl+Alt+T.
  2. Step 2 Введите команду для проверки версии PHP.

    Когда вы запустите команду, версия PHP отобразится на экране.

    • В Windows, Mac OS X, Linux введите php -v
  3. Step 3 Выполните следующие действия, если версия PHP не отображается в Windows.

    Возможно, на экране появится сообщение php.exe не является внутренней или внешней командой, исполняемой программой или пакетным файлом.[2]

    • Найдите файл php.exe. Как правило, он находится в C:\php\php.exe, но, возможно, вы изменили папку, когда устанавливали PHP.
    • Введите set PATH=%PATH%;C:\php\php.exe и нажмите Enter. В эту команду подставьте правильный путь к файлу php.exe.
    • Запустите команду php -v. Теперь на экране отобразится версия PHP.

    Реклама

Об этой статье

Эту страницу просматривали 32 711 раз.

Была ли эта статья полезной?

Here are some quick tips on how to check the PHP version on your computer or server.

There are several reasons why you want to check the version of PHP which is installed on your server. For example, you might want to install PHP-based software and to check if the software requirements match the PHP version installed on your server. Or you might be a developer who wants to use a feature which is only available in specific versions of PHP. 

There are a lot of different PHP versions, and they have some noticeable differences among them. With every new PHP version, new features are added and others are deprecated, so it’s always good to know the PHP version you’re using.

There are a few different ways to check the PHP version. Mainly, if you have SSH access to your server, you can use the command-line interface to check it. On the other hand, if you don’t have terminal access, I’ll show you how to check the PHP version using the phpinfo function.

Check the PHP Version by Using the Terminal

In this section, we’ll discuss how you could check the PHP version by using the command-line interface (CLI) in a terminal.

Check the PHP Version on Unix, Linux, and macOS

For *nix-based systems—Linux, Unix, and macOS—it just takes a single command to check the PHP version. Go ahead and run the following in your terminal.

You should see an output like the following:

1
PHP 7.2.24-0ubuntu0.18.04.3 (cli) (built: Feb 11 2020 15:55:52) ( NTS )
2
Copyright (c) 1997-2018 The PHP Group
3
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
4
    with Zend OPcache v7.2.24-0ubuntu0.18.04.3, Copyright (c) 1999-2018, by Zend Technologies

As you can see, this gives you comprehensive information about the PHP version which is installed on your server. In the above output, the 7.2.24 version of PHP is installed on the server.

Check the PHP Version on Windows

For Windows users, the same command is used to check the PHP version. But you might get an error if you don’t set the PATH environment variable first. You can do that by running the set PATH command. Run the following commands, and make sure that you replace the {PATH_TO_PHP_DIRECTORY} placeholder with the directory path where you’ve installed PHP. For example, if you installed PHP in the C:\software\php directory, you need to run set PATH=%PATH%;C:\software\php.

1
set PATH=%PATH%;{PATH_TO_PHP_DIRECTORY}
2
php -v

If you don’t want to set the PATH environment variable, you could also go to the directory where you’ve installed PHP and run the php -v command from there.

1
cd C:\softwares\php
2
php -v

So that was a brief introduction to the CLI option to check the PHP version. In the next section, we’ll discuss how you could check your PHP version with the phpinfo function.

Check the PHP Version by Using the phpinfo Function

You can also use the phpinfo function, which prints detailed information about the PHP software on your server and its configuration.

This option is especially useful when you don’t have SSH access to the server where your site is hosted. If you want to use this option to check the PHP version on the remote server, all you need is the ability to upload a PHP file, for example with FTP or a web-based portal.

Create a file called php_version_check.php file with the following contents. 

1
<?php
2
phpinfo();
3
?>

Upload this file to the root directory of your site. Once you’ve done that, you should be able to access it at the http://example.com/php_version_check.php URL (replacing example.com with your own domain name). It should produce output like that shown in the following screenshot.

The phpinfo Function

The phpinfo Function

phpinfo Security Risks

As you can see, the PHP version is displayed right on the top of the page. Also, it displays a lot of other important configuration information as well. This information can be very useful if you are setting up or debugging a PHP installation. It can also be very useful for hackers, allowing them to pinpoint specific vulnerabilities in your system! 

That’s why I strongly recommend you remove this file from the server once you’ve finished checking the PHP version.

Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

In this course, you’ll learn the fundamentals of PHP programming. You’ll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you’ll build up to coding classes for simple object-oriented programming (OOP). Along the way, you’ll learn all the most important skills for writing apps for the web: you’ll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.

phpversion

(PHP 4, PHP 5, PHP 7, PHP 8)

phpversionПолучает текущую версию PHP

Описание

Список параметров

extension

Необязательное имя модуля.

Возвращаемые значения

Функция возвращает текущую версию PHP в виде строки (string).
При передаче в параметр extension
строкового (string) аргумента функция phpversion()
возвращает версию модуля или false, если информации о версии нет или модуль не включили.

Список изменений

Версия Описание
8.0.0 Параметр extension теперь принимает значение null.

Примеры

Пример #1 Пример использования функции phpversion()

<?php// Выводит строку вида 'Текущая версия PHP: 8.3.12'
echo 'Текущая версия PHP: ' . phpversion();// Выводит строку вида '1.22.3' или ничего, если модуль не включили
echo phpversion('zip');?>

Пример #2 Пример работы с константой PHP_VERSION_ID

<?php/**
* Константу PHP_VERSION_ID определяют как число, причём чем больше число, тем новее
* версия PHP. Значение константы определяют выражением, которое приводит предыдущий абзац:
*
* $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
*
* Теперь через константу PHP_VERSION_ID можно проверять, какую функциональность
* поддерживает текущая версия PHP, для этого не нужно каждый раз вызывать функцию version_compare(),
* чтобы проверить, поддерживает ли функцию текущая версия PHP.
*
* Например, можно определить константы семейства PHP_*_VERSION,
* которые недоступны в версиях до 5.2.7:
*/
if (PHP_VERSION_ID < 50207) {
define('PHP_MAJOR_VERSION', $version[0]);
define('PHP_MINOR_VERSION', $version[1]);
define('PHP_RELEASE_VERSION', $version[2]);// и так далее…
}?>

Примечания

Замечание:

Информацию о версии PHP также даёт предопределённая константа
PHP_VERSION. Дополнительную информацию
о семантических значениях, из которых состоит полная версия
выпуска PHP, дают константы семейства PHP_*_VERSION.

Замечание:

Отдельные модули определяют свой номер версии,
но бо́льшая часть встроенных модулей в качестве своего номера
версии будет использовать версию PHP.

Смотрите также

  • Константы PHP_VERSION
  • version_compare() — Сравнивает две «стандартизованные» строки с номером версии PHP
  • phpinfo() — Выводит информацию о текущей конфигурации PHP
  • phpcredits() — Выводит список разработчиков PHP
  • zend_version() — Получает версию движка Zend

Нашли ошибку?

cHao

12 years ago

If you're trying to check whether the version of PHP you're running on is sufficient, don't screw around with `strcasecmp` etc. PHP already has a `version_compare` function, and it's specifically made to compare PHP-style version strings.

<?php
if (version_compare(phpversion(), '5.3.10', '<')) {
// php version isn't high enough
}
?>

burninleo at gmx dot net

8 years ago

Note that the version string returned by phpversion() may include more information than expected: "5.5.9-1ubuntu4.17", for example.

pavankumar at tutorvista dot com

14 years ago

To know, what are the {php} extensions loaded & version of extensions :


<?php

foreach (get_loaded_extensions() as $i => $ext)

{

echo
$ext .' => '. phpversion($ext). '<br/>';

}

?>

Benjamin Crozat

6 ways to check which version of PHP you are running

The quickest way to check your version of PHP

To check your version of PHP, simply run the php -v command, no matter if you are running macOS, Linux, or Windows.

6 ways to check your version of PHP

Using phpversion()

Checking the version of PHP using phpversion.

To check which version of PHP you are running, you use the phpversion() function. It returns a single string containing the precious information.

<?php echo phpversion(); ?>

Using phpinfo()

Checking the version of PHP using phpinfo.

To check which version of PHP you are running, use the phpinfo() function. It will show you a web page containing every bit of information you might need about your installation of PHP.

<?php phpinfo(); ?>

Using the terminal on macOS, Linux and WSL

Checking the version of PHP using the terminal on macOS and Linux.

To check which version of PHP you are running using your terminal on macOS or Linux, use the php -v command. It’s simple and straightforward, the version of PHP is the first thing in the output.

php -v

Using the command prompt on Windows

To check which version of PHP you are running using your Windows command prompt, use the php -v command. It’s as simple and straightforward as in the previous section.

php -v

Using Laravel’s welcome page

Checking the version of PHP using Laravel’s homepage.

To check which version of PHP you are running using Laravel’s welcome page, just look at the bottom right corner. It’s that simple.

Using Laravel Artisan

Checking the version of PHP using Laravel Artisan.

To check which version of PHP you are running using Laravel, use the php artisan about command. It will show you the version of PHP, including various information about your setup.

php artisan about

PHP is powering hundreds of websites & web applications around the world, and although most of the time it is used on Linux, we can install PHP on Windows 11 or 10 as well. However, after completing the setup or implementing any new version of PHP, it is essential to find out which version of PHP is running on your Windows system.

How to Check PHP version on Windows 10 or 11Check the PHP version using Command prompt or PowershellPHP is not recognized as an internal or external commandCreate a PHP Info () page on Windows

It helps to confirm the web application we are using on our Windows Desktop or Server has satisfied the PHP requirements it needed.

In this quick tutorial, we will find out the way to check the PHP version running on our Windows using the command line.

How to Check PHP version on Windows 10 or 11

Before following the tutorial, make sure PHP has been configured properly on your Windows system. Apart from that you need a command prompt or terminal access

If you don’t have this programming language on your system yet then see our tutorial on how to install PHP on Windows using the command prompt.

Check the PHP version using Command prompt or Powershell

The best and easiest way to identify the installed PHP version is by using its command line tool. However, to use the user must have access to the Windows command line apps like CMD.

Go to Windows 10 or 11 search box and type CMD or Powershell. You can use any of them. As the icon appears on any of these tools, click on it to run.

Run the given php the command that will help you to check the installed PHP version on Windows 10/11 or any other edition you are using:

php -v

or 

php -version

The above command is not just limited to Windows only, even other operating systems users such as Linux or MacOS can use it. As you run the syntax, in return the version and the technical details will be given.

However, the command will only show the default version on the system, not all the available ones, if you have installed multiple.

PHP is not recognized as an internal or external command

Sometimes, if you run the PHP -v and get an error saying PHP is not recognized as an internal or external command on Windows prompt or PowerShell then most probably the installed PHP location is not added in your system’s path.

So, first, open the C drive and find out the path of PHP. By default, it will be: C:\Program Files\php\php.exe however, we have used the Choco to install it, therefore our default path is C:\tools\php

Once you confirmed the location, open the system variables window. For that, go to the search box and type – Edit the system environment variables 

Click on it, as the option is available in the search result.

Edit the system environment variables

Soon the System Properties will open, here you have to click on the “Environment Variables…” button.

add php to environment variable in Windows

Select the Path from the System Variables area and click on the Edit button to get further options for adding the PHP-installed folder path in your Windows.

Add the system PATH in Windows

Finally, click on the Browse button and navigate to the folder where the PHP is located.

write Environment variables in window search

After finding the folder, select it and press the OK button.

Browse PHP installed folder

Now, open the command prompt or PowerShell to run the common php -v command for showing the version-related details.

Create a PHP Info () page on Windows

Another way to check the version of PHP on Windows 11 or 10 is by using a single line of code that will display all the necessary information including extensions and their versions.

For that on your command prompt or terminal type:

notepad info.php

After that paste the following code and save and close the file.

Create PHP Info file on Windows

Now, you may not know PHP comes with its own web server that we can use to test our PHP-based applications. So, in the same directory where you have created the info.php run:

php -S localhost:8000
Php inbuilt web server

You will see the PHP’s inbuilt web server will be started on your current Windows command prompt. Now, open your browser and type:

http://localhost:8000/info.php

And you will see a piece of detailed information about your installed PHP version.

PHP Info check version

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как отключить антивирус windows vista
  • После обновления windows 10 звук стал тише
  • Дистанционное управление mac с windows
  • Бесплатно офис 2010 для windows 10 бессрочная лицензия
  • Windows 10 may 2021 update