I am currently using this code which works fine
$messageFile="{$username}/new_messages.txt";
if( is_file($messageFile)){
$results=@file_get_contents($messageFile);
if(!empty($results) && unlink( $messageFile ) ){
//manipulate
}
}
I'm building a chat application in which messages are meant to be deleted upon delivery. $messageFile
is only being accessed by two sets of people- The receiver and his/her friends.
Friends messages are appended to the file and the receiver checks for new messages ( through checking if is_file()
or comparing last modified time--polling 3s) and once the messages are delivered, the file is deleted then keeps checking if the $messageFile
has been created or modified again and has messages.
My question is based on your experience, has there been any side effect in creating, deleting frequently same file?
I don't consider using db since the flat file is only been accessed by a user and his/her friends and the messages are not meant to be stored forever and also querying and updating/deleting messages in mysqli database frequently (esp when there are lots of users) can be much work i guess.
My Answer:
"message.txt";
// Create the file
$file = fopen($messageFile, "w");
fclose($file);
// Delete the file
unlink($messageFile);
echo "File created and deleted successfully.";
This code will create a file named "message.txt" and then delete it. There should not be any side effects to creating and deleting the same file in this manner. However, it is always a good practice to handle file operations carefully to avoid any unexpected issues.
Rate this post
4 of 5 based on 5821 votesComments