Reputation: 11
Is it possible for me to read from / and write to the same file? If so, could you explain me how to do that
Upvotes: 1
Views: 115
Reputation: 151
In PHP 5 file_put_contents
is the easiest way:
<?php
$file = 'people.txt';
$current = file_get_contents($file); // Open the file to get existing content
$current .= "John Smith\n"; // Append a new person to the file
file_put_contents($file, $current); // Write the contents back to the file
?>
Upvotes: 0
Reputation: 15
Here is some documentation. You can see there all the parameters you can use in these functions.
Upvotes: -2
Reputation: 82088
$file = "./test.txt";
// open file at the beginning.
$fh = fopen($file, 'r+');
//read the first line of the file. (advances pointer to the second line).
$contents = fread($fh);
// modify contents.
$new_contents = str_replace("hello world", "hello", $contents);
// make sure you're back at the 0 index.
fseek( $file, 0 );
// write
fwrite($fh, $new_contents);
// close.
fclose($fh);
// done!
Upvotes: 6