I’m a beginner at PHP, and I’m still trying to work out proper file handling techniques. I’m usually alright with trial and error, but when it comes to deleting and modifying data, I always like to be on the safe side.
I wrote the code below to delete a certain section of a file, but I’m not sure if it will work with larger files or under unforeseen conditions which require experience to code for.
I tested this just now and it did work, but I would like to run it by the more experienced programmers first:
function deletesection($start,$len){
$pos=0;
$tmpname=$this->name."tmp.tmp";
$tmpf=fopen($tmpname,"wb+");
rewind($tmpf);
$h=fopen($this->name,"rb");
rewind($h);
while(!feof($h)){
$this->xseek($h,$pos);
$endpos = $pos+1000;
if($endpos>$start && $pos<$start+$len){
$readlen=$start-$pos;
$nextpos=$start+$len;
}
else{
$readlen=1000;
$nextpos=$pos+1000;
}
fwrite($tmpf,fread($h,$readlen));
$pos=$nextpos;
}
fclose($h);
unlink($this->name);
rename($tmpname,$this->name);
}
This is inside a class where the property “name” is the file path.
I’m writing the file 1000 bytes at a time because I was getting errors about the maximum amount of memory being exceeded when testing with files over 30mb.
I had a quick look at your code – seems a bit complicated, also copying the entire file will be less efficient if the section to delete is small in relation to the total filesize…
I believe it would also be possible to do this modifying the file in place (i.e. not using a second file) using a single file handle – but the code would get a bit messy and would require lots of seeks (then an ftruncate).
NB using files for managing data with PHP (and most other languages in a multi-user context) is not a good idea.