phpinfo

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

phpinfoVisualizza diverse informazioni sul PHP

Descrizione

function phpinfo(int $what = ?): int

Visualizza molte informazioni sullo stato corrente del PHP Queste includono informazioni sulle opzioni di compila del PHP, sui moduli, la versioen di PHP, informazioni sul server e sull'ambiente (se compilato come modulo), l'ambiente PHP, la versione di OS, percorsi, valori delle configurazioni base e attauli, intestazioni HTTP e la licenza del PHP.

Dato che ogni sistema ha una cofigurazione differente, phpinfo() viene comunemente utilizzato per verificare le impostazioni di configurazione e le variabili predefinite disponibili in un dato sistema. Inoltre, phpinfo() è utili come strumento di debug poiché visualizza tutti i dati EGPCS (Environment, GET, POST, Cookie, Server).

L'output può essere personalizzato passando una o più delle seguenti costanti sommate a livello di bit nel parametro opzionale what. Le costanti, o i rispettivi valori, possono essere combinati anche con l'operatore or.

Opzioni di phpinfo()
Nome (constant) Valore Descrizione
INFO_GENERAL 1 La linea di configurazione, php.ini luogo, data di compila, Web Server, sistema e altro.
INFO_CREDITS 2 PHP 4 Credits. Vedere anche phpcredits().
INFO_CONFIGURATION 4 Impostazioni correnti e di base delle opzioni PHP. Vedere anche ini_get().
INFO_MODULES 8 Moduli caricati e le loro impostazioni. Vedere anche get_loaded_extensions().
INFO_ENVIRONMENT 16 Variabili d'ambiente disponibili in $_ENV.
INFO_VARIABLES 32 Visualizza tutte le variabili predefinite da EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE 64 Informazioni sulla licenza di PHP. Vedere anche » faq sulla licenza.
INFO_ALL -1 Visualizza tutto quanto descritto. Questo è il valore dei default.

Example #1 Esempio di uso di phpinfo()

<?php

// Visualizza tutte le informazioni, default: INFO_ALL
phpinfo();

// Solo le informazioni sui moduli
// phpinfo(8) visualizza il medesimo risultato
phpinfo(INFO_MODULES);

?>

Nota:

La visualizzazione di parte delle informazioni è disabilitata quando expose_php viene impostato a off. Queste includono i loghi PHP e Zend, e i credits.

Nota:

La funzione phpinfo() produce un testo normale anzichè un file HTML quando è utilizzata in modalità CLI.

Vedere anche phpversion(), phpcredits(), php_logo_guid(), ini_get(), ini_set(), get_loaded_extensions() e la sezione sulle Variabili Predefinite.

add a note

User Contributed Notes 18 notes

up
17
Phelon Dudras
17 years ago
A simple method to style your own phpinfo() output.

<style type="text/css">
#phpinfo {}
#phpinfo pre {}
#phpinfo a:link {}
#phpinfo a:hover {}
#phpinfo table {}
#phpinfo .center {}
#phpinfo .center table {}
#phpinfo .center th {}
#phpinfo td, th {}
#phpinfo h1 {}
#phpinfo h2 {}
#phpinfo .p {}
#phpinfo .e {}
#phpinfo .h {}
#phpinfo .v {}
#phpinfo .vr {}
#phpinfo img {}
#phpinfo hr {}
</style>

<div id="phpinfo">
<?php

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 ( '%^.*<body>(.*)</body>.*$%ms', '$1', $pinfo ) ) ) ;

?>
</div>
up
7
alec dot hewitt at gmail dot com
3 years ago
Simple JS snippet to print phpinfo() inline with it's styles renamed. Thus leaving the container page unaffected and pretty.

<script>
document.write(`<div id="phpinfo"><?php phpinfo(61) ?></div>`);
var x = document.querySelector('#phpinfo > style');
x.innerText = x.innerText.replaceAll('\n', '#phpinfo ');
</script>
up
5
cbar at vmait dot com
12 years ago
<?php

// NOTE: When accessing a element from the above phpinfo_array(), you can do:
$array = phpinfo_array();

// This will work
echo $array["General"]["System "];  

// This should work also, but it doesn't because there is a space after System in the array.
  echo $array["General"]["System"];  

// I hope the coder will fix it, so as to save someone else from wasting time. Otherwise, nice script.
 

?>
up
7
code at adspeed dot com
20 years ago
This function parses the phpinfo output to get details about a PHP module. 

<?php
/** parse php modules from phpinfo */
function parsePHPModules() {
 ob_start();
 phpinfo(INFO_MODULES);
 $s = ob_get_contents();
 ob_end_clean();
 
 $s = strip_tags($s,'<h2><th><td>');
 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/',"<info>\\1</info>",$s);
 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/',"<info>\\1</info>",$s);
 $vTmp = preg_split('/(<h2>[^<]+<\/h2>)/',$s,-1,PREG_SPLIT_DELIM_CAPTURE);
 $vModules = array();
 for ($i=1;$i<count($vTmp);$i++) {
  if (preg_match('/<h2>([^<]+)<\/h2>/',$vTmp[$i],$vMat)) {
   $vName = trim($vMat[1]);
   $vTmp2 = explode("\n",$vTmp[$i+1]);
   foreach ($vTmp2 AS $vOne) {
    $vPat = '<info>([^<]+)<\/info>';
    $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
    $vPat2 = "/$vPat\s*$vPat/";
    if (preg_match($vPat3,$vOne,$vMat)) { // 3cols
     $vModules[$vName][trim($vMat[1])] = array(trim($vMat[2]),trim($vMat[3])); 
    } elseif (preg_match($vPat2,$vOne,$vMat)) { // 2cols
     $vModules[$vName][trim($vMat[1])] = trim($vMat[2]); 
    } 
   } 
  } 
 } 
 return $vModules;
}
?>

Sample Output:
[gd] => Array
(
  [GD Support] => enabled
  [GD Version] => bundled (2.0.28 compatible)
  [FreeType Support] => enabled
  [FreeType Linkage] => with freetype
  [FreeType Version] => 2.1.9
  [T1Lib Support] => enabled
  [GIF Read Support] => enabled
  [GIF Create Support] => enabled
  [JPG Support] => enabled
  [PNG Support] => enabled
  [WBMP Support] => enabled
  [XBM Support] => enabled
)

[date] => Array (
  [date/time support] => enabled
  [Timezone Database Version] => 2005.14
  [Timezone Database] => internal
  [Default timezone] => America/Los_Angeles
  [Directive] => Array (
     [0] => Local Value
     [1] => Master Value
  )
  [date.timezone] => Array (
     [0] => no value
     [1] => no value
  )
 )


<?php
/** get a module setting */
function getModuleSetting($pModuleName,$pSetting) {
 $vModules = parsePHPModules();
 return $vModules[$pModuleName][$pSetting];
}
?>

Example: getModuleSetting('gd','GD Version'); returns "bundled (2.0.28 compatible)"
up
6
Helpful Harry
20 years ago
check out this cool and fantastic colourful phpinfo()!

<?php

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

preg_match_all('/#[0-9a-fA-F]{6}/', $phpinfo, $rawmatches);
for ($i = 0; $i < count($rawmatches[0]); $i++)
   $matches[] = $rawmatches[0][$i];
$matches = array_unique($matches);

$hexvalue = '0123456789abcdef';

$j = 0;
foreach ($matches as $match)
{

   $r = '#';
   $searches[$j] = $match;
   for ($i = 0; $i < 6; $i++)
      $r .= substr($hexvalue, mt_rand(0, 15), 1);
   $replacements[$j++] = $r;
   unset($r);
}

for ($i = 0; $i < count($searches); $i++)
   $phpinfo = str_replace($searches, $replacements, $phpinfo);
echo $phpinfo;
?>
up
6
jb2386 at hotmail dot com
19 years ago
This is a slight modification to the previous code by "code at adspeed dot com" that extracts the PHP modules as an array. I used it on PHP 4.1.2 and it failed as the <h2> tags also had an align="center". So this update changes the regex for those tags:

<?php

/* parse php modules from phpinfo */

function parsePHPModules() {
 ob_start();
 phpinfo(INFO_MODULES);
 $s = ob_get_contents();
 ob_end_clean();

 $s = strip_tags($s,'<h2><th><td>');
 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/',"<info>\\1</info>",$s);
 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/',"<info>\\1</info>",$s);
 $vTmp = preg_split('/(<h2[^>]*>[^<]+<\/h2>)/',$s,-1,PREG_SPLIT_DELIM_CAPTURE);
 $vModules = array();
 for ($i=1;$i<count($vTmp);$i++) {
  if (preg_match('/<h2[^>]*>([^<]+)<\/h2>/',$vTmp[$i],$vMat)) {
   $vName = trim($vMat[1]);
   $vTmp2 = explode("\n",$vTmp[$i+1]);
   foreach ($vTmp2 AS $vOne) {
   $vPat = '<info>([^<]+)<\/info>';
   $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
   $vPat2 = "/$vPat\s*$vPat/";
   if (preg_match($vPat3,$vOne,$vMat)) { // 3cols
     $vModules[$vName][trim($vMat[1])] = array(trim($vMat[2]),trim($vMat[3]));
   } elseif (preg_match($vPat2,$vOne,$vMat)) { // 2cols
     $vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
   }
   }
  }
 }
 return $vModules;
}
?>
up
6
jon at sitewizard dot ca
18 years ago
To extract all of the data from phpinfo into a nested array:
<?php
ob_start();
phpinfo();
$phpinfo = array('phpinfo' => array());
if(preg_match_all('#(?:<h2>(?:<a name=".*?">)?(.*?)(?:</a>)?</h2>)|(?:<tr(?: class=".*?")?><t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>)?)?</tr>)#s', ob_get_clean(), $matches, PREG_SET_ORDER))
    foreach($matches as $match)
        if(strlen($match[1]))
            $phpinfo[$match[1]] = array();
        elseif(isset($match[3]))
            $phpinfo[end(array_keys($phpinfo))][$match[2]] = isset($match[4]) ? array($match[3], $match[4]) : $match[3];
        else
            $phpinfo[end(array_keys($phpinfo))][] = $match[2];
?>

Some examples of using individual values from the array:

<?php
    echo "System: {$phpinfo['phpinfo']['System']}<br />\n";
    echo "Safe Mode: {$phpinfo['PHP Core']['safe_mode'][0]}<br />\n";
    echo "License: {$phpinfo['PHP License'][0]}<br />\n";
?>

To display everything:

<?php
    foreach($phpinfo as $name => $section) {
        echo "<h3>$name</h3>\n<table>\n";
        foreach($section as $key => $val) {
            if(is_array($val))
                echo "<tr><td>$key</td><td>$val[0]</td><td>$val[1]</td></tr>\n";
            elseif(is_string($key))
                echo "<tr><td>$key</td><td>$val</td></tr>\n";
            else
                echo "<tr><td>$val</td></tr>\n";
        }
        echo "</table>\n";
    }
?>

Note: In order to properly retrieve all of the data, the regular expression matches table headers as well as table data, resulting in 'Local Value' and 'Global Value' showing up as 'Directive' entries.
up
4
keinwort at hotmail dot com
8 years ago
REMARK/INFO: if Content-Security-Policy HTTP header
is
Content-Security-Policy "default-src 'self';";

phpinfo() is shown without a table
up
3
Joseph Reilly
11 years ago
One note on the very useful example by "jon at sitewizard dot ca".  
The following statements:
Statement 1:
$phpinfo[end(array_keys($phpinfo))][$match[2]] = isset($match[4]) ? array($match[3], $match[4]) : $match[3];
Statement 2:
$phpinfo[end(array_keys($phpinfo))][] = $match[2];

These two lines will produce the error "Strict Standards:  Only variables should be passed by reference in...".  The root of the error is in the incorrect use of the end() function. The code works but thows the said error.
To address this try using the following statements:

Statement 1 revision:
$keys = array_keys($phpinfo);
$phpinfo[end($keys)][$match[2]] = isset($match[4]) ? array($match[3], $match[4]) : $match[3];

Statement 2 revision:
$keys = array_keys($phpinfo);
$phpinfo[end($keys)][] = $match[2];

This fixes the error. 
To wrap it all in an example:
<?php
function quick_dev_insights_phpinfo() {
ob_start();
phpinfo(11);
$phpinfo = array('phpinfo' => array());

    if(preg_match_all('#(?:<h2>(?:<a name=".*?">)?(.*?)(?:</a>)?</h2>)|(?:<tr(?: class=".*?")?><t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>)?)?</tr>)#s', ob_get_clean(), $matches, PREG_SET_ORDER)){
        foreach($matches as $match){
        if(strlen($match[1])){
            $phpinfo[$match[1]] = array();
        }elseif(isset($match[3])){
        $keys1 = array_keys($phpinfo);
        $phpinfo[end($keys1)][$match[2]] = isset($match[4]) ? array($match[3], $match[4]) : $match[3];
        }else{
            $keys1 = array_keys($phpinfo);
            $phpinfo[end($keys1)][] = $match[2];      
            
        }
        
        }
}

    if(! empty($phpinfo)){
        foreach($phpinfo as $name => $section) {
            echo "<h3>$name</h3>\n<table class='wp-list-table widefat fixed pages'>\n";
            foreach($section as $key => $val){
                    if(is_array($val)){
                    echo "<tr><td>$key</td><td>$val[0]</td><td>$val[1]</td></tr>\n";
                    }elseif(is_string($key)){
                    echo "<tr><td>$key</td><td>$val</td></tr>\n";
                    }else{
                    echo "<tr><td>$val</td></tr>\n";
                }
            }
        }
            echo "</table>\n";
        }else{
    echo "<h3>Sorry, the phpinfo() function is not accessable. Perhaps, it is disabled<a href='http://php.net/manual/en/function.phpinfo.php'>See the documentation.</a></h3>";
    }
}
?>
Frankly, I went thought the trouble of adding this note because the example by "jon at sitewizard dot ca"  is probably the best on the web, and thought it unfortunate that it throws errors. Hope this is useful to someone.
up
2
arimbourg at ariworld dot eu
15 years ago
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).

<?php

ob_start ();

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);

$imp = new DOMImplementation ();
$dtd = $imp->createDocumentType (
    'html',
    '-//W3C//DTD XHTML 1.0 Transitional//EN',
    'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'
);
$doc = $imp->createDocument (
    'http://www.w3.org/1999/xhtml',
    'html',
    $dtd
);
$doc->encoding = 'utf-8';

$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