Reputation: 2629
I would like to cut off the beginning of a large file in PHP. Use of file_get_contents()
is not possible due to memory restrictions.
What is the best way to delete the first $n
characters from a file?
If it is possible to do it without creating a second file, I would prefer that solution.
Update After the file has been modified, it will be used by other scripts.
Upvotes: 1
Views: 151
Reputation: 14153
If you don't have enough memory to buffer the entire file, you'll need to create two files (at least temporarily) regardless of your solution.
Look into fseek()
, which allows you to go to a particular byte position within a file.
// Open the file
$filename = 'somefile.dat';
$file = fopen($filename, 'r');
// Skip the first 1 KB
fseek($file, 1024);
// Your processing goes here...
// Close the file
fclose($file);
In your case, you could open the original file for reading and the temp file for writing concurrently. Seek the original file. Loop over the original file, reading a small chunk and writing it to temp. Then rename temp to have the same name as original.
Upvotes: 2