Apache узнать версию php

phpinfo

Выводит большое количество информации о текущем состоянии PHP. Сюда входит информация о настройках компиляции PHP, о расширениях, о версии, информация о сервере и среде выполнения (если PHP компилировался как модуль), окружении PHP, версии ОС, о путях, об основных и локальных значениях настроек конфигурации, о HTTP заголовках и лицензии PHP.

Так как каждая система имеет свои особенности, phpinfo() используется в основном для проверки настроек конфигурации и для просмотра доступных предопределенных констант в данной системе.

phpinfo() также используется в целях отладки, так как содержит все EGPCS (Environment, GET, POST, Cookie, Server) данные.

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

Вывод функции можно настраивать, передавая битовую маску из одной или более приведенных ниже констант (constants). Эта маска передается в качестве необязательного аргумента what . Отдельные константы или битовые значения можно комбинировать с помощью оператора или.

Настройки phpinfo()

Имя (константа) Значение Описание
INFO_GENERAL 1 Строка конфигурации, расположение php.ini , дата сборки, Web-сервер, Система и др.
INFO_CREDITS 2 Разработчики PHP. См. также phpcredits() .
INFO_CONFIGURATION 4 Текущие значение основных и локальных PHP директив. См. также ini_get() .
INFO_MODULES 8 Загруженные модули и их настройки. См. также get_loaded_extensions() .
INFO_ENVIRONMENT 16 Информация о переменных окружения, которая также доступна в $_ENV .
INFO_VARIABLES 32 Выводит все предопределенные переменные из EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE 64 Информация о лицензии PHP. См. также » license FAQ.
INFO_ALL -1 Выводит все приведенное выше.
Читайте также:  Если массив php содержит

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

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

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

Версия Описание
5.5.0 GUID логотипов были заменены на URI данных, и отключение expose_php теперь не влияет на результат phpinfo(). Список авторов теперь также встроен в вывод.
5.2.2 Добавлен вывод информации о загруженном конфигурационном файле. Ранее выводился только путь к конфигурационному файлу (php.ini).

Примеры

Пример #1 Пример использования phpinfo()

// Показывать всю информацию, по умолчанию INFO_ALL
phpinfo ();

// Показывать информацию только о загруженных модулях.
// phpinfo(8) выдает тот же результат.
phpinfo ( INFO_MODULES );

Примечания

Замечание:

В версиях PHP до 5.5, часть информации не выводится, если настройка expose_php установлена в off. Это PHP и Zend логотипы и информация о разработчиках.

Замечание:

В режиме CLI phpinfo() выводит обычный текст вместо HTML.

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

  • phpversion() — Выдает текущую версию PHP
  • phpcredits() — Выводит список разработчиков PHP
  • php_logo_guid() — Получение guid логотипа
  • ini_get() — Получает значение настройки конфигурации
  • ini_set() — Установка значения настройки конфигурации
  • get_loaded_extensions() — Возвращает массив имен всех скомпилированных и загруженных модулей
  • Предопределенные переменные

Источник

phpinfo

Outputs a large amount of information about the current state of PHP. This includes information about PHP compilation options and extensions, the PHP version, server information and environment (if compiled as a module), the PHP environment, OS version information, paths, master and local values of configuration options, HTTP headers, and the PHP License.

Because every system is setup differently, phpinfo() is commonly used to check configuration settings and for available predefined variables on a given system.

phpinfo() is also a valuable debugging tool as it contains all EGPCS (Environment, GET, POST, Cookie, Server) data.

Parameters

The output may be customized by passing one or more of the following constants bitwise values summed together in the optional flags parameter. One can also combine the respective constants or bitwise values together with the bitwise or operator.

phpinfo() options

Name (constant) Value Description
INFO_GENERAL 1 The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS 2 PHP Credits. See also phpcredits() .
INFO_CONFIGURATION 4 Current Local and Master values for PHP directives. See also ini_get() .
INFO_MODULES 8 Loaded modules and their respective settings. See also get_loaded_extensions() .
INFO_ENVIRONMENT 16 Environment Variable information that’s also available in $_ENV .
INFO_VARIABLES 32 Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE 64 PHP License information. See also the » license FAQ.
INFO_ALL -1 Shows all of the above.

Return Values

Always returns true .

Examples

Example #1 phpinfo() Example

// Show all information, defaults to INFO_ALL
phpinfo ();

// Show just the module information.
// phpinfo(8) yields identical results.
phpinfo ( INFO_MODULES );

Notes

Note:

In versions of PHP before 5.5, parts of the information displayed are disabled when the expose_php configuration setting is set to off . This includes the PHP and Zend logos, and the credits.

Note:

phpinfo() outputs plain text instead of HTML when using the CLI mode.

See Also

  • phpversion() — Gets the current PHP version
  • phpcredits() — Prints out the credits for PHP
  • ini_get() — Gets the value of a configuration option
  • ini_set() — Sets the value of a configuration option
  • get_loaded_extensions() — Returns an array with the names of all modules compiled and loaded
  • Predefined Variables

User Contributed Notes 21 notes

A simple method to style your own phpinfo() output.

ob_start () ;
phpinfo () ;
$pinfo = ob_get_contents () ;
ob_end_clean () ;

// the name attribute «module_Zend Optimizer» of an anker-tag is not xhtml valide, so replace it with «module_Zend_Optimizer»
echo ( str_replace ( «module_Zend Optimizer» , «module_Zend_Optimizer» , preg_replace ( ‘%^.*(.*).*$%ms’ , ‘$1’ , $pinfo ) ) ) ;

This is necessary to obtain a W3C validation (XHTML1.0 Transitionnal).
phpinfo’s output is declared with that DTD :
— «System ID» has the wrong url to validate : «DTD/xhtml1-transitional.dtd» rather than «http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd»
— Some module names contains space and the function’s output use the name in anchors as ID and NAME. these attributes can’t be validated like that (unique name only).

ob_start (); // Capturing
phpinfo (); // phpinfo ()
$info = trim ( ob_get_clean ()); // output

// Replace white space in ID and NAME attributes. if exists
$info = preg_replace ( ‘/(id|name)(=[«\’][^ «\’]+) ([^ «\’]*[«\’])/i’ , ‘$1$2_$3’ , $info );

$info_doc = new DOMDocument ( ‘1.0’ , ‘utf-8’ );
/* Parse phpinfo’s output
* operator @ used to avoid messages about undefined entities
* or use loadHTML instead
*/
@ $info_doc -> loadXML ( $info );

$doc -> documentElement -> appendChild ( // Adding HEAD element to HTML
$doc -> importNode (
$info_doc -> getElementsByTagName ( ‘head’ )-> item ( 0 ),
true // With all the subtree
)
);
$doc -> documentElement -> appendChild ( // Adding BODY element to HTML
$doc -> importNode (
$info_doc -> getElementsByTagName ( ‘body’ )-> item ( 0 ),
true // With all the subtree
)
);

// Now you get a clean output and you are able to validate.
/*
echo ($doc->saveXML ());
// OR
echo ($doc->saveHTML ());
*/

// By that way it’s easy to add some style declaration :
$style = $doc -> getElementsByTagName ( ‘style’ )-> item ( 0 );
$style -> appendChild (
$doc -> createTextNode (
‘/* SOME NEW CSS RULES TO ADD TO THE FUNCTION OUTPUT */’
)
);

// to add some more informations to display :
$body = $doc -> getElementsByTagName ( ‘body’ )-> item ( 0 );
$element = $doc -> createElement ( ‘p’ );
$element -> appendChild (
$doc -> createTextNode (
‘SOME NEW CONTENT TO DISPLAY’
)
);
$body -> appendChild ( $element );

// to add a new header :
$head = $doc -> getElementsByTagName ( ‘head’ )-> item ( 0 );
$meta = $doc -> createElement ( ‘meta’ );
$meta -> setAttribute ( ‘name’ , ‘author’ );
$meta -> setAttribute ( ‘content’ , ‘arimbourg at ariworld dot eu’ );
$head -> appendChild ( $meta );

// As you wish, take the rest of the output and add it for debugging
$out = ob_get_clean ();

$pre = $doc -> createElement ( ‘div’ ); // or pre
$pre -> setAttribute ( ‘style’ , ‘white-space: pre;’ ); // for a div element, useless with pre
$pre -> appendChild ( $doc -> createTextNode ( $out ));
$body -> appendChild ( $pre );

$doc -> formatOutput = true ; // For a nice indentation
$doc -> saveXML ();

?>

All that could be done with only RegExp but I prefer the use of DOM for manipulating documents

Источник

How to Check PHP Version (Apache/Nginx/CLI)

PHP (Hypertext Preprocessor) is a popular programming language generally used for web development. It was originally developed by the Danish-Canadian programmer Rasmus Lerdorf in the year 1994. It can be used either via the command line or used with popular web servers like Apache or Nginx. Apache has a PHP module to directly run PHP files but Nginx required a PHP-FPM package to work with PHP files.

This tutorial will help you to check the PHP version installed on your system. Also, what is the active version of PHP on the command line as well as the check PHP version used by Apache or Nginx? As we can install multiple PHP versions on a single system, it can be the there are different version’s active on CLI and Web servers.

Check PHP Version (CLI)

By default, there can be one default PHP version that can use with standard binary. To check the PHP version currently active on the command line, execute the following command on the terminal:

Output
PHP 7.4.8 (cli) (built: Jul 13 2020 16:45:28) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies with Zend OPcache v7.4.8, Copyright (c), by Zend Technologies

On Ubuntu and Debian systems, you can also access another version by pointing their versions like: php7.2 or php7.3 etc.

Check PHP Version (Apache/Nginx)

This is fine that, the current active PHP version on the command line is different than the version used by the Apache or Nginx web servers. It’s also possible that two virtual hosts can use different-2 PHP versions by using PHP-FPM.

So, to check the currently active version for Apache or Nginx, navigate to the document root of the website to which you want to check the PHP version. For example, my document root is “/var/www/html”:

Then create and edit a PHP script file in your favorite text editor:

And, add the following content to the files. Here we used built-in phpinfo() function, which prints the active PHP version details:

Источник

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

Язык программирования PHP — один из самых популярных языков для создания веб-сайтов и различных веб-приложений. Когда вы устанавливаете какую-либо систему управления контентом, например, WordPress, Joomla, ModX или что-либо другое, обычно у них есть требование к минимальной версии PHP.

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

Просмотр версии в терминале

Для того чтобы узнать установленную версию PHP в терминале надо иметь SSH доступ к серверу. Подключитесь к серверу по SSH и выполните такую команду:

Утилита покажет информацию о сборке PHP, а также её версию. Однако, такой способ позволяет узнать версию используемую по умолчанию в консоли или php-cli. Если вы используете какую-либо панель управления сервером, то обычно панели устанавливают свои версии PHP отдельно в папку /opt. Чтобы посмотреть версию PHP установленной панелью надо использовать браузер.

Просмотр версии в браузере

Подключитесь по FTP или по SSH к серверу и перейдите в корневой каталог вашего сайта. Там создайте небольшой скрипт со следующим содержимым:

Затем откройте ваш сайт и допишите в адресной строке адрес этого файла:

Если всё сделано верно, будет выведена огромная таблица с информацией про PHP и установленные расширения, а в самом верху страницы будет версия PHP.

Если вы не хотите выводить всю таблицу с информацией о PHP, то можно вывести только версию с помощью функции phpversion. Например:

Тогда, в результате вы получите такую страницу:

Как видите, проверить версию PHP не так уже и сложно. А какие способы знаете вы? Напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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