HamletHub
HamletHub

Reputation: 551

Cannot read a file using parse_ini_file

I can't load the data from an ini file using parse_ini_file. It is able to read the file using file_get_contents, but fails when using parse_ini_file. The ini file is:

[names]
me = Robert
you = Peter

[urls]
first = "http://www.example.com"
second = "https://www.w3schools.com"

The code is:

echo file_exists($iniFile), "<br>";
echo file_get_contents($iniFile), "<br>";
echo "print_r parse result---->";
print_r(parse_ini_file($iniFile));
$data = parse_ini_file($iniFile);
echo "<br>this is data-me---->", $data['me'], "<br>";
echo "this is data---->", $data, "<br>";
if(empty($data)){
    HHelper::logItA($folder . "/Errors", $folder . "_ini", $key . " file empty");
    die("\nNo data in {$key}, iniFile {$iniFile}\n");
}

and the output is:

1
[names] me = Robert you = Peter [urls] first = "http://www.example.com" second = "https://www.w3schools.com"
print_r parse result---->
this is data-me---->
this is data---->
No data in EventImport/test.ini, iniFile s3://configs.hamlethub.com/EventImport/test.ini

I can't figure out why this will not read into the array. Any help would be appreciated.

Upvotes: 0

Views: 2506

Answers (1)

stratedge
stratedge

Reputation: 2820

Disregard my comment above, your ini file is syntactically fine and parses without issue on my machine.

If the file is located on S3, as implied by the value of the $iniFile variable in your error output, then the function parse_ini_file may not be what you need. A comment on the function's documentation notes the function does not seem to work for remote files: http://php.net/manual/en/function.parse-ini-file.php#37293.

That said, it's still possible to achieve what you're going for, here's what I'd try:

Since you can retrieve the contents of the file with file_get_contents off of S3, you can parse the text that is returned. You can use the function parse_ini_string to do the same parsing that parse_ini_file would have done, and return the expected associative array.

$ini = file_get_contents($iniFile);
$data = parse_ini_string($ini);
print_r($data);

That should do the trick.

Here's the documentation for parse_ini_string: http://php.net/manual/en/function.parse-ini-string.php

It's worth at least noting that the idea of having a remote ini file strikes me as a security risk, depending on what the contents of the ini file are used for, so make sure you lock the permissions of this file in AWS' ecosystem down tightly. The reason the parse_ini_file function probably doesn't contact remote machines may just be for security reasons (though they may have just decided never to implement the functionality due to low demand).

Upvotes: 3

Related Questions