Solved

php if statement with date function

Posted on 2016-08-25
5
22 Views
Last Modified: 2016-08-25
Dear Experts,

I insert my web form to my database, but sometimes users insist on sending the form again and again. I know that using CAPTCHA is helping reducing this kind of stuff, but I already know who visit my web page thanks to login and session user id.

I insert the web form to my database with username, ip address and time ( 2016-08-24 18:33:36 )
so I can check if the username and time of the repeated insert is less than 5 minutes I can say that, I already received the form, do not send any form, if you do so, wait for 5 minutes.

my code like this

$sql = "SELECT * FROM mesaj where uid='$uid' order by _key desc limit 1 ";
$result = $conn->query($sql);

    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["uid"]. " - İsim: " . $row["tarih"]. " " . $row["yorum"]. "<br>";
            
      $yeni= $row["tarih"];
      $yeni2= $row["yorum"];
      $yeni3= $row["ipi"];

so my date is in $yeni variable
user id = $uid
how can I write the if statement?

if the (userid is the userid and date difference is less than 5 minutes)  than { echo "I already have your form" } else { my code to be executed }
0
Comment
Question by:Braveheartli
  • 2
  • 2
5 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41770366
You can prevent duplicate submissions with something like this design.
<?php // demo/prevent_multi_submit.php
/**
 * Prevent repeated data submissions due to browser refresh, resubmit,
 * or browser back-button.
 *
 * GET-method requests must be idempotent and nullipotent; GET must not
 * disrupt the data model.  POST (PUT) requests can change the data model,
 * but for client convenience, good design will make POST, PUT, and DELETE
 * requests modifiable or reversible.
 *
 * This function can test either $_GET or $_POST request variables.
 *
 *    if ( multi_submit() )
 *    {
 *       // handle duplicate inputs
 *    }
 *    else
 *    {
 *       // handle original inputs
 *    }
 */
error_reporting(E_ALL);


// A FUNCTION TO RETURN TRUE OR FALSE ABOUT MULTI-SUBMIT CONDITIONS
function multi_submit($type="POST")
{
    // MAKE THE FUNCTION WORK FOR EITHER GET OR POST SUBMITS
    $input_array = (strtoupper(trim($type)) == "GET") ? $_GET : $_POST;

    // GATHER THE CONTENTS OF THE SUBMITTED FIELDS AND MAKE A MESSAGE DIGEST
    $string = 'X';
    foreach ($input_array as $val)
    {
        $string .= $val;
    }
    $string = md5($string);

    // IF THE SESSION VARIABLE IS EMPTY THIS IS NOT A MULTI-SUBMIT
    if (empty($_SESSION["multi_submit"]))
    {
        $_SESSION['multi_submit'] = $string;
        return FALSE;
    }

    // IF THE SESSION DATA MATCHES THE MESSAGE DIGEST THIS IS A MULTI-SUBMIT
    if ($_SESSION['multi_submit'] == $string)
    {
        return TRUE;
    }

    // IF THE SESSION DATA DOES NOT MATCH THIS IS NOT A MULTI-SUBMIT
    else
    {
        $_SESSION['multi_submit'] = $string;
        return FALSE;
    }
}


// ALWAYS START THE PHP SESSION AT THE LOGICAL TOP OF EVERY PAGE
session_start();


// SHOW HOW TO USE THE FUNCTION
if (!empty($_POST))
{
    if (multi_submit())
    {
        echo "ALREADY GOT THAT";
    }
}


// CREATE THE FORM FOR THE DEMONSTRATION
$form = <<<FORM
<form method="post">
ENTER SOMETHING, THEN REENTER IT
<input name="mydata" />
<input type="submit" />
</form>
FORM;

echo $form;

Open in new window


If you want to determine something about the time, such as if five minutes have elapsed since an event, try something like this.
https://iconoun.com/demo/temp_braveheartli.php
<?php // demo/temp_braveheartli.php
/**
 * https://www.experts-exchange.com/questions/28965606/php-if-statement-with-date-function.html
 *
 * https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
 * https://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL-Procedural-Version.html
 * https://www.experts-exchange.com/articles/20920/Handling-Time-and-Date-in-PHP-and-MySQL-OOP-Version.html
 */
error_reporting(E_ALL);
echo '<pre>';

$alpha = date('c', strtotime('Now'));
$omega = date('c', strtotime('Now + 5 minutes'));

$test1 = date('c', strtotime('Now + 3 minutes'));
$test2 = date('c', strtotime('Now + 6 minutes'));

if ($test1 >= $alpha)
{
    if ($test1 <= $omega)
    {
        echo PHP_EOL . "$test1 IS BETWEEN $alpha AND $omega";
    }
}

if ($test2 >= $alpha)
{
    if ($test2 <= $omega)
    {
        echo PHP_EOL . "$test2 IS BETWEEN $alpha AND $omega";
    }
    else
    {
        echo PHP_EOL . "$test2 IS <i>NOT</i> BETWEEN $alpha AND $omega";
    }
}

Open in new window

Relevant articles:
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
https://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL-Procedural-Version.html
https://www.experts-exchange.com/articles/20920/Handling-Time-and-Date-in-PHP-and-MySQL-OOP-Version.html
0
 
LVL 52

Expert Comment

by:Julian Hansen
ID: 41770388
Why not just put a random string in a hidden field and check for that
<form method="post" ...>
   <input type="hidden" name="formid" value="f7f5ce59-6ad1-11e6-aaf9-00155df9b130" />
...
</form>

Open in new window


<?php
error_reporting(E_ALL);
session_start();
if ($_POST) {
   $saved_form_id = isset($_SESSION['form_id']) ? $_SESSION['form_id'] : false;
   $current_form_id = isset($_POST['form_id']) ? $_POST['form_id'] : false;
   if ($saved_form_id && $saved_form_id != $current_form_id) {
      // This is a new submission - add to DB
      ...
   }

   $_SESSION['form_id'] = $current_form_id;
}

Open in new window

0
 
LVL 1

Author Comment

by:Braveheartli
ID: 41770396
thank you both.
I have a question for you Julian Hansen,

what if the user remember something and want to send another form for example 10 minutes later?
can he send it or does he have to close the session?
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 41770475
A random string in a hidden field needs a bit of qualification.  If the random string is generated at the time the form is created, it's a reasonable assumption that it will be regenerated and be a different value each time the form is created.  This would occur independent of the content of the rest of the form.  Thus each form submit request will appear to be different, even if the client manually puts the same information into the form, over and over.  The principle advantage of the random string is to ensure that the client requested the form again before populating it with request data. This is often called a "form token."

On the other hand, a message digest made from the form elements (or from the form elements that you care  about) will only match the prior message digest if the same information is resubmitted.  

As a practical matter, the PHP session can be expected to live for at least 24 minutes, and maybe longer, so message digest matching gives a period of immunity from duplication.  But if you want to allow duplication after five minutes, or some similar interval you can just test the time of the submit actions.  If the submit occurs inside the 5-minute limit, make the test for duplicate data.  If the submit is outside the limit, you might choose to permit duplicate data.

In my experience, duplicated form submissions are almost always an attack vector or a client error.
0
 
LVL 52

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
ID: 41770499
I think Ray has answered your question - I will add my 2c worth.

The solution I posted was to prevent against someone hitting the submit button repeatedly and sending the same request to the server.

Under normal circumstances - a POST should be immediately followed by a redirect to an idempotent page - one that cannot affect the state of the system. This will isolate re-submissions from a refresh and other such actions. If the default action is to return to the form after submission then the redirect should take a turn through the form rendering code which in turn will spit out a new unique id.

Message digests can work - but only when the data being submitted is likely to be unique on each submission. If you have a situation where separate, legitimate submissions can have the same data (which is possible) then the message digest will not help and will in fact work against you. A time based submission can also work but gets tricky if you have users doing rapid data capture and legitimately submit the same data within the allotted time.

For me a unique form ID is the solution with the least question marks.
0

Featured Post

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
PHP Healthcheck 2 83
Passing variables to stored procedure 3 35
Problem with Simple PHP/mySQL Query 3 51
PHP warning 4 29
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Creating and Managing Databases with phpMyAdmin in cPanel.
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

914 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now