如何每1分钟运行一次PHP代码?

时间:2016-05-27 17:47:06

标签: php

我有这个PHP代码

$uploaded=0;
$_SESSION['numberOfUploadsInTimeFrame']=$uploaded;
if (isset($_POST['UploadMSub'])) {
    $uploaded++;
    $_SESSION['firstUploadTime'] = time();
}


function isFileUploadAllowed() {
    $isAllowed                  = true;
    $timeNow                    = time();
    $timeFrameInSeconds         = 30;
    $maxUploadsInTimeFrame      = 5;
    $firstUploadTime            = $_SESSION['firstUploadTime'] ? intval($_SESSION['firstUploadTime']) : $timeNow;
    $numberOfUploadsInTimeFrame = $_SESSION['numberOfUploadsInTimeFrame'] ? intval($_SESSION['numberOfUploadsInTimeFrame']) : 0;
    $givenTimeFrameExpired      = (($firstUploadTime + $timeFrameInSeconds) < $timeNow);
    if (!$givenTimeFrameExpired) {
        if ($numberOfUploadsInTimeFrame + 1 > $maxUploadsInTimeFrame) {
            $isAllowed = false;
        }
    }

    if ($isAllowed === true) {
        if ($givenTimeFrameExpired) {
            $_SESSION['firstUploadTime'] = $timeNow;
            $_SESSION['numberOfUploadsInTimeFrame'] = 0;
        }

        $_SESSION['numberOfUploadsInTimeFrame']++;
    }
    return $isAllowed;
}   

我怎么能这样做每60秒$ _SESSION ['numberOfUploadsInTimeFrame']将减少一个 请不要建议sleep()或Cron

1 个答案:

答案 0 :(得分:0)

您可以在60000毫秒= 1分钟的setInterval内使用jQuery's ajax method,请参阅以下示例:

setInterval(function() {
    $.ajax({
        url: 'url to your php script you want to execute',
        method: 'post',
        aysnc: false,
        data: {
            var: 'value'
        }
        success: function(response) {
            console.log(response);
        }
    });
}, 60000);