开发者

Using fwrite() to set a variable in a file

I have two php files: one is called key.php and the other is the function that validates the key. I want to regularly write to the key.php file and update the开发者_StackOverflow中文版 key from the validator.php file.

I have this code:

 $fp = fopen('key.php', 'w');
 $fwrite = fwrite($fp, '$key = "$newkey"');

What I'm trying to do is set the $key variable in the file key.php to the value of $new key which is something like $newkey = 'agfdnafjafl4'; in validator.php.

How can I get this to work (use fwrite to set a pre-existing variable in another file aka overwrite it)?


Try this:

$fp = fopen('key.php', 'w');
fwrite($fp, '$key = "' . $newkey . '"');
fclose($fp);

This will "overwrite" the variable in a literal sense. However, it won't modify the one you're using in your script as it runs, you'll need to set it ($key = somevalue).

More to the point, you really should be using a database or a seperate flat text file for this. Modifying php code like this is just plain ugly.


for_example, you have YOUR_File.php, and there is written $any_varriable='hi Mikl';

to change that variable to "hi Nicolas", use like the following code:

<?php
$filee='YOUR_File.php'; 
        /*read ->*/ $temmp = fopen($filee, "r");   $contennts=fread($temp,filesize($filee)); fclose($temmp);

// here goes your update
$contennts = preg_replace('/\$any_varriable=\"(.*?)\";/', '$any_varriable="hi Jack";', $contennts);
        /*write->*/ $temp =fopen($filee, "w");    fwrite($temp, $contennts);    fclose($temp);
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜