phpfopen

How to get fopen with "rw" to work in php?


I have looked at several excellent questions/answers related to this (such as this and this), and none seem to apply. The latter link says r and rw are the same (at least rw+) and fopen ignores the w. Here's what I am doing:

$curl_log = fopen(__DIR__ . "/curl.txt", 'rw'); // open file for read and write
// Do various curly tings here...
rewind($curl_log);
$output= fread($curl_log, 2048);
echo "<pre>". print_r($output, 1). "</pre>";
fclose($curl_log);

but I get the error:

[Mon Apr 15 17:07:05.410468 2024] [php7:warn] [pid 2485068] [client x.x.x.x:56086] PHP Warning: fopen(/var/www/example.com/example/curl.txt): failed to open stream: No such file or directory in /var/www/example.com/example/pn.php on line 147, referer: https://example.com/...

So how do I get it to read and write?


Solution

  • Actually rw is not a valid mode, take a look at what man fopen says:

    The argument mode points to a string beginning with one of the following sequences (possibly followed by additional characters, as described below):

    To open a file for reading and writing, you need to use any mode with a + sign (r+ w+ a+ x+ c+) as appropriate.

    For example, regarding your error, it is because the r (or r+) mode requires that the file must exist. If you want to automatically create a non-existent file, you need to use the w+ mode.