Reputation: 12538
I am trying to write data to a php file everytime the page is refreshed. The code below successfully writes to a file, however, the file contents remain the same after the first rewrite, even though the the data contained in the array that is used to write to the file is different every time the page is refreshed.
My question is: how can I rewrite or replace the contents of .php file that already exists?
I tried unlink('../html/freesample2.php');
to solve this problem, by deleting the 'written' file and then recreating it, however it did not help.
I appreciate any advice.
//Create variable for file I want to write to
//second parameter 'a' stands for APPEND
$f = fopen('../html/freesample2.php', 'a') or die('fopen failed');
$php_script= '<?php $free_sample_array_new = Array(); $free_sample_array_new[] = '.$free_sample_array[0].'; $free_sample_array_new[] = '.$free_sample_array[1].'; ?>';
fwrite($f, $php_script);
fclose($f);
Upvotes: 1
Views: 10369
Reputation: 1601
If you are on windows, you must close the csv file (if opened on desktop), before writing it with 'w' mode.
Upvotes: 0
Reputation: 12834
Run this code and check if each time after refresh, freesample2.php has new value or not?
<?
$free_sample_array = array(rand());
$f = fopen('../html/freesample2.php', 'w') or die('fopen failed');
$php_script= '<?php $free_sample_array_new = Array(); $free_sample_array_new[] = '.$free_sample_array[0].'; ?>';
fwrite($f, $php_script);
fclose($f);
?>
Upvotes: 0
Reputation: 20753
If you want to open a file for writing, you can use 'w'
as the access mode for fopen()
. That will create the file if it's not there yet, or truncate it to be empty and you can write into it as if it's new.
Alternatively you can use file_put_contents to make the operation a oneliner.
side note: If you are generating php code with literal values, take a look into var_export function, that could simplify it vastly (with the second, optional parameter).
Upvotes: 6