I am writing an "unfriend" script for my mini social network, basically the unfriend action needs to remove their id called: $user
from their friend list and my id called: $my_id
. I have made the scripts that add user id's to each users files but I am not sure how to delete this?
My friend_list
file:
1,2,3 // I am user 1
Their friend_list
file:
1,2,3 // They are user 3
I currently use this to add each id into the text file:
if($action === 'accept'){
mysql_query("DELETE FROM `friend_req` WHERE `from`='$user' AND `to`='$my_id'");
$fp = fopen($user_data['friend_list'], 'a');
fwrite($fp, ",".$user."");
fclose($fp);
$their_id = friend_list_from_user_id($user);
$fp = fopen($their_id, 'a');
fwrite($fp, ",".$my_id."");
fclose($fp);
}
But to remove $my_id
from their friend_list
and their $user
id from my friend_list
I'm thinking I need to use something like this but it isn't working:
if($action === 'unfriend'){
$fp = fopen($user_data['friend_list'], 'a');
unset($user);
fclose($fp);
$their_id = friend_list_from_user_id($user);
unset($my_id);
fclose($fp);
}
But that doesn't seem to work, what should I do to delete only the specified usernames from the respective file?
Oh, and also, this may/may not be of use:
$myFile = $file;
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
$friend = explode(',', $theData);
for($i=0; $i < count($friend); $i++){
if($i >= 0)
{
if($friend[$i] == $user_id) {
$their_user_id = $user_id;
}
}
To solve your issue just do something like:
//get the contents of the file
$contents = file_get_contents($user_data['friend_list']);
$contents = str_replace(",".$friend_id, "", $contents); //remove the friend's id
//open the file again and rewrite the whole thing with the new contents without that id
$fp = fopen($user_data['friend_list'], 'w+');
fwrite($fp, $contents);
fclose($fp);