Hướng dẫn localhost phpinfo php

)#s',
        $input,
        $matches,
        PREG_SET_ORDER
    )) {
        foreach ($matches as $match) {
            $fn = strpos($match[0], '            if (strlen($match[1])) {
                $phpinfo[$match[1]] = array();
            } elseif (isset($match[3])) {
                $keys1 = array_keys($phpinfo);
                $phpinfo[end($keys1)][$fn($match[2])] = isset($match[4]) ? array($fn($match[3]), $fn($match[4])) : $fn($match[3]);
            } else {
                $keys1 = array_keys($phpinfo);
                $phpinfo[end($keys1)][] = $fn($match[2]);
            }

        }
    }

        return $phpinfo;
}

The output looks something like this (note the headers are also included but are prefixed with '# ', e.g. '# Directive'):

Array
(
    [phpinfo] => Array
        (
            [0] => PHP Version 5.6.5
            [System] => Darwin Calins-MBP 15.0.0 Darwin Kernel Version 15.0.0: Wed Aug 26 19:41:34 PDT 2015; root:xnu-3247.1.106~5/RELEASE_X86_64 x86_64
            [Build Date] => Feb 19 2015 18:34:18
            [Registered Stream Socket Transports] => tcp, udp, unix, udg, ssl, sslv3, sslv2, tls, tlsv1.0
            [Registered Stream Filters] => zlib.*, bzip2.*, convert.iconv.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk
            [1] => This program makes use of the Zend Scripting Language Engine:Zend Engine...
        )

    [apache2handler] => Array
        (
            [Apache Version] => Apache/2.4.16 (Unix) PHP/5.6.5 OpenSSL/0.9.8zg
            [Apache API Version] => 20120211
            [Server Administrator] =>
            [Hostname:Port] => sitestacker.local:0
            [# Directive] => Array
                (
                    [0] => # Local Value
                    [1] => # Master Value
                )

            [engine] => Array
                (
                    [0] => 1
                    [1] => 1
                )

            [last_modified] => Array
                (
                    [0] => 0
                    [1] => 0
                )

Phelon Dudras

13 years ago

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

keinwort at hotmail dot com

4 years ago

REMARK/INFO: if Content-Security-Policy HTTP header
is
Content-Security-Policy "default-src 'self';";

phpinfo() is shown without a table

Ken

10 years ago

Hi.

Here my version of saving php_info into an array:

function phpinfo_array()
{
   
ob_start();
   
phpinfo();
   
$info_arr = array();
   
$info_lines = explode("\n", strip_tags(ob_get_clean(), "

]+>([^<]*)]+>([^<]*)~", $line, $val))
        {
           
$info_arr[$cat][$val[1]] = $val[2];
        }
        elseif(
preg_match("~
]+>([^<]*)]+>([^<]*)]+>([^<]*)~", $line, $val))
        {
           
$info_arr[$cat][$val[1]] = array("local" => $val[2], "master" => $val[3]);
        }
    }
    return
$info_arr;
}
// example:
echo "
".print_r(phpinfo_array(), 1)."
"
;
?>

SimonD

9 years ago

Removes sensitive data like AUTH_USER and AUTH_PASSWORD from the phpinfo output:

// start output buffering
ob_start();// send phpinfo content
phpinfo();// get phpinfo content
$html = ob_get_contents();// flush the output buffer
ob_end_clean();// remove auth data
if (isset($_SERVER['AUTH_USER'])) $html = str_replace($_SERVER['AUTH_USER'], 'no value', $html);
if (isset(
$_SERVER['AUTH_PASSWORD'])) $html = str_replace($_SERVER['AUTH_PASSWORD'], 'no value', $html);

echo

$html;

arimbourg at ariworld dot eu

11 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).

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

jb2386 at hotmail dot com

15 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

tags also had an align="center". So this update changes the regex for those tags:

/* parse php modules from phpinfo */function parsePHPModules() {
ob_start();
phpinfo(INFO_MODULES);
$s = ob_get_contents();
ob_end_clean();$s = strip_tags($s,'

)#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:

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

To display everything:

    foreach($phpinfo as $name => $section) {
        echo
"

$name

\n

phpinfo.php là tập lệnh PHP chứa thông tin về PHP. Tập lệnh là một phần của cấu hình máy chủ web và được cung cấp cho tất cả các công ty lưu trữ web để hiển thị thông tin theo yêu cầu cụ thể. Chẳng hạn như trang web của bạn có hoạt động bình thường hay không, có bao nhiêu khách đã truy cập và có lỗi nào xảy ra hay không. Trong trường hợp trang web không hoạt động, phpinfo.php này cũng cung cấp thông tin về các lý do có thể xảy ra.

Tập lệnh phpinfo.php là một tài nguyên quan trọng cho phép bạn kiểm tra chức năng của trang web của mình.

Làm thế nào để dễ dàng tạo và sử dụng tệp phpinfo trong trang web php của bạn? Là khó khăn? Có lẽ không nếu bạn biết một chút về php. Giống như bạn có thể tạo một tài liệu html để hiển thị chú thích hoặc thay đổi màu sắc trong phần mềm xử lý văn bản, các nhà phát triển có thể sử dụng dòng lệnh, phpinfo, để hiển thị và thay đổi thông tin về các trang web của họ. Mọi thứ từ các dòng và từ bắt đầu bằng php theo sau là dấu chấm phẩy đến bất kỳ ký hiệu nào (bao gồm cả dấu chấm hỏi) trong tệp phpinfo đều có ý nghĩa đối với php.

Trong khoảng 60 giây, bạn có thể có một phpinfo () Trang SiteInfo trên trang localhost của bạn. Nó khá dễ dàng. Sau đây là các bước:

phpinfo () là một hàm phpinfo () rất, rất mạnh. Nó có thể được sử dụng theo một số cách, tất cả đều khá dễ hiểu. Điều tốt nhất về phpinfo () là nó có thể xuất ra hầu hết mọi thông tin bạn cần về tập lệnh PHP đang được chạy. Điều này có thể bao gồm thông tin như những gì đang được gọi từ bên trong tập lệnh, mảng hình cầu / bí danh, đường dẫn đến tập lệnh và nhiều thông tin khác! Tất cả những gì bạn phải làm để sử dụng phpinfo () là thêm đoạn mã sau vào tập lệnh php của bạn:

phpinfo ();

Làm cách nào để tải Phpinfo trên localhost?

phpinfo nằm trong / var / www / html / phpinfo. Nếu bạn duyệt đến thư mục này khi trang web này được cài đặt, nó sẽ hiển thị cho bạn thông tin về phần mềm được cấu hình trong máy chủ. Điều này bao gồm thông tin về các tiện ích mở rộng php được cài đặt và các thống kê hữu ích như số lượng truy vấn mỗi phút. Có các tệp khác trong / var / www / html / phpinfo, nhưng đây là tệp

Phpinfo.php là gì và nó có thể được sử dụng như thế nào trên trang web WordPress?

Tệp phpinfo.php là một tập lệnh chẩn đoán hiển thị thông tin về cấu hình PHP của máy chủ. Tập lệnh có thể được sử dụng trên bất kỳ máy chủ nào có cài đặt PHP và nó có thể được sử dụng để khắc phục sự cố PHP hoặc chẩn đoán các sự cố tiềm ẩn.

Tệp phpinfo.php là một công cụ dòng lệnh có thể được truy cập bằng cách mở cửa sổ dòng lệnh và gõ “php -i”. Điều này sẽ hiển thị thông tin trên màn hình để bạn xem lại.

Cần tìm gì khi tìm kiếm lỗ hổng trong PHP Info.php

Khi tìm kiếm các lỗ hổng trong PHP info.php, có một số điều bạn nên tìm kiếm. Đầu tiên, lỗ hổng phải nằm trong thư mục tải lên của phpinfo.php. Tiếp theo, bạn nên tìm kiếm một dòng mã cụ thể cho phép kẻ tấn công thực hiện các lệnh trên hệ thống của bạn. Thứ ba, bạn cần xem xét bất kỳ tập lệnh nào khác có thể đã được gọi bởi phpinfo.php và xem chúng có dễ bị tấn công hay không. Cuối cùng, hãy đảm bảo rằng bất kỳ tập lệnh hoặc tệp nào khác trong thư mục của bạn cũng không dễ bị tấn công vì chúng có thể dẫn đến việc kẻ tấn công giành được quyền truy cập vào hệ thống của bạn và thực hiện các lệnh trên đó.

Làm thế nào các nhà phát triển web có thể ngăn chặn phương pháp tấn công này xảy ra?

Kẻ tấn công có thể đưa mã độc vào trang web bằng cách chèn nó vào mã hợp pháp. Bằng cách này, họ có thể truy cập dữ liệu nhạy cảm và sử dụng nó có lợi cho họ.

Các nhà phát triển web nên kiểm tra trang web của họ để tìm các lỗ hổng và đảm bảo rằng chúng không dễ bị tấn công. Họ cũng nên quan tâm đến các bản cập nhật phần mềm của mình và đảm bảo rằng chúng được cập nhật tất cả các bản vá bảo mật mới nhất.

Tại sao Phpinfo của tôi không hoạt động?

Nếu bạn nhận được thông báo lỗi khi cố gắng mở phpinfo.php, thì điều đó có nghĩa là tệp không có ở đó hoặc nó đã bị đổi tên hoặc bị xóa. Bạn có thể thử đổi tên phpinfo.php thành phpinfo2.php và xem cách này có khắc phục được sự cố không. Nếu cách này không hiệu quả, thì bạn có thể cần tạo một tệp phpinfo2.php mới trong thư mục hiện tại của mình với mã sau:

echo “Phiên bản PHP:”. phpversion ();

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

phpinfoOutputs information about PHP's configuration

Description

phpinfo(int $flags = INFO_ALL): bool

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

flags

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

Returns true on success or false on failure.

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

Calin S.

7 years ago

After reading and trying various functions, I couldn't find one that correctly parses all the configurations, strips any left-over html tag and converts special characters into UTF8 (e.g. ' into '), so I created my own by improving on the existing ones:

function phpinfo2array() {
    $entitiesToUtf8 = function($input) {
        // http://php.net/manual/en/function.html-entity-decode.php#104617
        return preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $input);
    };
    $plainText = function($input) use ($entitiesToUtf8) {
        return trim(html_entity_decode($entitiesToUtf8(strip_tags($input))));
    };
    $titlePlainText = function($input) use ($plainText) {
        return '# '.$plainText($input);
    };

        ob_start();
    phpinfo(-1);

        $phpinfo = array('phpinfo' => array());

    // Strip everything after the

Configuration

tag (other h2's)
    if (!preg_match('#(.*]*>\s*Configuration.*)        return array();
    }

        $input = $matches[1];
    $matches = array();

    if(preg_match_all(
        '#(?:(?:)?(.*?)(?:<\/a>)?<\/h2>)|'.
        '(?:(.*?)\s*(?:(.*?)\s*(?:(.*?)\s*)?)?

"));
   
$cat = "General";
    foreach(
$info_lines as $line)
    {
       
// new cat?
       
preg_match("~

(.*)

~"
, $line, $title) ? $cat = $title[1] : null;
        if(
preg_match("~

');
$s = preg_replace('/]*>([^<]+)<\/th>/',"\\1",$s);
$s = preg_replace('/]*>([^<]+)<\/td>/',"\\1",$s);
$vTmp = preg_split('/(]*>[^<]+<\/h2>)/',$s,-1,PREG_SPLIT_DELIM_CAPTURE);
$vModules = array();
for (
$i=1;$i<count($vTmp);$i++) {
  if (
preg_match('/]*>([^<]+)<\/h2>/',$vTmp[$i],$vMat)) {
  
$vName = trim($vMat[1]);
  
$vTmp2 = explode("\n",$vTmp[$i+1]);
   foreach (
$vTmp2 AS $vOne) {
  
$vPat = '([^<]+)<\/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;
}
?>

cbar at vmait dot com

8 years ago

// 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.?>

code at adspeed dot com

16 years ago

This function parses the phpinfo output to get details about a PHP module.

/** parse php modules from phpinfo */
function parsePHPModules() {
ob_start();
phpinfo(INFO_MODULES);
$s = ob_get_contents();
ob_end_clean(); $s = strip_tags($s,'

');
$s = preg_replace('/]*>([^<]+)<\/th>/',"\\1",$s);
$s = preg_replace('/]*>([^<]+)<\/td>/',"\\1",$s);
$vTmp = preg_split('/(

[^<]+<\/h2>)/',$s,-1,PREG_SPLIT_DELIM_CAPTURE);
$vModules = array();
for (
$i=1;$i<count($vTmp);$i++) {
  if (
preg_match('/

([^<]+)<\/h2>/',$vTmp[$i],$vMat)) {
  
$vName = trim($vMat[1]);
  
$vTmp2 = explode("\n",$vTmp[$i+1]);
   foreach (
$vTmp2 AS $vOne) {
   
$vPat = '([^<]+)<\/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
  )
)

/** 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)"

Helpful Harry

16 years ago

check out this cool and fantastic colourful phpinfo()!

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

jon at sitewizard dot ca

14 years ago

To extract all of the data from phpinfo into a nested array:
ob_start();
phpinfo();
$phpinfo = array('phpinfo' => array());
if(
preg_match_all('#(?:

(?:)?(.*?)(?:)?

)|(?:(.*?)\s*(?:(.*?)\s*(?:(.*?)\s*)?)?

\n";
        foreach(
$section as $key => $val) {
            if(
is_array($val))
                echo
"
\n";
            elseif(
is_string($key))
                echo
"
\n";
            else
                echo
"
\n";
        }
        echo
"
$key$val[0]$val[1]
$key$val
$val
\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.

yurkins

14 years ago

big thanx 2 Mardy dot Hutchinson at gmail dot com
very good!

some fixes to correct result displaying:
1. we need to trim $matches [1], 'cause there can be empty lines;
2. not bad to remove tag 'cause styles for it not apply correctly...
3. ...and change styles a little (remove "body" selector)

we need to change two lines:

preg_match ('%.*?(.*)%s', ob_get_clean(), $matches);
?>
to
preg_match ('%.*?(.*?)%s', ob_get_clean(), $matches);
?>

and

preg_split( '/\n/', $matches[1] )
?>
to
preg_split( '/\n/', trim(preg_replace( "/\nbody/", "\n", $matches[1])) )
?>

That's all! Now we have a really flexible addition to phpinfo();

Andrew dot Boag at catalyst dot net dot nz

15 years ago

One note on the above functions for cleaning up the phpinfo() HTML and throwing it into an array data structure. In order to catch all of the info tidbits the preg_match_all has to be tweaked to deal with 2 and 3 column tables.

I have changed the preg_match_all() here so that the last is optional

function parsePHPConfig() {
   
ob_start();
   
phpinfo(-1);
   
$s = ob_get_contents();
   
ob_end_clean();
   
$a = $mtc = array();
    if (
preg_match_all('/(.*?)<\/td>(.*?)<\/td>(:?(.*?)<\/td>)?<\/tr>/',$s,$mtc,PREG_SET_ORDER))
        foreach(
$mtc as $v){
            if(
$v[2] == 'no value') continue;
           
$a[$v[1]] = $v[2];
        }
    }
    return
$a;
}
?>

Joseph Reilly

7 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:
function quick_dev_insights_phpinfo() {
ob_start();
phpinfo(11);
$phpinfo = array('phpinfo' => array());

    if(

preg_match_all('#(?:

(?:)?(.*?)(?:)?

)|(?:(.*?)\s*(?:(.*?)\s*(?:(.*?)\s*)?)?)#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
"

$name

\n\n";
            foreach(
$section as $key => $val){
                    if(
is_array($val)){
                    echo
"\n";
                    }elseif(
is_string($key)){
                    echo
"\n";
                    }else{
                    echo
"\n";
                }
            }
        }
            echo
"
$key$val[0]$val[1]
$key$val
$val
\n"
;
        }else{
    echo
"

Sorry, the phpinfo() function is not accessable. Perhaps, it is disabledSee the documentation.

"
;
    }
}
?>
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.

Mardy dot Hutchinson at gmail dot com

15 years ago

Embedding phpinfo within your page, that already has style information:

The phpinfo output is wrapped within a

, and we privatize all the style selectors that phpinfo() creates.

Yes, we cheat on preparing the selector list.

ob_start();
phpinfo();preg_match ('%.*?(.*)%s', ob_get_clean(), $matches);# $matches [1]; # Style information
# $matches [2]; # Body information
echo "

\n",
   
$matches[2],
   
"\n
\n";
?>

Perhaps one day the phpinfo() function will be modified to output such a safe string on its own.

webmaster at askapache dot com

13 years ago

I wanted a simple *function* to convert the output of phpinfo into an array.  Here's what I came up with thanks to alot of the previous authors tips, and the source file: php-5.2.6/ext/standard/info.c

Call this function like phpinfo_array() prints the array, phpinfo_array(1) returns the array for your own processing.

== Sample Output ==
[PHP Configuration] => Array
(
  [PHP Version] => 5.2.6
  [PHP Egg] => PHPE9568F34-D428-11d2-A769-00AA001ACF42
  [System] => Linux askapache 2.6.22.19-grsec3
  [Build Date] => Nov 11 2008 13:09:07
  [Configure Command] =>  ./configure --prefix=/home/grsec/bin/php
  [Server API] => FastCGI

  [IPv6 Support] => enabled
[Zend Egg] => PHPE9568F35-D428-11d2-A769-00AA001ACF42
  [PHP Credits Egg] => PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000
)

[mbstring] => Array
(
  [mbstring.http_input] => pass
  [mbstring.internal_encoding] => Array
    (
     [0] => ISO-8859-1
     [1] => no value
    )

  [mbstring.language] => neutral
   )

[mcrypt] => Array
(
  [Version] => 3.5.7
  [Api No] => 20031217
)

function phpinfo_array($return=false){
/* Andale!  Andale!  Yee-Hah! */
ob_start();
phpinfo(-1);$pi = preg_replace(
array(
'#^.*(.*).*$#ms', '#

PHP License

.*$#ms',
'#

Configuration

#'
"#\r?\n#", "##", '# +<#',
"#[ \t]+#", '# #', '#  +#', '# class=".*?"#', '%'%',
 
'#(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" />'
 
.'

PHP Version (.*?)

(?:\n+?)#'
,
 
'#

PHP Credits

#'
,
 
'#(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)#',
 
"# +#", '##', '##'),
array(
'$1', '', '', '', '' . "\n", '<', ' ', ' ', ' ', '', ' ',
 
'

PHP Configuration

'
."\n".'PHP Version$2'.
 
"\n".'PHP Egg$1',
 
'PHP Credits Egg$1',
 
'Zend Engine$2' . "\n" .
 
'Zend Egg$1', ' ', '%S%', '%E%'),
ob_get_clean());$sections = explode('

', strip_tags($pi, '

'));
unset(
$sections[0]);$pi = array();
foreach(
$sections as $section){
  
$n = substr($section, 0, strpos($section, '

'
));
  
preg_match_all(
  
'#%S%(?:(.*?))?(?:(.*?))?(?:(.*?))?%E%#',
    
$section, $askapache, PREG_SET_ORDER);
   foreach(
$askapache as $m)
      
$pi[$n][$m[1]]=(!isset($m[3])||$m[2]==$m[3])?$m[2]:array_slice($m,2);
}

return (

$return === false) ? print_r($pi) : $pi;
}
?>

henzeberkheij at dot SPAM dot gmail dot com

10 years ago

I needed a way to quickly scroll through the phpinfo which is a large list of information. so here it is. In the top there is a list with sections, the new section loaded extensions will hold the links to the anchors of the loaded modules. the section session variables will show the current loaded sessions. It's using Domdocument for manipulation so you should have that loaded:
ob_start();
   
$exts = get_loaded_extensions();
   
phpinfo();
   
$phpinfo = ob_get_contents();
   
ob_end_clean();
   
//print $phpinfo;
   
$html_str = $phpinfo;
   
$html = new DOMDocument();
   
$html->loadHTML($html_str);
   
$title = $html->getElementsByTagName("title")->item(0);
   
$title->nodeValue = "PHP Version ".phpversion();
   
$body = $html->getElementsByTagName("body")->item(0);$body->setAttribute("style", "background-color:beige;");
   
$table = $body = $html->getElementsByTagName("table")->item(3)->nextSibling;
   
$head  = $html->getElementsByTagName("table")->item(0)->nextSibling;
   
ob_start();
   
?>
   

Session variables


   
   
    foreach($_SESSION as $key=>$value){
        if(
is_bool($value)){
           
$value = ($value)?"true":"false";
        }else if(
is_array($value)){
           
$value = '
'.print_r($value, true).'
'
;
        }else if(empty(
$value) && $value != "0"){
           
$value = "no value";
        }
   
?>
   

       
       
   
        }
   
?>
   
VariablesValue

       

loaded extensions


   
   
   

                natcasesort

($exts);
    foreach(
$exts as $value){
       
$version = phpversion($value);   
   
?>
   

       

       

   

        }
   
?>
   
ExtensionVersion
(!empty($version))?$version:"Unknown" ?>


        $txt_str = ob_get_contents();
   
ob_end_clean();
   
$txt = new DOMDocument();
   
$txt->loadHTML($txt_str);
   
$txt_body = $txt->getElementsByTagName("body")->item(0);

    foreach(

$txt_body->childNodes as $child){
       
$child = $html->importNode($child, true);
       
$table->parentNode->insertBefore($child, $table);
    }
$h2 = $html->getElementsByTagName("h2");
    foreach(
$h2 as $item){
        if(
$item->getElementsByTagName("a")->length == 0){
           
$value = $item->nodeValue;
           
$item->nodeValue = "";
           
$a = $html->createElement("a");
           
$a->setAttribute("name", strtolower(str_replace(" ", "_", $value)));
           
$a->nodeValue = $value;
           
$item->appendChild($a);
        }
       
$a = $item->getElementsByTagName("a")->item(0);

                if(!

in_array($a->nodeValue, $exts)){
           
$menu[strtolower(str_replace(" ", "_", $a->nodeValue))] = $a->nodeValue;
        }
       
$top_a = $html->createElement("a");
        if(!
in_array($a->nodeValue, $exts)){
           
$txt = $html->createTextNode("(Go to top)");
           
$top_a->appendChild($txt);
           
$top_a->setAttribute("href", "#");
        }else{
           
$txt = $html->createTextNode("(Go to extensionlist)");
           
$top_a->appendChild($txt);
           
$top_a->setAttribute("href", "#loaded_extensions");
        }
       
$top_a->setAttribute("style", "background-color:beige; font-size:12px; margin-left:5px; margin-top:-5px; color:black;");
       
$item->appendChild($top_a);       
    }
   
ob_start();
   
?>
   

   
   
   
                $i = 0;
        foreach(
$menu as $key=>$item){
            print
"";
            if(
$i%2){
                print
'';
            }
           
$i++;
        }
        if(
$i%2){
            print
'';
        }
       
?>
   
   
Sections
$item

            $txt_str = ob_get_clean();
   
$txt = new DOMDocument();
   
$txt->loadHTML($txt_str);
   
$txt_body = $txt->getElementsByTagName("body")->item(0);
    foreach(
$txt_body->childNodes as $child){
       
$child = $html->importNode($child, true);
       
$table->parentNode->insertBefore($child, $head);
    }
    print
$html->saveHTML();
?>

neo_selen

10 years ago

here you can notice that these numeric values of phpinfo
are similar to certain things in the binary system:

-1, coded in 7 digits:
111 1111

look at this:
1+2+4+8+16+32+64=127

unsigned,127 is:
111 1111

so, take a look at this: the way to get all function is to add all of them. zero is nothing.-1 is all.
so you can pass option with a negative number.
for example:
(48) ?>
is also:
(-80) ?>
48 = 32 + 16
-80= 0 - 64 - 8 - 4 - 2 - 1

so you can see in negative mode it like that:
not nothing
not all (-1) don't forget it !
not option 64
not option 8
not option 4
not option 2

so, that's good if you don't want option 8, you will do this:
not nothing(0)
not all(-1)
not option 8(-1)
you got:
(-9); ?>

hope this will be useful, that's my 1rst post ^^

LewisR

7 years ago

Building on SimonD's elegant example to hide the logged-in username and password, which otherwise appear in plain text, the following should work for PHP 5.4+:

    // start output buffering
   
ob_start();// send phpinfo content
   
phpinfo();// get phpinfo content
   
$html = ob_get_contents();// flush the output buffer
   
ob_end_clean();// remove auth data
   
if ( isset( $_SERVER[ 'PHP_AUTH_USER' ] ) ) $html = str_replace( $_SERVER[ 'PHP_AUTH_USER' ], '[ protected ]' , $html);
    if ( isset(
$_SERVER[ 'PHP_AUTH_PW' ] ) ) $html = str_replace( $_SERVER[ 'PHP_AUTH_PW' ], '[ protected ]' , $html);

    echo

$html;
?>

To remove additional items, just add them as above.

bimal at sanjaal dot com

4 years ago

If you are embeding the output of the function within a page, the tag can collide and page will distort.

Rather, it is important to extract the contents within the and tags only. Here is how.

    public function info()
    {
       
ob_start();
           
phpinfo();
       
$info = ob_get_clean();$info = preg_replace("/^.*?\/is", "", $info);
       
$info = preg_replace("/<\/body\>.*?$/is", "", $info);

        echo

$info;
    }
?>

Bài Viết Liên Quan