M9A
M9A

Reputation: 3276

How to check if a date is expired (PHP)

Hi my php script has two textboxes (one for month and one for year). When the user presses the submit button, it should verify the inputs to see if the dates are expired. Here is the code I made, but it doesnt seem to do anything.

$input_date = "$_POST['m']/$_POST['y']"; 

$todays_date = date("MM/YY");

if ($input_date < $todays_date)
{
   print '<p class = "error">Date has elapsed</p>';
}

Note: the date format is MM/YYYY (textbox 'm' contains MM and tetxbox 'y' contains YYYY)

Upvotes: 2

Views: 14111

Answers (3)

safarov
safarov

Reputation: 7804

You can use mktime() or strtotime()

$input_time = mktime(0,0,0,$_POST['m']+1,0,$_POST['y']); 

if ($input_time < time()){
   print '<p class = "error">Date has elapsed</p>';

}

Upvotes: 5

jonaz
jonaz

Reputation: 4124

You could probably use the strtotime function like this:

$input_date = "$_POST['m']/$_POST['y']"; 
$todays_date = date("m/Y");

if (strtotime($input_date) < strtotime($todays_date)){
print '<p class = "error">Date has elapsed</p>';

}

You can read here what kind of formats strtotime can handle: http://php.net/manual/en/function.strtotime.php

Upvotes: 3

psalvaggio
psalvaggio

Reputation: 181

I don't believe that you can put those $_POST variables in quotes. For instance, the following code will crash:

<?php
$foo = array("foo" => "bar");
$input = "$foo['foo']";
print $input;
?>

Instead, try

$input_date = $_POST['m'] . "/" . $_POST['y'];

Also, you may want to consider reversing month and year. In the current scheme 01/13 comes before 12/12.

Upvotes: 2

Related Questions