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?
CodePudding user response:
Use FILE_APPEND
option
e.g.
file_put_contents ( $dir, preg_replace ( $find_third_data, $replace_third_data, $file_content ), FILE_APPEND );
CodePudding user response:
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.