phpday 2027 - Call for Papers

parse_ini_string

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

parse_ini_string — Effettua il parsing di una stringa di configurazione

Descrizione

function parse_ini_string(string $ini_string, bool $process_sections = false, int $scanner_mode = INI_SCANNER_NORMAL): array|false

parse_ini_string() restituisce le impostazioni contenute nella stringa ini_string in un array associativo.

La struttura della stringa ini è la stessa del php.ini.

Avviso

Questa funzione non deve essere usata con input non attendibili, a meno che scanner_mode non sia INI_SCANNER_RAW, poiché l'output analizzato potrebbe contenere i valori di costanti sensibili, come le costanti che contengono la password di un database.

Elenco dei parametri

ini_string

Il contenuto del file ini da analizzare.

process_sections

Impostando il parametro process_sections a true, si ottiene un array multidimensionale, con i nomi delle sezioni e le impostazioni incluse. Il valore predefinito di process_sections è false

scanner_mode

Può essere INI_SCANNER_NORMAL (predefinito) oppure INI_SCANNER_RAW. Se viene fornito INI_SCANNER_RAW, i valori delle opzioni non verranno analizzati.

A partire da PHP 5.6.1 può anche essere specificato come INI_SCANNER_TYPED. In questa modalità i tipi boolean, null e integer vengono preservati quando possibile. I valori stringa "true", "on" e "yes" vengono convertiti in true. "false", "off", "no" e "none" sono considerati false. "null" viene convertito in null in modalità tipizzata. Inoltre, tutte le stringhe numeriche vengono convertite nel tipo integer, se possibile.

Valori restituiti

Le impostazioni vengono restituite come array associativo in caso di successo e false in caso di fallimento.

Note

Nota:

Esistono parole riservate che non devono essere usate come chiavi nei file ini. Tra queste: null, yes, no, true, false, on, off, none. I valori null, off, no e false producono "", mentre i valori on, yes e true producono "1", a meno che non venga usata la modalità INI_SCANNER_TYPED. I caratteri ?{}|&~![()^" non devono essere usati in nessuna parte della chiave e hanno un significato speciale nel valore.

Vedere anche:

User Contributed Notes 4 notes

up
24
epicmaxim at gmail dot com
13 years ago
parse_ini_string_m is analog for a parse_ini_string function.

had to code this function due to the lack of a php 5.3 on some hosting.

parse_ini_string_m:
- ignores commented lines that start with ";" or "#"
- ignores broken lines that do not have "="
- supports array values and array value keys

<?php
function parse_ini_string_m($str) {
    
    if(empty($str)) return false;

    $lines = explode("\n", $str);
    $ret = Array();
    $inside_section = false;

    foreach($lines as $line) {
        
        $line = trim($line);

        if(!$line || $line[0] == "#" || $line[0] == ";") continue;
        
        if($line[0] == "[" &amp;&amp; $endIdx = strpos($line, "]")){
            $inside_section = substr($line, 1, $endIdx-1);
            continue;
        }

        if(!strpos($line, '=')) continue;

        $tmp = explode("=", $line, 2);

        if($inside_section) {
            
            $key = rtrim($tmp[0]);
            $value = ltrim($tmp[1]);

            if(preg_match("/^\".*\"$/", $value) || preg_match("/^'.*'$/", $value)) {
                $value = mb_substr($value, 1, mb_strlen($value) - 2);
            }

            $t = preg_match("^\[(.*?)\]^", $key, $matches);
            if(!empty($matches) &amp;&amp; isset($matches[0])) {

                $arr_name = preg_replace('#\[(.*?)\]#is', '', $key);

                if(!isset($ret[$inside_section][$arr_name]) || !is_array($ret[$inside_section][$arr_name])) {
                    $ret[$inside_section][$arr_name] = array();
                }

                if(isset($matches[1]) &amp;&amp; !empty($matches[1])) {
                    $ret[$inside_section][$arr_name][$matches[1]] = $value;
                } else {
                    $ret[$inside_section][$arr_name][] = $value;
                }

            } else {
                $ret[$inside_section][trim($tmp[0])] = $value;
            }            

        } else {
            
            $ret[trim($tmp[0])] = ltrim($tmp[1]);

        }
    }
    return $ret;
}
?>

example usage:

<?php
$ini = '

    [simple]
    val_one = "some value"
    val_two = 567

    [array]
    val_arr[] = "arr_elem_one"
    val_arr[] = "arr_elem_two"
    val_arr[] = "arr_elem_three"

    [array_keys]
    val_arr_two[6] = "key_6"
    val_arr_two[some_key] = "some_key_value"

';

$arr = parse_ini_string_m($ini);
?>

variable $arr output:

Array
(
    [simple] => Array
    (
        [val_one] => some value
        [val_two] => 567
    )

    [array] => Array
    (
        [val_arr] => Array
        (
            [0] => arr_elem_one
            [1] => arr_elem_two
            [2] => arr_elem_three
        )
    )

    [array_keys] => Array
    (
        [val_arr_two] => Array
        (
            [6] => key_6
            [some_key] => some_key_value
        )

    )

)
up
3
Peter Baylies
13 years ago
Replacement for php_ini_string() for PHP pre 5.3 - uses php_ini_file() and streams

<?php
if ( !function_exists( 'parse_ini_string' ) ) {
    function parse_ini_string( $string, $process_sections ) {
        if ( !class_exists( 'parse_ini_filter' ) ) {
            /* Define our filter class */
            class parse_ini_filter extends php_user_filter {
                static $buf = '';
                function filter( $in, $out, &$consumed, $closing ) {
                    $bucket = stream_bucket_new( fopen('php://memory', 'wb'), self::$buf );
                    stream_bucket_append( $out, $bucket );
                    return PSFS_PASS_ON;
                }
            }
            /* Register our filter with PHP */
            stream_filter_register("parse_ini", "parse_ini_filter")
            or return false;
        }
        parse_ini_filter::$buf = $string;
        return parse_ini_file( "php://filter/read=parse_ini/resource=php://memory", $process_sections );
    }
}
?>
up
2
msegit post pl
8 years ago
With function parse_ini_stringM() below you can:
- fix unvalued fields ('key' (invalid) ==> 'key=' (OK) )
- fix unquotted values with equal sign '=' ('key=value_part1=value_part2' ==> 'key="value_part1=value_part2"')
- fix (solve) multidimensional arrays (makes 'key[key1][key2]=value' valid)

function parse_ini_stringM() on github https://gist.github.com/msegu/c43a871c5a874a1d9bff978b448a0aa4 (here is too long)

// Example:

$ini = '[a]
b
c=d
e=';

var_export(parse_ini_string($ini, TRUE)); /* array (
  'a' => 
  array (
    'c' => 'd',
    'e' => '',
  ),
)
*/

$ini .= '
f[g][2]=h
f[g][i]=j
f[g][][]=k
m=n=o';

var_export(parse_ini_string($ini, TRUE)); // false

var_export(parse_ini_stringM($ini, TRUE)); /* array (
  'a' => 
  array (
    'b' => '',
    'c' => 'd',
    'e' => '',
    'f' => 
    array (
      'g' => 
      array (
        2 => 'h',
        'i' => 'j',
        3 => 
        array (
          0 => 'k',
        ),
      ),
    ),
    'm' => 'n=o',
  ),
)
*/
up
0
Philo
2 years ago
Hi,
Up to PHP 8.3 (at least), it seems that INI_SCANNER_TYPED is ignored when trying to get values from constants.
For example :
<?php
// https://3v4l.org/qK5o8

const OK = true;
const KO = false;
const NIL = null;

$ini = <<<'INI'
a = TRUE
b = FALSE
c = null
d = 9223372036854775807
INI;
var_dump(parse_ini_string($ini, false, INI_SCANNER_NORMAL), parse_ini_string($ini, false, INI_SCANNER_TYPED));
$ini = <<<'INI'
a = OK
b = KO
c = NIL
d = PHP_INT_MAX
INI;
var_dump(parse_ini_string($ini, false, INI_SCANNER_NORMAL), parse_ini_string($ini, false, INI_SCANNER_TYPED));
?>

I thought it was worth mentioning.
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top