view raw
user5740843 user5740843 - 6 months ago 43
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:

function write_php_ini($array, $file)
$res = array();
foreach($array as $key => $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);
{ $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);


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

p_ip = ""
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!


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(''));

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

php > var_dump(is_numeric('192.168'));
php > var_dump(is_numeric('192.168.10'));