bryan sammon
bryan sammon

Reputation: 7441

Read and write to the same file

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);
?>

Upvotes: 6

Views: 9386

Answers (3)

Adam Hupp
Adam Hupp

Reputation: 1573

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

Upvotes: 6

coreyward
coreyward

Reputation: 80140

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

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

Upvotes: 5

Sam Dufel
Sam Dufel

Reputation: 17608

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

Upvotes: 12

Related Questions