简体   繁体   中英

php mysql - trying to add time limit to how offten user can post

I'm new to using php, but here my problem:

I'm working on a website where users can post things to the server. I'm trying to add a 5 minute limit to how often a user can post. Every time a user posts it updates a field on their row in the database with CURRENT_TIMESTAMP()

What I would like to do is something that checks how long ago they posted and if it is less than 5 minutes ago it disallows them to post yet.

I figure it would look something like this:

<?php

$query = "SELECT * FROM Users_table WHERE Username = '$username'";
$result = mysql_query($query);

if (($result['last_post']-now())<=5minutes) {

echo "Please wait 5 minutes before you can post again.";

} else {

code to let user post

}

?>

The problem i'm having is i don't know how time works very well and don't know how long 5 minutes would look like.

Any help is much appreciated.

Instead of using a database, you can use sessions too:

session_start();
if (isset($_SESSION['last_post']) && $_SESSION['last_post'] + 300 >= time()) {
    echo "sorry, please wait for 5 minutes before next post";
} else {
    // do your post here
    $_SESSION['last_post'] = time();
}

It will add a session variable that keeps track of the last post within this session; every time you post the value gets updated.

When the last time + 5 minutes is in the future, then it hasn't been 5 minutes yet since the last post.

You can check that directly on SQL, then use PHP just to verify if the query returned anything:

$query = "
    SELECT * FROM Users_table 
    WHERE Username = '$username' 
    AND DATE_ADD(last_post, INTERVAL 5 MINUTE) > NOW()
";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
    echo "Please wait 5 minutes before you can post again.";
} else {
    //code to let user post
}

SELECT * FROM Users_table WHERE Username = ? AND DATE_ADD(last_post, INTERVAL 5 MINUTE) > NOW()

然后检查结果是否为空。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM