ini_get

(PHP 4, PHP 5)

ini_get Получает значение настройки конфигурации

Описание

string ini_get ( string $varname )

В случае успеха возвращает значение настройки конфигурации.

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

varname

Имя настройки конфигурации.

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

Возвращает значение настройки конфигурации в виде строки. Для значений null будет возвращаться пустая строка. Функция вернет FALSE, если указанная настройка не существует.

Примеры

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

<?php
/*
Наш файл php.ini содержит следующие настройки:

display_errors = On
register_globals = Off
post_max_size = 8M
*/

echo 'display_errors = ' ini_get('display_errors') . "\n";
echo 
'register_globals = ' ini_get('register_globals') . "\n";
echo 
'post_max_size = ' ini_get('post_max_size') . "\n";
echo 
'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n";
echo 
'post_max_size in bytes = ' return_bytes(ini_get('post_max_size'));

function 
return_bytes($val) {
    
$val trim($val);
    
$last strtolower($val[strlen($val)-1]);
    switch(
$last) {
        
// Модификатор 'G' доступен, начиная с PHP 5.1.0
        
case 'g':
            
$val *= 1024;
        case 
'm':
            
$val *= 1024;
        case 
'k':
            
$val *= 1024;
    }

    return 
$val;
}

?>

Результатом выполнения данного примера будет что-то подобное:


display_errors = 1
register_globals = 0
post_max_size = 8M
post_max_size+1 = 9
post_max_size in bytes = 8388608

Примечания

Замечание: Возвращаемые boolean-значения

Boolean-значение ini-настройки off будет возвращено в виде пустой строки или строки "0", в то время как значению on будет соответствовать строка "1". Функция также может возвращать буквенные значения INI настройки.

Замечание: Возвращаемые значения количества памяти

Многие ini настройки, значения которых измеряются количеством памяти, такие как upload_max_filesize, записаны в php.ini в сокращенном виде. ini_get() вернет именно то, что записано в файле php.ini, а НЕ integer эквивалент этой величины. Попытка использования полученной величины в арифметических операциях не даст желаемого результата. В приведенном выше примере продемонстрировано, как можно перевести сокращенную запись в число байт.

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

  • get_cfg_var() - Извлекает значение настройки конфигурации PHP
  • ini_get_all() - Получение всех настроек конфигурации
  • ini_restore() - Восстанавливает значение настройки конфигурации
  • ini_set() - Установка значения настройки конфигурации

Коментарии

Автор:
It might be useful for included scripts that include other files to extend the 'include_path' variable:

<?php ini_set('include_path',ini_get('include_path').':../includes:');  ?>

Sometimes, it may also be useful to store the current 'include_path' in a variable, overwrite it, include, and then restore the old 'include_path'.
2004-08-16 14:59:05
http://php5.kiev.ua/manual/ru/function.ini-get.html
You can set custom entries in the ini file to provide globals such as database details.
However these must be retrieved with get_cfg_var, ini_get won't work.
2005-06-21 22:01:37
http://php5.kiev.ua/manual/ru/function.ini-get.html
Concerning the value retourned, it depends on how you set it.
I had the problem with horde-3 which test the safe_mode value.
THan :
- if you set the value with php_admin_value safe_mode Off (or On) ini_get returns the string
- if you set the value with php_admin_flag safe_mode Off (or On) ini_get returns the boolean.
2005-11-21 08:24:55
http://php5.kiev.ua/manual/ru/function.ini-get.html
Автор:
The above example function called return_bytes() assumes that ini_get('upload_max_filesize') delivers only one letter at the end. As I've seen 'Mb' and things like that, I'd suggest to change the $last = ... part into $last = strtolower(substr($val,strlen($val/1),1)).
I'd call it $unit then.
2008-07-29 17:25:11
http://php5.kiev.ua/manual/ru/function.ini-get.html
Here is how to accurately test for boolean php.ini values:

<?php

function ini_get_bool($a)
{
   
$b ini_get($a);

    switch (
strtolower($b))
    {
    case 
'on':
    case 
'yes':
    case 
'true':
        return 
'assert.active' !== $a;

    case 
'stdout':
    case 
'stderr':
        return 
'display_errors' === $a;

    default:
        return (bool) (int) 
$b;
    }
}

?>
2009-08-19 13:51:14
http://php5.kiev.ua/manual/ru/function.ini-get.html
another version of return_bytes which returns faster and does not use multiple multiplications (sorry:). even if it is resolved at compile time it is not a good practice;
no local variables are allocated;
the trim() is omitted (php already trimmed values when reading php.ini file);
strtolower() is replaced by second case which wins us one more function call for the price of doubling the number of cases to process (may slower the worst-case scenario when ariving to default: takes six comparisons instead of three comparisons and a function call);
cases are ordered by most frequent goes first (uppercase M-values being the default sizes);
specs say we must handle integer sizes so float values are converted to integers and 0.8G becomes 0;
'Gb', 'Mb', 'Kb' shorthand byte options are not implemented since are not in specs, see
faq.using#faq.using.shorthandbytes

<?php
function return_bytes ($size_str)
{
    switch (
substr ($size_str, -1))
    {
        case 
'M': case 'm': return (int)$size_str 1048576;
        case 
'K': case 'k': return (int)$size_str 1024;
        case 
'G': case 'g': return (int)$size_str 1073741824;
        default: return 
$size_str;
    }
}
?>
2010-03-26 12:08:06
http://php5.kiev.ua/manual/ru/function.ini-get.html
Автор:
This version of return_bytes takes care of the MB, GB, KB cases along with the M,G,K ones.
Hope this is helpful!

<?php
   
public static function return_bytes ($val)
    {
        if(empty(
$val))return 0;

       
$val trim($val);

       
preg_match('#([0-9]+)[\s]*([a-z]+)#i'$val$matches);

       
$last '';
        if(isset(
$matches[2])){
           
$last $matches[2];
        }

        if(isset(
$matches[1])){
           
$val = (int) $matches[1];
        }

        switch (
strtolower($last))
        {
            case 
'g':
            case 
'gb':
               
$val *= 1024;
            case 
'm':
            case 
'mb':
               
$val *= 1024;
            case 
'k':
            case 
'kb':
               
$val *= 1024;
        }

        return (int) 
$val;
    }
?>
2011-11-15 10:27:52
http://php5.kiev.ua/manual/ru/function.ini-get.html
Автор:
Yet another implementation of return_bytes:

<?php
function return_bytes($val)
{
   
assert('1 === preg_match("/^\d+([kmg])?$/i", $val)');
    static 
$map = array ('k' => 1024'm' => 1048576'g' => 1073741824);
    return (int)
$val * @($map[strtolower(substr($val, -1))] ?: 1);
}
?>

If you're using PHP >= 7, you might replace ?: with ?? to avoid the use of the @ silencer.
2015-09-02 22:37:00
http://php5.kiev.ua/manual/ru/function.ini-get.html
In a similar vein, converting flags to booleans proper:

<?php
function return_boolean($val)
{
    static 
$map = array ('on' => true'true' => true'off' => false'false' => false);
    return @(
$map[strtolower($val)] ?: (bool)$val);
}
?>

If you're using PHP >= 7, consider replacing ?: with ?? and removing the @ silencer.
2015-09-02 22:52:28
http://php5.kiev.ua/manual/ru/function.ini-get.html
Автор:
Be aware that max_execution_time can be altered by XDebug.

While debugging a script locally that made use of <?php ini_get('max_execution_time'); ?> it returned 0 when XDebug remote debugging was enabled and the IDE was listening to it.

It makes sense, since debugging manually takes time so we don't want the script to time out ; but in that particular case, it made it look to the script like max_execution_time was 0, so calculations were wrong.

You can see in phpinfo() that local value is 0 in that case, but master value is the correct one you set in your php.ini.
2017-06-05 11:53:15
http://php5.kiev.ua/manual/ru/function.ini-get.html
Автор:
Here is another way to get the result in bytes using PHP8

<?php

   
/**
     * @param string $size
     * @return int
     * @author DevsrealmGuy
     */
   
public function getBytes(string $size): int
   
{
       
$size trim($size);

       
#
        # Separate the value from the metric(i.e MB, GB, KB)
        #
       
preg_match('/([0-9]+)[\s]*([a-zA-Z]+)/'$size$matches);

       
$value = (isset($matches[1])) ? $matches[1] : 0;
       
$metric = (isset($matches[2])) ? strtolower($matches[2]) : 'b';

       
#
        # Result of $value multiplied by the matched case
        # Note: (1024 ** 2) is same as (1024 * 1024) or pow(1024, 2)
        #
       
$value *= match ($metric) {
           
'k''kb' => 1024,
           
'm''mb' => (1024 ** 2),
           
'g''gb' => (1024 ** 3),
           
't''tb' =>  (1024 ** 4),
            default => 
0
       
};

        return (int)
$value;
    }

       
#
        # TEST: This default to 0 if it doesn't conform with the match standard
        #
       
echo getBytes('2GB') . "</br>";
       
# OUTPUT: 2147483648
       
echo getBytes('4tb') . "</br>";
       
# OUTPUT: 4398046511104
       
echo getBytes('5345etrgrfd') . "</br>";
       
# OUTPUT: 0
       
echo getBytes('357568336586') . "</br>";
       
# OUTPUT: 0
?>
2021-08-11 05:40:46
http://php5.kiev.ua/manual/ru/function.ini-get.html
Here is a version combining a few of the examples here that does *not* require php8 nor does it generate a warning

/**
* gets the value in bytes converted from a human readable string like 10G'

* @param mixed $val the human readable/shorthand version of the value
* @return int the value converted to bytes
*/
function return_bytes($val) {
    $val = trim($val);
    preg_match('/([0-9]+)[\s]*([a-zA-Z]+)/', $val, $matches);
    $value = (isset($matches[1])) ? intval($matches[1]) : 0;
    $metric = (isset($matches[2])) ? strtolower($matches[2]) : 'b';
    switch ($metric) {
        case 'tb':
        case 't':
            $value *= 1024;
        case 'gb':
        case 'g':
            $value *= 1024;
        case 'mb':
        case 'm':
            $value *= 1024;
        case 'kb':
        case 'k':
            $value *= 1024;
    }
    return $value;
}
2022-01-16 12:44:22
http://php5.kiev.ua/manual/ru/function.ini-get.html

    Поддержать сайт на родительском проекте КГБ