user858940
user858940

Reputation: 11

PHP FILES reading and writing

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

Answers (4)

JonnyDevs
JonnyDevs

Reputation: 45

file_put_contents("write.txt",file_get_contents("read.txt"));

Upvotes: -1

Dale Hurley
Dale Hurley

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

cwallenpoole
cwallenpoole

Reputation: 82088

Yes it is.

$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

Related Questions