Reputation: 81
I'm trying to take individual values for date/time from a form submission and parse them into a date of a certain format.
If validation fails for any reason (e.g. 30th Feb, 13th month, etc) then the result should default to the current time.
if (isset($_POST['year'], $_POST['month'], $_POST['day'], $_POST['hour'], $_POST['minute']))
{
$y = $_POST['year'];
$m = $_POST['month'];
$d = $_POST['day'];
$h = $_POST['hour'];
$i = $_POST['minute'];
if (checkdate($m, $d, $y))
{
if ($h >= 0 && $h <= 23)
{
if ($i >= 0 && $i <= 59)
{
$str = $y.'-'.$m.'-'.$d.' '.$h.':'.$i.':00';
$time = strtotime($str);
}
else $time = time();
}
else $time = time();
}
else $time = time();
}
else $time = time();
$datetime = date('D j M Y - H:i:s T', $time);
echo $datetime;
Two things happen which I don't understand:
If one or more date values are missing, an error appears about checkdate()... I can't see why the validation doesn't just fail at the first if()
If one or more time values are missing, the end result is the UNIX Epoch?!
Upvotes: 1
Views: 1012
Reputation: 14523
Empty value check before execute checkdata
<?php
if(!empty($y) && !empty($m) && !empty($d) && !empty($h) && !empty($i))
{
if (checkdate($m, $d, $y))
{
if ($h >= 0 && $h <= 23)
{
if ($i >= 0 && $i <= 59)
{
$str = $y.'-'.$m.'-'.$d.' '.$h.':'.$i.':00';
$time = strtotime($str);
}
else $time = time();
}
else $time = time();
}
else $time = time();
}
else $time = time();
$datetime = date('D j M Y - H:i:s T', $time);
echo $datetime;
?>
Upvotes: 1
Reputation: 219914
If one or more date values are missing, an error appears about checkdate()... I can't see why the validation doesn't just fail at the first if()
Being set and having a valid value are two different things. A variable can be set and contain an empty string or null. Check to make sure those values actually contain values using empty()
.
If one or more time values are missing, the end result is the UNIX Epoch?!
If you pass date()
an invalid second parameter (i.e. a valid unix timestamp) it defaults to the epoch.
Upvotes: 5