在PHP中加入限制

时间:2016-05-22 14:04:54

标签: php ajax

如何在一分钟内限制用户所做的事情? 我有这个PHP代码

 if(isset($_POST['new_post'])){
            $Text=htmlspecialchars($_POST['new_post'],ENT_QUOTES);
            $Text=trim($Text);
            if (is_uploaded_file($_FILES['Upload_f']['tmp_name'])) {
                    $fileP=$_FILES['Upload_f'];
                    $fileP_name=$fileP['name'];
                    $fileP_tmp=$fileP['tmp_name'];
                    $fileP_size=$fileP['size'];
                    $fileP_error=$fileP['error'];
                    $fileP_extension=explode('.', $fileP_name);
                    $fileP_extension=strtolower(end($fileP_extension));
                    $allowed=array('jpg','png');
                    if (in_array($fileP_extension, $allowed)){
                        if ($fileP_error===0) {
                            if ($fileP_size<=2097152){
                                $fileP_new_name=uniqid().'.'.$fileP_extension;  
                            }
                        }
                        $NotInarray=false;
                    }else{
                        $fileP_new_name="";  
                        $NotInarray=true;
                    }
                    $Fileuploaded=true;
            }else{
                $fileP_new_name="";
                $fileP=0;
                $Fileuploaded=false;
                $NotInarray=false;
            }
                $Posts=$con->query("SELECT Posts FROM user_opt WHERE Username='$NameId'");
                $row=$Posts->fetch_row();
            if (strlen($Text)>400) {
                $Res="Error occurred.Please try again";
                $PostNum=$row[0];
            }elseif(strlen($Text)==0 && $fileP==0){
                $Res="Both fields are empty";
                $PostNum=$row[0];
            }elseif($Fileuploaded===true){
                if ($NotInarray==true) {
                $Res="Only jpg and png files are allowed";
                $PostNum=$row[0];
                }elseif ($fileP_error!=0) {
                $Res="Error occurred.Please try again";
                $PostNum=$row[0];
                }else{
                    $Res="Success";
                    $PostNum=$row[0]+1;
                    $upladed++;
                }
            }else{
                    function generateRandomString($length) {
                        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        $charactersLength = strlen($characters);
                        $randomString = '';
                        for ($i = 0; $i < $length; $i++) {
                            $randomString .= $characters[rand(0, $charactersLength - 1)];
                        }
                        return $randomString;
                    }
                    $Rand=generateRandomString(100);
                    $query=$con->query("INSERT INTO uploads (Rand,Username,image,`Text`,`Date`) VALUES('$Rand','$NameId','$fileP_new_name','$Text',NOW())");
                    $querya=$con->query("UPDATE user_opt SET posts=posts+1 WHERE Username='$NameId'");
                    $PostNum=$row[0]+1;
                    $Res="Success";           
                    $upladed++;
                }
                 echo json_encode(array($Res,$PostNum,$upladed));
        }

此代码由ajax调用。如何让这段代码在一分钟内最多执行5次?我试过这样做

    $upladed=0;
     if(isset($_POST['new_post'])){
            if ($upladed<=5) {
              code
  }
}

但是每当新的ajax出现$ upladed再次变为0

1 个答案:

答案 0 :(得分:1)

您可能希望使用会话来存储$ uploaded变量的值,并在每次Ajax调用发生时检索它。您可能还希望在第一篇文章发生时存储实际分钟,以确保在该分钟内不再有帖子到达。并且你应该在另一分钟开始时使$ uploaded(将其设置为0)无效。

如果您存储第一篇文章的实际第二篇文章会更好,并为其他潜在上传文件提供60秒(达到您的限制)

修改后的代码可能如下所示:

<?php

session_start();

function generateRandomString($length) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function isFileUploadAllowed() {
    $isAllowed                  = true;
    $timeNow                    = time();
    $timeFrameInSeconds         = 60;
    $maxUploadsInTimeFrame      = 5;
    $firstUploadTime            = $_SESSION['firstUploadTime'] ? intval($_SESSION['firstUploadTime']) : $timeNow;
    $numberOfUploadsInTimeFrame = $_SESSION['numberOfUploadsInTimeFrame'] ? intval($_SESSION['numberOfUploadsInTimeFrame']) : 0;
    $givenTimeFrameExpired      = (($firstUploadTime + $timeFrameInSeconds) < $timeNow);

    // when there would be more time to allow upload
    if (!$givenTimeFrameExpired) {
        // disallowing only when the limit is reached
        if ($numberOfUploadsInTimeFrame + 1 > $maxUploadsInTimeFrame) {
            $isAllowed = false;
        }
    }

    // if there is no need to restrict this upload
    if ($isAllowed === true) {
        // if previous time frame is expired, reset 'firstUploadTime' and 'numberOfUploadsInTimeFrame'
        if ($givenTimeFrameExpired) {
            $_SESSION['firstUploadTime'] = $timeNow;
            $_SESSION['numberOfUploadsInTimeFrame'] = 0;
        }

        // increasing the number of uploaded files
        $_SESSION['numberOfUploadsInTimeFrame']++;
    }

    return $isAllowed;
}

if(isset($_POST['new_post'])){
    $Text=htmlspecialchars($_POST['new_post'],ENT_QUOTES);
    $Text=trim($Text);
    if (is_uploaded_file($_FILES['Upload_f']['tmp_name'])) {
        if (isFileUploadAllowed()) {
            $fileP=$_FILES['Upload_f'];
            $fileP_name=$fileP['name'];
            $fileP_tmp=$fileP['tmp_name'];
            $fileP_size=$fileP['size'];
            $fileP_error=$fileP['error'];
            $fileP_extension=explode('.', $fileP_name);
            $fileP_extension=strtolower(end($fileP_extension));
            $allowed=array('jpg','png');
            if (in_array($fileP_extension, $allowed)){
                if ($fileP_error===0) {
                    if ($fileP_size<=2097152){
                        $fileP_new_name=uniqid().'.'.$fileP_extension;  
                    }
                }
                $NotInarray=false;
            }else{
                $fileP_new_name="";  
                $NotInarray=true;
            }
            $Fileuploaded=true;
        }
    }else{
        $fileP_new_name="";
        $fileP=0;
        $Fileuploaded=false;
        $NotInarray=false;
    }
        $Posts=$con->query("SELECT Posts FROM user_opt WHERE Username='$NameId'");
        $row=$Posts->fetch_row();
    if (strlen($Text)>400) {
        $Res="Error occurred.Please try again";
        $PostNum=$row[0];
    }elseif(strlen($Text)==0 && $fileP==0){
        $Res="Both fields are empty";
        $PostNum=$row[0];
    }elseif($Fileuploaded===true){
        if ($NotInarray==true) {
        $Res="Only jpg and png files are allowed";
        $PostNum=$row[0];
        }elseif ($fileP_error!=0) {
        $Res="Error occurred.Please try again";
        $PostNum=$row[0];
        }else{
            $Res="Success";
            $PostNum=$row[0]+1;
            $upladed++;
        }
    }else{
            $Rand=generateRandomString(100);
            $query=$con->query("INSERT INTO uploads (Rand,Username,image,`Text`,`Date`) VALUES('$Rand','$NameId','$fileP_new_name','$Text',NOW())");
            $querya=$con->query("UPDATE user_opt SET posts=posts+1 WHERE Username='$NameId'");
            $PostNum=$row[0]+1;
            $Res="Success";           
            $upladed++;
        }
         echo json_encode(array($Res,$PostNum,$upladed));
}