Jump to content

Function - get value in file and write


eevan79

Recommended Posts

I wrote function to get value of specific variable in file:

function get_lang_of($name)
{
     $lines = file("config.php");

     foreach (array_values($lines) AS $line)
     {
          list($key, $val) = explode('=', trim($line) );
          
          if (trim($key) == $name)
          {     $val = convEnt($val);
                return $val;
          }
     }
     return false;
} 

 

and call it with get_value_of('$topics_per_page');

In file config.php I have:

$topic_per_page = "10"

and with this function I get 10.

 

I need same function (method) but to write.

example:

write_value_of('$topics_per_page','5');

 

Tried but failed.

Wanted to avoid white spaces:

$topics_per_page = '10'  and  $topics_per_page      =    '10'

 

Tried something like this (not function):

$file = "config.php";
$file_contents = file_get_contents($file);

$fh = fopen($file, "w");
$file_contents = str_replace('$topics_per_page = \'10\'','$topics_per_page = \'5\'',$file_contents);
fwrite($fh, $file_contents);
fclose($fh);

Link to comment
Share on other sites

This works fine:

<?php
function write_value_of($var,$oldval,$newval) {
$contents = file_get_contents('config.php');
$contents = str_replace($var . " = '" . $oldval . "'",$var . " = '" . $newval . "'",$contents);
file_put_contents('config.php',$contents);
}
write_value_of('$topics_per_page','10','5');
?>

 

Ken

Link to comment
Share on other sites

Thanks ken.

 

Thats working. But as you see from previous function I use explode('=', trim($line) ) to eliminate empty spaces between variable and value. I already tried similiar code as you suggest, but it wont working if I have (example):

$topics_per_page    =  '5';

only will work in this case:

$topics_per_page = '5';

 

Not big deal, but still want to eliminate this.

Link to comment
Share on other sites

I'm guessing your config.php file is basically containing a bunch of variables. You could code your get_value_of function as

function get_value_of($name)
{
    include 'config.php';

    if(isset(${$name}))
        return ${$name};

     return false;
}

 

Now to get the value for $topics_per_page

$topics_per_page = get_value_of('topics_per_page');

Link to comment
Share on other sites

Yes. I wrote it in first post. Now I want to write variable.

 

part of content of config.php

$topics_per_page = '10';

$blah_blah = '5'; ...etc

 

Now want to write new value (for example in $topics_per_page). That is not a problem. Get variable...and than write another value. Problem is if I have:

$topics_per_page  =  '10';

(instead of $topics_per_page = '10'; - note white space).

 

Problem with getting value is solved (ignoring white space between =), but when I write value if I have one more empty space between variable, '=' and value it wont work. Hope now its clear.

Link to comment
Share on other sites

Try this:

<?php
function write_value_of($var,$oldval,$newval) {
$contents = file('config.php');
$tmp = array();
foreach ($contents as $line) {
	list($k,$v) = explode('=',trim($line));
	$tmp[trim($k)] = trim($v);
}
if (array_key_exists($var,$tmp) && rtrim($tmp[$var],';') == $oldval) {
	$tmp[$var] = str_replace($oldval,$newval,$tmp[$var]);
}
$tmp1 = array();
foreach ($tmp as $k => $v) {
	$tmp1[] = $k . ' = ' . $v;
}
file_put_contents('config.php',implode("\n",$tmp1));
}
write_value_of('$topics_per_page',"'10'","'5'");
?>

The code works even if you have a ";" at the end of the line. A side effect is that the multiple spaces around the "=" are eliminated.

 

Ken

Link to comment
Share on other sites

Unfortunately, I noticed some failure in function  :shrug:

 

When I call function it add "=" at first 3 lines and at last 3 lines.

So it look like this:

<?php =
session_start(); =
=
$server = 'localhost';
$username = 'root';
$password = '';

 

instead of:

<?php 
session_start();

$server = 'localhost';
$username = 'root';
$password = '';
...
$topics_per_page = '10';

Link to comment
Share on other sites

Try

function write_value_of($var,$oldval,$newval)
{
$contents = file_get_contents('config.php');

$regex = '~\\'.$var.'\s+=\s+\''.$oldval.'\';~is';

$contents = preg_replace($regex, "$var = '$newval';", $contents);		

file_put_contents('config.php', $contents);
}

write_value_of('$topics_per_page',"10","5");

 

I went with the regex approach.

Link to comment
Share on other sites

if you are looking to store variables and values...there's really no reason why you need to store them as valid php syntax...if you're gonna do that, why not just include the file so the variables are simple made...(though i guess this doesn't account for writing values..)

 

Alternatively, just do the var:value with a simple delimiter so you don't need to mess around with having to strip out all that extra php syntax...

 

Alternatively, you could look into serialize and unserialize

 

 

Link to comment
Share on other sites

  • 2 weeks later...

I'm late to this post, but I thought I would recomend using an array.  As with many things, arrays make it so much easier.  Your config.php would need to be only vars and be structured like this:

 

<?php
$config['username'] = 'user';
$config['password'] = 'secret';
?>

 

Then it's fairly straightforward.  Just a thought:

 

function get_value_of($var) {
include 'config.php';
return isset($config[$var]) ? $config[$var] : false;
}

function write_value_of($var, $val) {
include 'config.php';
$config[$var] = $val;

$output = '<?php' . PHP_EOL;
foreach($config as $k => $v) {
	$output .= "\$config['$k'] = '$v';". PHP_EOL;
}
$output .= '?>' . PHP_EOL;
file_put_contents('config.php', $output);
}

 

Without a check to see if the var exists, you can add vars.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.