user5740843 user5740843 - 1 month ago 9
PHP Question

PHP Write to .ini file exception

Everyone, hello!

I'm currently trying to write to an .ini file from PHP, and I'm using Teoman Soygul's answer and code from here: http://stackoverflow.com/a/5695202

<?php
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}

function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime(TRUE);
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));

//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}

}
?>


This works out great, although, when I save the data to it part of it shows up strange in my .ini:

[Server]
p_ip = "192.168.10.100"
p_port = 80


It seems that when I have .'s in the variable, it seems to put quotation marks. I'm not sure why.

If anyone could point me into the right direction, that would really be appreciated. Thank you!

Answer

You get quotes because you told PHP to put them there:

    else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
                                   ^^^^

IP addresses aren't "numeric" - they're strings:

php > var_dump(is_numeric('192.168.10.100'));
bool(false)

multi-"dot" strings aren't numbers. Only one single . is permitted:

php > var_dump(is_numeric('192.168'));
bool(true)
php > var_dump(is_numeric('192.168.10'));
bool(false)
Comments