- phpinfo
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- Примечания
- Смотрите также
- Посмотреть настройки PHP
- Как проверить настройки PHP и функция phpinfo
- phpinfo
- Parameters
- Return Values
- Examples
- Notes
- See Also
- User Contributed Notes 21 notes
- LINUX — HOW TO CHECK PHP CONFIGURATION — PHPINFO()
- 1. The phpinfo() function.
- 2. PHP console utility.
phpinfo
Выводит большое количество информации о текущем состоянии PHP. Сюда входит информация о настройках компиляции PHP, о расширениях, о версии, информация о сервере и среде выполнения (если PHP компилировался как модуль), окружении PHP, версии ОС, о путях, об основных и локальных значениях настроек конфигурации, о HTTP заголовках и лицензии PHP.
Так как каждая система имеет свои особенности, phpinfo() используется в основном для проверки настроек конфигурации и для просмотра доступных предопределенных констант в данной системе.
phpinfo() также используется в целях отладки, так как содержит все EGPCS (Environment, GET, POST, Cookie, Server) данные.
Список параметров
Вывод функции можно настраивать, передавая битовую маску из одной или более приведенных ниже констант (constants). Эта маска передается в качестве необязательного аргумента what . Отдельные константы или битовые значения можно комбинировать с помощью оператора или.
Имя (константа) | Значение | Описание |
---|---|---|
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 | Выводит все приведенное выше. |
Возвращаемые значения
Возвращает 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() — Возвращает массив имен всех скомпилированных и загруженных модулей
- Предопределенные переменные
Посмотреть настройки PHP
Проверить настройки PHP актуальные для сайта можно обратившись к скрипту, содержащему одну специальную PHP функцию.
Как проверить настройки PHP и функция phpinfo
Из консоли для пользователя от имени которого выполняются скрипты (имя пользователя можно найти в php.ini о чём ниже) настройки можно посмотреть так:
В случае с www-data, например:
Однако, это будут настройки для CLI, скрипты же выполняются в режиме CGI, задействуется другой бинарный файл. Как следствие, могут отличаться версия PHP, лимиты и список подключенных расширений.
Точную информацию дает только результат выполнения скрипта с функцией phpinfo() в нем.
Скрипт можно разместить в корне сайта, затем обратиться к нему через браузер. Результатом будет страница с настройками.
На странице отдельными блоками приведены все подключенные расширения и информация по ним. Чаще всего здесь приходится на практике смотреть путь к php.ini, в котором задаются все настройки.
В таблице это значение, соответствующее Loaded Configuration File
Loaded Configuration File | /home/web/etc/php/php.ini |
Этот файл нужно менять чтобы подключить или отключить какие-то расширения.
Также может быть задан какой-то каталог с .ini файлами, каждый из которых будет учитываться. Обычно это конфигурационный файл для каждого расширения в отдельности.
Scan this dir for additional .ini files | (none) |
Если результат выполнения скрипта размещенного в корне сайта не отображается можно попробовать временно (на несколько секунд, которых достаточно чтобы обратиться к странице) переименовать .htaccess.
Иногда мешают директивы, заданные в нем. После проверки настроек нужно вернуть .htaccess прежнее имя, в файле задаются все перенаправления, файл считывает и обрабатывает веб-сервер.
phpinfo() представляет служебную информацию, которая может использоваться для получения сведений о системе. Из соображений безопасности файл в корне сайта лучше не оставлять, а удалить когда требуемые сведения получены.
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.
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 ( ‘%^.*
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
LINUX — HOW TO CHECK PHP CONFIGURATION — PHPINFO()
Every web application or site has important PHP version, extensions and configuration requirements installed on the server. It is recommended to make sure that all necessary PHP settings are installed on your server.
The content of the article:
1. The phpinfo() function.
In the first version of checking the php configuration, the special php function phpinfo() will help us. To use this function, you need to create a file with any name with the .php extension in the root directory of the site, in which you place the code below and save the file.
After saving the file, enter the domain and name of the created file in the browser, and as a result, if PHP is activated on your server, a page with its version and all existing parameters will be displayed.
2. PHP console utility.
The next check option we can use is a special php utility that is installed on your server along with all php components.
The first command shows the PHP version on the server and the compilation time.
The second command shows all installed modules in PHP.
The last command which shows detailed information about PHP.
Thank you all, I hope my article was of some help to you.