Php code to get php version

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

Читайте также:  Видеокурсы по html для начинающих

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

Источник

phpversion

Returns a string containing the version of the currently running PHP parser or extension.

Parameters

An optional extension name.

Return Values

Returns the current PHP version as a string . If a string argument is provided for extension parameter, phpversion() returns the version of that extension, or false if there is no version information associated or the extension isn’t enabled.

Changelog

Examples

Example #1 phpversion() example

// prints e.g. ‘Current PHP version: 4.1.1’
echo ‘Current PHP version: ‘ . phpversion ();

// prints e.g. ‘2.0’ or nothing if the extension isn’t enabled
echo phpversion ( ‘tidy’ );
?>

Example #2 PHP_VERSION_ID example and usage

// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
if (! defined ( ‘PHP_VERSION_ID’ )) $version = explode ( ‘.’ , PHP_VERSION );

Читайте также:  Class java lang illegalstateexception

define ( ‘PHP_VERSION_ID’ , ( $version [ 0 ] * 10000 + $version [ 1 ] * 100 + $version [ 2 ]));
>

// PHP_VERSION_ID is defined as a number, where the higher the number
// is, the newer a PHP version is used. It’s defined as used in the above
// expression:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Now with PHP_VERSION_ID we can check for features this PHP version
// may have, this doesn’t require to use version_compare() everytime
// you check if the current PHP version may not support a feature.
//
// For example, we may here define the PHP_VERSION_* constants thats
// not available in versions prior to 5.2.7

if ( PHP_VERSION_ID < 50207 ) define ( 'PHP_MAJOR_VERSION' , $version [ 0 ]);
define ( ‘PHP_MINOR_VERSION’ , $version [ 1 ]);
define ( ‘PHP_RELEASE_VERSION’ , $version [ 2 ]);

Notes

Note:

This information is also available in the predefined constant PHP_VERSION . More versioning information is available using the PHP_VERSION_* constants.

See Also

  • PHP_VERSION constants
  • version_compare() — Compares two «PHP-standardized» version number strings
  • phpinfo() — Outputs information about PHP’s configuration
  • phpcredits() — Prints out the credits for PHP
  • zend_version() — Gets the version of the current Zend engine

Источник

How to get the current PHP version.

This a guide on how to check the current version of PHP.

This can be useful for a number of reasons:

  • You’re building a portable PHP application and you need to be able to programmatically detect the current version so that you can provide fallback code for unsupported features.
  • You want to prevent your PHP application from being run on earlier versions of PHP.
  • You’re using a shared hosting solution and you’re not sure which PHP version is installed.

The PHP_VERSION constant.

One approach is to use the predefined PHP_VERSION constant, which can be used like so:

//Using the PHP_VERSION constant. echo PHP_VERSION, '
';

The advantage of using the PHP_VERSION constant is that it looks cleaner and has no function overhead. Note that this constant is defined by the PHP core. i.e. It is automatically available to all PHP scripts.

Comparing versions.

In the example below, we use the version_compare function to check if our PHP_VERSION constant is 7 or above:

//If the current version is 7.0.0 or above. if(version_compare(PHP_VERSION, '7.0.0') >= 0) < //PHP is 7 or above. >

This can be useful if you need to use fallback functions for libraries that were only introduced in PHP 7.

Another example, in which we kill the script if PHP is below 7.0.0:

//Prevent app from running on older versions. if(version_compare(PHP_VERSION, ‘7.0.0’)

The phpversion() function.

The function phpversion will return a string containing the current PHP version:

//Print out the current PHP version. echo 'PHP Version: ' . phpversion();

If you run the code above, you will see that it outputs something like “PHP Version: 5.5.12”

Note that in some cases, the version will contain information about the package such as: “php5 5.5.9+dfsg-1ubuntu4.22”

Obviously, the result of this function will depend on which PHP package has been installed on your server.

Читайте также:  What is constructor in java with example

Getting the version via the command line.

You can also check the PHP version by using the Command Line Interface (CLI). You can do this by using the following command:

On a Windows machine, this resulted in the following output:

cmd php

A screenshot of the “php -v” command being used in Window’s CMD.

As you can see, the result was: PHP 5.5.12 (cli) (built: Apr 30 2014 11:20:58).

This Linux command line will also display something similar:

The above screenshot is from an Ubuntu 16 server that had PHP 7.2 installed.

Note that the “php -v” command will return the PHP CLI version. In some cases, this may differ from the version of PHP that Apache or Nginx is using.

The phpinfo function.

The phpinfo function can be used to output information about your PHP configuration. This information will also contain the current version:

//Output info about the current PHP installation. phpinfo();

If you call the function above, you will see that the version is displayed in the top left-hand corner of the page:

php version

A screenshot from the phpinfo() output.

This output contains a lot of sensitive details about your PHP environment. As a result, it should never be left on a live server.

Источник

phpversion

Возвращает строку с номером версии текущего PHP-анализатора или расширения.

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

Необязательное имя расширения.

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

Если задан аргумент extension , phpversion() вернет версию этого расширения или FALSE , если информации о версии нет или расширение в данный момент не подключено.

Примеры

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

// Выводит строку типа ‘Текущая версия PHP: 4.1.1’
echo ‘Текущая версия PHP: ‘ . phpversion ();

// Выводит строку типа ‘2.0’ или ничего, если расширение не подключено
echo phpversion ( ‘tidy’ );
?>

Пример #2 Пример использования PHP_VERSION_ID

// PHP_VERSION_ID доступна в версиях PHP 5.2.7 и выше. Если
// наша версия ниже, можно ее сэмулировать
if (! defined ( ‘PHP_VERSION_ID’ )) $version = explode ( ‘.’ , PHP_VERSION );

define ( ‘PHP_VERSION_ID’ , ( $version [ 0 ] * 10000 + $version [ 1 ] * 100 + $version [ 2 ]));
>

// PHP_VERSION_ID определена как число. Чем больше число, тем новее
// PHP. Эта константа задается по той же схеме, что приведена выше:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Теперь с PHP_VERSION_ID можно проверять, какой функционал есть в
// текущей версии PHP. Не обязательно пользоваться version_compare()
// каждый раз, когда требуется проверить, поддерживает ли PHP нужную
// нам функцию.
//
// Например, мы можем задать значения констант PHP_VERSION_*,
// которые недоступны в версиях ранее 5.2.7

if ( PHP_VERSION_ID < 50207 ) define ( 'PHP_MAJOR_VERSION' , $version [ 0 ]);
define ( ‘PHP_MINOR_VERSION’ , $version [ 1 ]);
define ( ‘PHP_RELEASE_VERSION’ , $version [ 2 ]);

Примечания

Замечание:

Эта информация также доступна через предопределенную константу PHP_VERSION . Более детальную информацию можно получить с помощью констант PHP_VERSION_* .

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

  • Константы PHP_VERSION
  • version_compare() — Сравнивает две «стандартизованные» строки с номером версии
  • phpinfo() — Выводит информацию о текущей конфигурации PHP
  • phpcredits() — Выводит список разработчиков PHP
  • php_logo_guid() — Получение guid логотипа
  • zend_version() — Получает версию Zend движка

Источник

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