Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and write to the same file

Tags:

file

php

Im trying to read and write to/from the same file, is this possible?

Here is what I am getting negative results with:

<?php
$file = fopen("filename.csv", "r") or exit("Unable to open file!");

while (!feof($file)) {
    $line = fgets($file);
    fwrite($file,$line);
}

fclose($file);
?>
like image 688
bryan sammon Avatar asked Feb 04 '11 05:02

bryan sammon


3 Answers

You're opening the file in read-only mode. If you want to write to the file as well, do fopen("filename.csv", "r+")

like image 148
Sam Dufel Avatar answered Oct 21 '22 05:10

Sam Dufel


You'll need to open the file with more 'r+' instead of just 'r'. See the documentation for fopen: http://php.net/manual/en/function.fopen.php

like image 32
Adam Hupp Avatar answered Oct 21 '22 04:10

Adam Hupp


You opened the file in "read only" mode. See the docs.

$file = fopen("filename.csv", "r+") or exit("Unable to open file!");
like image 31
coreyward Avatar answered Oct 21 '22 05:10

coreyward