Difference between r+ and w+ in fopen()

Both r+ and w+ can read and write to a file. However, r+ doesn’t delete the content of the file and doesn’t create a new file if such file doesn’t exist, whereas w+ deletes the content of the file and creates it if it doesn’t exist.

Overwrite Line in File with PHP

If the file is really big (log files or something like this) and you are willing to sacrifice speed for memory consumption you could open two files and essentially do the trick Jeremy Ruten proposed by using files instead of system memory. $source=”in.txt”; $target=”out.txt”; // copy operation $sh=fopen($source, ‘r’); $th=fopen($target, ‘w’); while (!feof($sh)) { $line=fgets($sh); … Read more

How to read only 5 last line of the text file in PHP?

For a large file, reading all the lines into an array with file() is a bit wasteful. Here’s how you could read the file and maintain a buffer of the last 5 lines: $lines=array(); $fp = fopen(“file.txt”, “r”); while(!feof($fp)) { $line = fgets($fp, 4096); array_push($lines, $line); if (count($lines)>5) array_shift($lines); } fclose($fp); You could optimize this … Read more

PHP check if file contains a string

Much simpler: <?php if( strpos(file_get_contents(“./uuids.txt”),$_GET[‘id’]) !== false) { // do stuff } ?> In response to comments on memory usage: <?php if( exec(‘grep ‘.escapeshellarg($_GET[‘id’]).’ ./uuids.txt’)) { // do stuff } ?>

fopen deprecated warning

It looks like Microsoft has deprecated lots of calls which use buffers to improve code security. However, the solutions they’re providing aren’t portable. Anyway, if you aren’t interested in using the secure version of their calls (like fopen_s), you need to place a definition of _CRT_SECURE_NO_DEPRECATE before your included header files. For example: #define _CRT_SECURE_NO_DEPRECATE … Read more