I wanna to open a php file and replace the content I tried this code but it didn't work,
$fh = fopen("c/".$file."/underbaba.php", 'w');
$file = file_get_contents($fh);
$file = str_replace('error":4,', 'error":0,', $file);
This system open my file and delete all the code in file underbaba.php, I need a code because I have a lot of files to edit I used scandir
and foreach
for reading files in all directory c
with name underbaba.php
, Thanks.
You need to open your file in append mode
use mode a+
or r+
for this
Please check the below link for help https://www.w3schools.com/php/php_file_open.asp
If that is all you are doing, then yes you are emptying your file. According to the manual:
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
Are you writing the string you have modified back to the file somewhere as well?
Your problem:
If you use file_get_contents
you don't pass a file handle but the path to the file as a string.
While
$fh = fopen("c/".$file."/underbaba.php", 'w');
without writing to the file with fwrite
will result in simply erasing the file. Also the file should be fclose
d before the script ends.
The solution:
Simply Use file_get_contents
to read the file then file_put_contents
to write.
$contents = file_get_contents( $full_path_to_file );
$contents = str_replace( 'error":4,', 'error":0,', $contents );
file_put_contents( $full_path_to_file, $contents );
You get a very little overhead versus using a sequence of fopen
, fread
, fseek
, fwrite
, fclose
because the file is opened and closed twice but I don't think this is an issue.
Worth mentioning that file_get_contents
will read all the whole file at once and store it into memory so this solution is feasable only with files with a reasonable size.
You may add error handling easily:
$contents = file_get_contents( $full_path_to_file );
if( $contents === false )
{
// an error occurred reading
}
$contents = str_replace( 'error":4,', 'error":0,', $contents );
$bytes_written = file_put_contents( $full_path_to_file, $contents );
if( $bytes_written !== strlen( $contents ) )
{
// an error occurred writing
}
As you're operating on a set of files setup a for
/ foreach
loop setting $full_path_to_file
properly at each iteration.
For your reference: