Verifying age on PHP - php

I've looked at many posts on here and I still cant figure this out.
I am trying to verify that someone is older than 13 before they register for my site. This is what i have so far
<?php
if (is_string($_POST['birthday']) && $_POST['birthday'] != 'mm/dd/yyyy')
{
$dateObj = new DateTime($_POST['birthday']);
$ageLimit = new DateTime('13 years');
$now = new DateTime(date("Y/m/d"));
$checkDate = $now->diff($ageLimit);;
if($checkDate > $dateObj)
{
$errors[]='You must be atleast 13 years old to join.';
}
else
{
$bday = mysqli_real_escape_string($db,$_POST['birthday']);
}
}
else
{
$errors[]= 'Enter your birthday.';
}
The code will always run to
$bday = mysqli_real_escape_string($db,$_POST['birthday']);}
no matter what is entered in the date field and the outcome is always 1.
Can anyone help me with this? I cant figure this one out on my own.
<b>Birth Date</b><br><input type="date" name="birthday"
value=<?php if(isset($_POST['birthday']))echo $_POST['birthday'];?>><br>

Comparaison operators work with DateTime, see the answer here.
So something like this should work
$dateObj=new DateTime($_POST['birthday']);
$ageLimit=new DateTime('-13 years');
if($dateObj > $ageLimit){
//TOO YOUNG
}
EDIT per comment
Replace
if(isset($_POST['birthday']))echo $_POST['birthday'];
with
if(isset($_POST['birthday'])) {
echo $_POST['birthday'];
} else {
echo 'mm/dd/yyyy';
}
Or change
if (is_string($_POST['birthday']) && $_POST['birthday'] != 'mm/dd/yyyy')
To
if (!empty($_POST['birthday']) && is_string($_POST['birthday']))

You have several errors
'13 years' is not a valid value for DateTime()
A date in the 'Y/m/d' format is not a valid format for DateTime()
$checkDate is a DateInterval object and is not comparable to a DateTime object
You can fix this and simplify your code by comparing DateTime objects which are comparable:
$birthday = new DateTime($_POST['birthday']);
$ageLimit = new DateTime('-13 years');
if ($birthday < $ageLimit) {
// they're old enough
}
else {
// too young
}
Demo

It might be easier to use strtotime to calculate the date difference. The higher the number the younger somebody is. So if the persons age is higher than the minimal age number they are not old enough.
if(is_string($_POST['birthday'])&&$_POST['birthday']!='mm/dd/yyyy') {
$minAge = strtotime("-13 years");
$dateObject = strtotime($_POST['birthday']);
if($dateObject > $minAge) {
$errors[]= 'You must be atleast 13 years old to join.';
}
} else {
$errors[]='Enter your birthday.';
}

Related

DateTime format question with negative numbers

I am having problems figuring out why the following code does not work. It returns the right numbers but when it hits -1 the page should stop.
The date fields are date in the mysql database.
$date = new DateTime(date("Y-m-d", strtotime($pay_posted1)));
$date->modify('+'.$time_frame1.' months');
$NEW_DATE = $date->format('Y-m-d');
$firstp = new DateTime(date("Y-m-d")); //CURRENT DATE
$secondp = new DateTime(date("Y-m-d", strtotime($NEW_DATE)));
$diffp = $firstp->diff($secondp);
$DIFFp = $diffp->format('%R%a');
$DIFF_p = $diffp->format('%a');
if ($DIFFp == +0) {
$PAYMENT_ERROR = "<center><h2><b><font color='#FF0000'>PAYMENT DUE
TODAY <a href=\"javascript:void(window.open('payment_history.php',
'',
'width=500,height=600,top=10,left=40,scrollbars=yes'))\">(View)
</a>
</font></b></h2></center>";
} elseif($DIFFp <= +10) {
$PAYMENT_ERROR = "<h2><b><font color='#FF0000'>PAYMENT DUE IN
$DIFFp DAY(S)</b></font></h2>";
} elseif ($DIFFp <= -1) {
$PAYMENT_ERROR = "<br><br><br><br><h1><b><font
color='#ff0000'>PAYMENT IS PAST DUE!! <br>
PLEASE FOLLOW THIS <a
href='http://wawoffice.net/contact.php'>LINK</a></font></h1>";
exit();
} else {
$PAYMENT_ERROR = "";
}
Thanks
-1 matches the condition elseif($DIFFp <= +10) so the last elseif will never be reached, you need to reverse the order of the elseif clauses.
Thank you gramamj42. That was it, have no idea how I missed that.

how to understand if one date in php is less than another minus one day?

how to understand if one date in php is less than another minus one day? I mean if for example a date is set to "2018/07/03"; how can I understand if a given date is less than "2018/07/02"
date1 : year1/month1/day1
date2: year2/month2/day2
<?php
if ($year1 >= $year2) {
if ($month1 >= $month2) {
if (($day1 - 1) > $day2) {
echo 'you could do something..';
}
}
}
?>
the above code fails if forexample $year2 = 2017 and $month2 = 11.. can anybody help me? thanks a lot..
Here, this should work.
$date_to_check = new DateTime($yesterday);
$today = new DateTime();
$time_diff = $today->diff($date_to_check)->d;
if($time_diff > 1) {
echo "This is greater than one day.";
}else{
echo "This is not greater than one day.";
$date = strtotime("2018/07/01");
$date2 = strtotime("2018/07/02");
if($date > $date2){
print('date is bigger');
// do stuff when date is bigger than date2
} else {
// else ...
print('date2 is bigger');
}
To convert string to date php has function named strtotime().
Compairing date objects is simple.
There is full information about strtotime()
http://php.net/manual/ru/function.strtotime.php
Another way:
$date = new DateTime("2018/07/01");
$date2 = new DateTime("2018/07/02");
if($date->modify("+1day") > $date2){
print('date is bigger');
// do stuff when date is bigger than date2
} else {
// else ...
print('date2 is bigger or equal');
}
Notice modify modifies $date object itself.
Read more here http://php.net/manual/en/class.datetime.php

How can I use getdate() to verify a user's age?

When a user attempts to register with my site, I need to verify that they are old enough. I am trying to do this using the getdate() function.
I understand what getdate() does, but I am struggling to understand how to use it correctly for this purpose.
<?php
$fn = $_POST["fullname"];
$un = $_POST["username"];
$pw = $_POST["password"];
$dob = $_POST["dayofbirth"];
$mob = $_POST["monthofbirth"];
$yob = $_POST["yearofbirth"];
$date = getdate();
if ( $yob =$yob>= $date["year"]-16)
{
echo "Too young to register!";
}
elseif ($yob <=1899)
{
echo "Don't be silly, you are not that old!";
}
else
{
echo "<h1>Thank you for registering with us!</h1>";
echo "<p> You have successfully registered with these details:
<br>Your full name :$fn<br> Username: $un
<br>Date of birth: $dob $mob $yob</p>";
}
?>
Try:
$registration = new DateTime(implode('-', array($yob, $mob, $dob)));
$now = new DateTime();
var_dump($now->diff($registration)->y);
This will give you the actual age, taking months, days and leap years into account.
DateTime Class Manual
If you correct this if ( $yob =$yob>= $date["year"]-16) to if ( $yob >= $date["year"]-16), then this will do what you're expecting it to and it will work some of the time. The problem is that depending on when someone's birthday is in the year compared to the current date, just subtracting the year like this will often give an incorrect result.
A better way would be to calculate the age using the DateTime::diff method. This should get you the person's exact age.
$age = date_create("$yob-$mob-$dob")->diff(new DateTime());
Then you can compare the year property of the resulting DateInterval object to verify the age.
if ( $age->y < 16) {
echo "Too young to register!";
} elseif ($age->y > 117) {
echo "Don't be silly, you are not that old!";
} else { ...

date within range or not

I am trying to check whether user submitted date is within range or not.
<?php
$datesyntx = "/^(19|20)\d\d[\-\/.](0[1-9]|1[012])[\-\/.](0[1-9]|[12][0-9]|3[01])$/";
$paydate = "2015-03-01";
if (preg_match($datesyntx, $paydate)) {
if(strtotime($paydate) > strtotime('2015-04-23') && strtotime($paydate) < strtotime('2015-07-23')) {
}
}
?>
It is not working what actually I am trying to get.
Try this code :
$paydate = date('2015-03-01');
$DateBegin = date('2010-01-01');
$DateEnd = date('2016-01-01');
if (($paydate > $DateBegin) && ($paydate < $DateEnd))
{
echo "is between";
}
else
{
echo "not between!";
}
P.S: this question was answered before at stackoverflow:
PHP check if date between two dates
EDIT2: easy way .
No need to use regex in this scenario, use simple DateTime class to check whether user submitted date is within range or not.you can also use typical strtotime() to do this job. But DateTime class will be great fun for this.
<?php
$userSubmitted = new DateTime("2015-04-01");
$startDate=new DateTime("2014-02-01 20:20:00");
$endDate=new DateTime("2015-04-30 23:50:11");
if ($userSubmitted > $startDate && $userSubmitted < $endDate)
{
return true; #date is within the range of yours
}
return false; #date not within the range of yours

Php custom date format and comparison

In my database I have one table in which I keep registered users.
One column is Date of register and I keep this value in my own string format.
For example "[2013-11-30] [19:42:46]"
Then I want to make a check.
If user is 30 days old or more.
The sure thing is that the above code is wrong.
The problem is that if one user registers at 29/01/2015
will not been showing in 30 last days if the current day is 02/02/2015!
//Datetime
$today = date_parse_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_parse_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if (
(($store[year] >= $today[year]) && ($store[month] >= $today[month]))
)
{ $date_last = "<font color='green'>".$row["LastSeen"]."</font>"; }
else
{ $date_last = "<font color='red'>".$row["LastSeen"]."</font>"; }
Use date_create_from_format instead of date_parse_from_format. Then you can simply compare the resulting values:
$today = date_create_from_format("[Y-m-d] [H:i:s]", gmdate("[Y-m-d] [H:i:s]"));
$store = date_create_from_format("[Y-m-d] [H:i:s]", $row["LastSeen"]);
if ($store < $today) {
// ...
}
else {
// ...
}

Categories