0

i have a Simple Chat script of php it has no database it work fine. but it create and store all chats in a file msg.html i want to delete these chats after some time. How to delete these chats after some time about 30min.

The Php Code is here below

<?php 
    if (isset($_GET['msg'])){
        if (file_exists('msg.html')) {
           $f = fopen('msg.html',"a+");
        } else {
           $f = fopen('msg.html',"w+");
        }
      $nick = isset($_GET['nick']) ? $_GET['nick'] : "Hidden";
      $msg  = isset($_GET['msg']) ? htmlspecialchars($_GET['msg']) : ".";
      $line = "<p><span class=\"name\">$nick: </span><span class=\"txt\">$msg</span></p>";
        fwrite($f,$line."\r\n");
        fclose($f);

        echo $line;

    } else if (isset($_GET['all'])) {
       $flag = file('msg.html');
       $content = "";
       foreach ($flag as $value) {
        $content .= $value;
       }
       echo $content;

    }
?>

Please Help me...

IamRobin
  • 1
  • 1

1 Answers1

2

The best solution is to use a cron. You can execute a cleanup PHP script every X minutes, like so:

0,30 * * * * /path/to/php /path/to/cleanup_script.php

If you want to empty the file, that's easy - you can just use file_put_contents($file, '');

If you want to delete specific messages you'll need to add a timestamp to the start of each line (You can remove it when you output the chat) and parse it in your cleanup script.

Note

You can obtain the path to php by running which php on your command line.

Martin
  • 6,632
  • 4
  • 25
  • 28
  • I gave you the code for the cron, (30 is minutes by the way.. I also linked the documentation), to edit your list of cron jobs type `crontab -e` in your terminal. This is assuming you're running a *nix based OS - if you're on Windows (god forbid), you can use `scheduled events`. – Martin Jul 15 '12 at 23:05
  • dear sir i am not a php programer please explain in the uper code wher i add your code and which name *.php file i make and what i put in this file and the output of the chat in *.html file and this script contain only three files (index.php,msg.html and message.php) all in one root directory eg: example.com/chat/ – IamRobin Jul 15 '12 at 23:13
  • If you put the `0,30 * * * * /path/to/php /path/to/cleanup_script.php` line into your `crontab -e` (Be sure to update your paths, I can't give you them as every server is different). Then in your `cleanup_script.php` you will need to put the PHP for emptying the .html file using one of the two options I mentioned above. – Martin Jul 15 '12 at 23:16