Reputation: 3
I want to change the old values of a text file with a new values (delete the old content and replace it), when I use the code below it shows me an error page , don't really know how to fix this , even used the different types of file opening methods (w , r+ , a ...) and didn't work !
$i=$_POST['id'];
$fp = fopen ("/test/member_dl.txt", "r+");
$ch = fgets ($fp);
$t=explode('||',$ch);
$t[$i-1]='';
$ch2=implode('||',$t);
fwrite($fp,$ch2);
fclose ($fp);
Upvotes: 0
Views: 3660
Reputation: 164
Whilst it's open as $fp = fopen ("/test/member_dl.txt", "r+");
You will not be able to fwrite($fp,$ch2);
Opening it with 'w+' should enable read and writing.
Try this:
$i=$_POST['id'];
$fp = fopen("/test/member_dl.txt", "w+");
$ch = fread($fp, filesize($fp));
$t=explode('||',$ch);
$t[$i-1]='';
$ch2=implode('||',$t);
fwrite($fp,$ch2);
fclose ($fp);
EDIT:
Tested this, this works
$ch = file_get_contents("test.txt");
$t=explode('||',$ch);
$t[$i-1]='';
$ch2=implode('||',$t);
file_put_contents("test.txt","hello");
Upvotes: 0
Reputation: 33502
As you want to completely replace the contents, why not just delte it, and re-create it?
unlink ("/test/member_dl.txt");
$fp = fopen ("/test/member_dl.txt", "r+");
// Continue with your code.
// Not sure I follow what you are doing with it
Edit: I am not sure I understand what that part of your code is doing to be honest.
The unlink()
command deletes the file. From there you can start over and write the file out as you need it?
Upvotes: 1