如何在php中20分钟后生成相同电子邮件地址的随机代码?

时间:2014-05-17 07:04:10

标签: php

 $fetch=mysql_query("select time from code where user_email='$email'");
$db_time=mysql_fetch_array($fetch);

        $code= createRandomCode().time();
        $current_time=date('Y-m-d H:i:s');  
        echo "present time".$current_time;

        $time_string=strtotime($current_time); 
        //echo $time['time']."-".$time_string;

    $time_diff=($time_string - $db_time);
    echo $time_diff;
    //if time difference is less than 60,then its seconds
    if ($time_diff < 60) {
         $result=$time_diff . " seconds";
         echo $result;
    }
    //if time difference is greater than 60 and lesser than 60*60*60 ,then its minutes
    if (($time_diff > (60)) && ($time_diff < (60 * 60 * 60))) {
        $result=round($time_diff / (60 * 60)) . " minutes";
        echo $result;
    }

    //if time difference is greater than 60*60*60 and lesser than 60*60*60*24,then its hours
    if (($time_diff > (60 * 60 * 60)) && ($time_diff <= (60 * 60 * 60 * 24))) {
        $result=round($time_diff / (60 * 60 * 60)) . " hours";
        echo $result;
    }

    if ($time_diff > (60 * 60 * 60 * 24)) {
        $result=round($time_diff / (60 * 60 * 60 * 24)) . " days";
        echo $result;
    }

实际上,我试图为所有用户生成随机代码。但斗争是当用户输入电子邮件ID时,代码已经生成,即使他们在一秒钟后点击它,也会生成新代码。现在是我面临的问题。

我希望每个老用户只在20分钟后获得他的代码。请帮忙。

1 个答案:

答案 0 :(得分:0)

由于您希望向每个用户发送他的代码,因此最佳解决方案是使用Cron Job(计划任务)。

此任务可以每2分钟运行一次,并将代码发送给所有有效接收代码的用户。

您必须创建一个将调用PHP脚本的任务。一个例子:

*/2 * * * * /usr/bin/wget http://example.com/myscript.php >/dev/null

以下是一些关于Cron Job的文档,可以帮助您入门:

http://www.thesitewizard.com/general/set-cron-job.shtml

http://www.thegeekstuff.com/2011/07/php-cron-job/

如果您选择此解决方案,我建议您创建一个单独的表,该表仅用于存储[user_id,time_to_send_code]。

另外,不要忘记在字段上添加索引,因为它会被查询很多。