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:
file_get_contents
file_put_contents