How can I access a variable in a config.ini file?

0

How can I get the value of a variable found in the file config.ini in the root of my hard drive and be able to use it for a SQL query?

    
asked by Greenonline 03.07.2018 в 21:36
source

1 answer

2

You can use parse_ini_file . p>

If you pass the param% TRUE at the end you will create an associative array by sections, if you do not pass anything, you will create a unique array.

Suppose this file (put as an example in the manual), which is called ejemplo.ini :

; Este es un ejemplo de fichero de configuración
; Los comentarios empiezan con ';', como en php.ini

[primera_sección]
uno = 1
cinco = 5
animal = PÁJARO

[segunda_sección]
ruta = "/usr/local/bin"
URL = "http://www.example.com/~username"

[tercera_sección]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"

urls[svn] = "http://svn.php.net"
urls[git] = "http://git.php.net"

To read it, the code would be:

$archivo="ejemplo.ini";  //aquí se debe poner la ruta correcta del archivo si fuera necesario

$array_ini = parse_ini_file($archivo);
print_r($array_ini);

$array_ini would be an array like this:

Array
(
    [uno] => 1
    [cinco] => 5
    [animal] => Pájaro dodo
    [ruta] => /usr/local/bin
    [URL] => http://www.example.com/~username
    [phpversion] => Array
        (
            [0] => 5.0
            [1] => 5.1
            [2] => 5.2
            [3] => 5.3
        )

    [urls] => Array
        (
            [svn] => http://svn.php.net
            [git] => http://git.php.net
        )

)

To read it, it would be like reading any array. For example, if you want to get the 1 and the 5 , you would do:

$uno=$array_ini["uno"];
$cinco=$array_ini["cinco"];

Now we read it with TRUE :

$array_ini = parse_ini_file($archivo, TRUE);
print_r($array_ini);

The result would be an associative array in this case:

Array
(
    [primera_sección] => Array
        (
            [uno] => 1
            [cinco] => 5
            [animal] => Pájaro dodo
        )

    [segunda_sección] => Array
        (
            [ruta] => /usr/local/bin
            [URL] => http://www.example.com/~username
        )

    [tercera_sección] => Array
        (
            [phpversion] => Array
                (
                    [0] => 5.0
                    [1] => 5.1
                    [2] => 5.2
                    [3] => 5.3
                )

            [urls] => Array
                (
                    [svn] => http://svn.php.net
                    [git] => http://git.php.net
                )

        )

)

And to obtain results you would have to access by sections. For example:

$seccUno=$array_ini["primera_sección"]
$uno=$seccUno["uno"];
$cinco=$seccUno["cinco"];
    
answered by 03.07.2018 в 22:04