Solved

php if statement with date function

Posted on 2016-08-25
5
19 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 51

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 51

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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

This article discusses four methods for overlaying images in a container on a web page
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

757 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

22 Experts available now in Live!

Get 1:1 Help Now