I have a file data.php
looks like the below:
$first_data = 0;
$second_data = 0;
$third_data = 0;
I have three HTML checkbox on frontend and I would like to store the value into data.php
.
( The value is 1
if it’s checked )
In process.php
, I use $_POST['data_value']
and store the value into the variables which looks like the below:
$process_first_data = isset ( $_POST['first_checkbox'] ) ? 1 : 0;
$process_second_data = isset ( $_POST['second_checkbox'] ) ? 1 : 0;
$process_third_data = isset ( $_POST['third_checkbox'] ) ? 1 : 0;
And I use this method with preg_replace
to replace the value in data.php
from process.php
which looks like the below:
$find_first_data = '/$first_data = d;/';
$find_second_data = '/$second_data = d;/';
$find_third_data = '/$third_data = d;/';
$replace_first_data = '$first_data = ' . $process_first_data . ';';
$replace_second_data = '$second_data = ' . $process_second_data . ';';
$replace_third_data = '$third_data = ' . $process_third_data . ';';
$dir = 'path/to/file';
$file_content = file_get_contents ( $dir );
file_put_contents ( $dir, preg_replace ( $find_first_data, $replace_first_data, $file_content ) );
file_put_contents ( $dir, preg_replace ( $find_second_data, $replace_second_data, $file_content ) );
file_put_contents ( $dir, preg_replace ( $find_third_data, $replace_third_data, $file_content ) );
But now the problem is only the last file_put_contents
is working. For example, now only the third one is working. And if I remove the third one, there are two left, then the second one is working only. And if I remove the second and the third one, there is one left, then the first one is working only.
There is no error, sorry for the long story because I want to make it in detail. May I know why only the last file_put_contents
is working in this case?
3
Answers
It looks like all three file_put_contents() are working, but you are overwriting the same file "$dir" three times.
file_put_contents($file, $contents, $flags);
An example of $flags is FILE_APPEND which will append to the end of the file instead of overwriting.
Use
FILE_APPEND
optione.g.
One way to understand code better is to introduce some meaningful names for intermediate variables. So we could change this:
To this:
Now, notice that the definitions for the three new variables don’t reference each other, or re-read the file, they just look at
$original_file_content
. They could actually happen in any order, before the set offile_put_contents
calls:Since
file_put_contents
over-writes the whole file by default, the content of the file will always be$third_new_content
.What you probably intended is for each of the replacements to happen on the result of the previous one, then write the final result to the file at the end: