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
php вывод текста и переменной | Особенности
Решил я написать эту статью, чтобы расставить точки как правильно и когда выводить данные. Статья не простая, поэтому если Вы ещё никогда не выводили текст ранее, то лучше начните с первого урока курса по PHP, а уже как опыта наберётесь, тогда заглядывайте сюда.
Чтобы вывести на экран текст мы используем одну из следующих конструкций языка: echo или print, либо функцию printf. Давайте разберём варианты и их особенности:
Функция printf позволяет нам вывести на экран отформатированный текст:
printf("%%b = '%b'", 322); // Вывести значение в двоичном представлении
printf используется очень редко, самое популярное применение: преобразовать цену товара в классический вид: рубли.копейки. К примеру:
Если printf используют для вывода очень редко, то вот языковые конструкции print и echo — в каждом коде! Я говорю, что printf функция и значение надо писать в скобках по примеру выше, а вот echo и print — языковые конструкции и текст писать в скобках не надо:
Разница между echo и print есть, хоть смысл у них один и тот же. print может указывать лишь 1 значение, а вот в echo можно перечислять их через запятую:
Не смотря на это всё же можно вывести через один print 2 переменных и делается это с использованием конкатенации:
Конкатенация строк работает следующим образом, она СНАЧАЛА объединяет все в одну большую строку, а уже потом выводит один раз! С другой стороны мы не говорим по очереди «выведи то, выведи сё», мы говорим: у тебя выделено в памяти 1 байт под $x, и 1 байт под $y, объедини $x и $y в памяти и получи ещё одну временную строку в 2 байта (2 символа латинских), и потом выведи и очисти память. В итоге математики уже смогли посчитать. что при конкатенации будет занято уже 4 байта временно на данные, а при перечислении через запятую только 2.
На первый взгляд кажется, что запятая всё же круче в данном случае, но везде повсеместно используют точку. На самом деле ответ очень прост и его подтвердит любой эксперт — нет смысла заморачиваться и экономить на спичках, использование точки считается более классическим и делом привычки многих, и вы никогда в жизни не столкнётесь с тем, что сайт быстрее или медленнее работает из-за точки или запятой. Настоящая производительность сайтов кроется совсем в других вопросах (сложные операции, большой объем данных в Базе Данных)! Поэтому смело используйте то, что Вы уже ранее использовали, переучиваться нет смысла.
По поводу конкатенации стоит заметить самую важную и огромнейшую вещь — её используют для объединения переменной с переменной или строки с переменной, но объединять строку со строкой будет считаться плохим тоном:
Hello