Как посмотреть версию php windows

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

11 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/>';

}

?>

Загрузить 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 676 раз.

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

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.

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

Hosting providers are traditionally slow to adopt new PHP versions on their servers. Consequently, multiple different PHP versions can exist on the server at the same time.

If you are implementing new features, installing a new PHP-based app, or trying to locate a bug on your website, it is important to know which PHP version your web server is running.

In this tutorial, you will learn how to check your PHP version on a local machine, server, or WordPress website.

How to check PHP version - a tutorial.

Prerequisites

  • PHP installed.
  • Write access to the server’s file system.
  • Access to the command line.

Check PHP Version by Running PHP Code

The simplest method to determine the PHP version on your website is to execute a PHP file with a code that prints the program version. Follow the steps in the sections below.

Step 1: Create PHP File

To determine the PHP version on your website, start by creating a PHP file with code that outputs the version information:

1. Open a text editor like gedit or Notepad.

2. Paste one of the following code snippets depending on the amount of information you need:

  • To obtain only the PHP version, use the following code:
<?php
echo 'PHP version: ' . phpversion();
  • For more details on your PHP configuration, such as system information, build date, server API, configuration file information, etc., create a file containing the phpinfo() function:
<?php 
phpinfo();

Note: While phpinfo() is useful for debugging, the page includes sensitive information about your system. Remove the file from the server once you finish using it.

  • For a list containing all the loaded PHP extensions and their versions, use the following code:
<?php 
foreach (get_loaded_extensions() as $i => $ext)
{
   echo $ext .' => '. phpversion($ext). '<br/>';
}

3. Save the file as phpinfo.php or any other name.

Step 2: Upload the PHP File

Upload the PHP file to your website’s document root directory. Use an FTP client of your choice or another method to upload the file.

Step 3: Check PHP Version

Open a web browser and type the full address of the file in the address bar. For example, if you uploaded a file titled phpinfo.php to the example.com root directory, enter:

http://www.example.com/phpinfo.php

The code above displays the PHP version without any further details, like in the output below:

Checking PHP version by using the phpversion command.

Check PHP Version Using Command Line (Windows, Linux, and macOS)

This section outlines the steps for checking your PHP version using the command line in Windows, Linux, and macOS. Skip to the part applicable to your operating system.

Check PHP Version on Windows

Follow the steps below to check your PHP version on a Windows system:

1. Open the Command Prompt or Windows PowerShell.

2. Run the following command to check the PHP version:

php -v
Checking the PHP version in Windows.

The command outputs the PHP version installed on your computer. If you get an error that php is not recognized as internal or external command even though you have PHP installed, add PHP to the PATH environment variable.

How to Add PHP to the PATH Environment Variable

To fix the PHP is not recognized error on Windows:

1. Press the Windows key and type Environment variables. Press Enter to open the System Properties Window.

Searching for Environment variables settings in Windows.

2. In System Properties, click the Environment Variables… button.

System Properties window.

3. Find the System variables section and scroll down the list until you find the PATH variable. Select the PATH variable and click Edit:

Editing the path environment variable in Windows.

4. Click the New button and enter the path to your PHP installation path. Click OK in every window to save and apply the changes.

Adding a new environment variable to path in Windows.

5. Open the Command Prompt again and check the PHP version:

php -v

Check PHP Version on Linux

If you have permission to SSH into the remote server, use the command line to check the installed PHP version. This method is also useful for checking the PHP version installed locally.

1. In the terminal, run the following command:

php -v
Checking PHP version using the command line in Ubuntu.

The command outputs the PHP version number, build date, and copyright information.

Note: If there is more than one PHP version installed on the server, the php -v command shows the default command-line interface (CLI) version. This version is not necessarily the one that runs on hosted websites.

Check PHP Version on macOS

To check the PHP version on macOS using the terminal, follow these steps:

1. Press Command + Space and type Terminal to open the Terminal app or go to Applications > Utilities > Terminal.

2. Run the following command:

php -v
Checking PHP version in macOS.

The terminal outputs the PHP version currently installed on your system.

How to Check PHP Version if You Are Using WordPress

PHP plays a fundamental role in every WordPress website’s functionality and performance. It is used to write WordPress code, themes, plugins, and helps deliver dynamic web pages to visitors.

New PHP versions usually include various upgrades, often related to performance, compatibility, and security. Thus, it is important to know which PHP version your WordPress site is using.

This section shows how you can check the PHP version in WordPress.

Important: Before making any changes, backup your website. Backups allow you to revert changes in case something goes wrong. If you do not have a backup solution, use one of the many available free WordPress backup plugins.

Check PHP Version via WordPress Site Health Tool

The easiest way to check your PHP version in WordPress is from the dashboard. Follow the steps below:

1. Log in to your WordPress account and navigate to Tools > Site Health.

Accessing Site Health in WordPress.

2. The Site Health page shows the health status of your WordPress site and any available updates or recommended improvements. It also states if you are using an outdated PHP version. Click the Info tab:

Open website info in WordPress.

3. Scroll down the list and expand the Server section. This section provides a lot of details regarding your server setup, including your PHP version:

Checking PHP version in WordPress dashboard.

Check PHP Version via a WordPress Plugin

Follow the steps below to check the PHP version in WordPress using a plugin:

1. Navigate to your WordPress site and log in with an admin account.

2. From the Dashboard, select Plugins > Add New to add a system information plugin.

Adding a new plugin to WordPress.

3. In the search bar, type PHP version or similar keywords to get a list of plugins compatible with your WordPress version.

4. Choose and install a plugin from the list, for example, Display PHP Version or PHP Compatibility Checker.

PHP version plugin search in WordPress.

5. Once you install the plugin, click Activate. Depending on the plugin you install, the PHP version might be displayed in different locations within the WordPress dashboard.

Popular plugins usually show the PHP version in:

  • The At a Glance section on the Dashboard.
  • The WP-ServerInfo section.
  • The Site Health section / Info tab.
  • A new menu item, such as Query Monitor.

For this tutorial, we used Display PHP Version, which shows the PHP version in the At a Glance section on the Dashboard:

Checking PHP version in WordPress using a plugin.

Conclusion

This article showed the common ways to check the PHP version on your server, local machine, or WordPress website. The methods covered in this tutorial include running PHP code, using the command-line interface, or checking the version via plugins or WP dashboard.

Next, check out how to make a redirect in PHP or see the 4 different types of errors in PHP.

Was this article helpful?

YesNo

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows xp настройка сетевого подключения для локальной сети
  • Монитор сетевой активности для windows 10
  • Можно ли поставить directx 12 на windows 7
  • Виды файловых систем для windows
  • Windows server 2008 лекарство