php birthday validation function - php

I am trying to add a birthday validation function in my php script to make sure users are 18+. But I am stuck on how to add it in my if statement.
This is what is taken from the input fields:
$ydob = ($_POST['ydob']);
$mdob =($_POST['mdob']);
$ddob = ($_POST['ddob']);
$dob = $ddob."-".$mdob."-".$ydob;
The function:
function validateDOB($dob){
list($ydob,$mdob,$ddob) = explode("-",$dob);
$year_diff = date("Y") - $ydob;
$month_diff = date("m") - $mdob;
$day_diff = date("d") - $ddob;
if ($day_diff < 0 || $month_diff < 0) {
$year_diff--;
return $year_diff;
} }
This block is to check if all details are entered correctly. So my question is how would I add the function here to validate if the user is over 18.
if((!$username) || (!$country) || (!$dob) || (!$email) || (!$password)){
$error_message = "You did not submit the following required information!<br /><br />";
if(!$username){
$error_message .= "Enter a User Name";
} else if(!$country){
$error_message .= "Enter a Country";
} else if(!$dob){
$error_message .= "Enter a D.O.B";
} else if(!$email){
$error_message .= "Enter a Email Address";
} else if(!$password){
$error_message .= "Enter a Password";
}
} else {
....}
Thank you so much.
Ray

There's a much easier way to do it:
function validateDOB($date)
{
$minAge=strtotime("-18 YEAR");
$entrantAge= strtotime($date);
if ($entrantAge < $minAge)
{
return false;
}
return true;
}
And then:
if(validateDOB($date))
{
echo "Welcome";
}
else
{
echo "Sorry, you are too young";
}
EDIT: To convert your date from European date format to MySQL format, you can do this:
$ymd = DateTime::createFromFormat('d-m-Y', $dmy)->format('Y-m-d');
You can do that before you pass it through to the function, or you could do it inside the function. Up to you.

You have to add in your else statement:
else {
if(validateDOB($dob) <18)
{
$error_message .= "Not old enough<br />";
}
}

$date = '2010-11-05 18:55:21';
if (strtotime($date) !== false)
{
...
}

This Function returns True only if it is a valid date (also leap year) and also throw FALSE if it is not meeting your Application's minimum age requirement. Find Me On Best Social Network Fun n Enjoy ( http://www.myfne.com/ravinder )
function checkDOB($minage="-18 YEAR")
{
if(checkdate( $_POST["dob_month"] , $_POST["dob_day"] , $_POST["dob_year"])==TRUE){
return true;
}
$date=$_POST["dob_month"]."-".$_POST["dob_day"]."-".$_POST["dob_year"];
$minAge=strtotime($minage);
$entrantAge= strtotime($date);
if ($entrantAge > $minAge)
{
return true;
}
return false;
}

Related

Add input's errors in array with for

I have one problem in PHP code. It did not give me whatever output. Where my mistake?
if (isset($_POST['regBtn'])) {
$fname = strip_tags(trim($_POST['fname']));
$lname = strip_tags(trim($_POST['lname']));
$email = strip_tags(trim($_POST['email']));
$password = strip_tags(trim($_POST['password']));
$errMsg = array();
for($i=0; $i<=3;$i++) {
if (strlen($fname) < 0) {
$errMsg[$i] = "Գրեք Ձեր անունը ամբողջությամբ։";
} elseif (strlen ($lname) <0) {
$errMsg[$i] = "Գրեք Ձեր ազգանունը ամբողջությամբ";
} elseif (strlen($email) < 0) {
$errMsg[$i] = "Գրեք Ձեր էլ․ հասցեն";
} elseif (strlen($password) < 6) {
$errMsg = "Գաղտնաբառը պետք է պարունակի առնվազն 6 նիշ";
} }
var_dump ($errMsg);
}
else {
}
Several problems here, assuming that you have a form input with name="regBtn" which is required for this code to run:
strlen will not be < 0 though it may be 0. Use empty or a number greater than 0 if needed.
elseif will only execute if the if fails so just use if.
No need to loop, just use multiple if blocks and dynamically append to the error array [].
if (isset($_POST['regBtn'])) {
$fname = strip_tags(trim($_POST['fname']));
$lname = strip_tags(trim($_POST['lname']));
$email = strip_tags(trim($_POST['email']));
$password = strip_tags(trim($_POST['password']));
$errMsg = array();
if (empty($fname)) { // or use strlen < 2 or < 3 or whatever like $password
$errMsg[] = "Գրեք Ձեր անունը ամբողջությամբ։";
}
if (empty($lname)) {
$errMsg[] = "Գրեք Ձեր ազգանունը ամբողջությամբ";
}
if (empty($email)) {
$errMsg[] = "Գրեք Ձեր էլ․ հասցեն";
}
if (strlen($password) < 6) {
$errMsg[] = "Գաղտնաբառը պետք է պարունակի առնվազն 6 նիշ";
}
var_dump ($errMsg);
}
Also, you probably want to trim after strip_tags in case it leaves space(s):
$fname = trim(strip_tags($_POST['fname']));

PDO insert trying to bind wrong number of params

I am having trouble figuring out where my insert (using pdo) is failing. I passed it 19 parameters via an array, and then bound 19 values from that same array.
It fails at the bind step with the following error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens'
I was wondering if you guys would be able to figure out why its failing. The code I am using is below:
addevent.php
if(isset($_POST['add_event'])){
$eventDetails = $_POST;
$event_code = htmlspecialchars($eventDetails['ecode']);
$event_title = htmlspecialchars($eventDetails['etitle']);
$location = htmlspecialchars($eventDetails['location']);
$start_date = htmlspecialchars($eventDetails['start_date']);
$end_date = htmlspecialchars($eventDetails['end_date']);
$super_early_date = htmlspecialchars($eventDetails['super_early_date']);
$early_date = htmlspecialchars($eventDetails['early_date']);
$tax_type = htmlspecialchars($eventDetails['tax_desc']);
$tax_rate = htmlspecialchars($eventDetails['tax_rate']);
$is_call_open = htmlspecialchars($eventDetails['is_call_open']);
$domain_name = htmlspecialchars($eventDetails['domain']);
$sold_out_msg = htmlspecialchars($eventDetails['sold_out_msg']);
$group_min = htmlspecialchars($eventDetails['group_discount_min']);
$group_num = htmlspecialchars($eventDetails['group_discount_per']);
//errors array that will be passed to view if there are errors;
$errors = array();
//if there are contents in the error array from previous execution empty error
if(!empty($errors)){ unset($errors); }
//if any of these fields are empty add them to the array
if(empty($event_code)) { array_push($errors, ucwords('event code is required')); }
if(empty($event_title)) { array_push($errors, ucwords('event title is required')); }
if(empty($location)) { array_push($errors, ucwords('location is required')); }
if(empty($start_date)) { array_push($errors, ucwords('start date is required')); }
if(preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/',$start_date) == 0) { array_push($errors, ucwords('incorrect format for start date, it should be').' yyyy-mm-dd'); }
if(empty($end_date)) { array_push($errors, ucwords('end date is required')); }
if(preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $end_date) == 0) { array_push($errors, ucwords('incorrect format for end date, it should be').' yyyy-mm-dd'); }
if(preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $super_early_date) == 0) { array_push($errors, ucwords('incorrect format for super early bird date, it should be').' yyyy-mm-dd'); }
if(preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $early_date) == 0) { array_push($errors, ucwords('incorrect format for early bird date, it should be').' yyyy-mm-dd'); }
if($tax_type == 'none') { array_push($errors, ucwords('tax type is required')); }
if(empty($tax_rate)) { array_push($errors, ucwords('tax rate is required')); }
if(empty($domain_name)) { array_push($errors, ucwords('domain name is required')); }
if(preg_match('/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/', $domain_name) == 0) { array_push($errors, ucwords('domain name is not valid')); }
if(empty($sold_out_msg)) { array_push($errors, ucwords('sold out message is required')); }
if(!empty($group_min) && empty($group_num)) { array_push($errors, ucwords('group discount (percent) is required')); }
if(!empty($errors)){
$this->set('errors', $errors);
}
else{
//remove the add_event button from the event
$add_event_index = array_pop($eventDetails);
$keys = array_keys($eventDetails);
$addEvent = "INSERT INTO v_events (" . implode(",", $keys) . ") VALUES (";
for($i = 0; $i < sizeof($eventDetails); $i+=1){
if($i == 0) { $addEvent .= "?"; }
else { $addEvent .= ",?"; }
}
$addEvent .= ")";
$success = $this->Cms->query($addEvent, $eventDetails);
if(!$success){
print_r($this->Cms->getError());
}
$this->set('success', ucwords('event succcesfully added!'));
}
}
$this->Cms->query function:
public function query($query, $attributes = array(), $singleResult = 0) {
echo $query;
$stmt = $this->dbc->prepare($query);
if(!empty($attributes)){
echo'<pre>';
print_r($attributes);
echo'</pre>';
foreach($attributes as $values){
if(empty($values) || $values) { $values = 'not provided'; }
if($values == NULL) { $values = '0'; }
echo $stmt->bindParam('?', $values);
echo'<pre>';
$stmt->debugDumpParams();
echo'</pre>';
}
}
$success = $stmt->execute();
return $success;
}

PHP - Avoiding nested if statements - cleaner way to code this

Assume that I am creating a registration form. I have code like the below and it is hard to manage because of all the nested if statements.
I want to know the cleanest and easiest to follow way to write code that functions similarly to what I have below.
EDIT: People have told me that I can move the empty($_POST['email']) to the validation functions. I can't do that because I need to know 1) whether user has posted data or not, and 2) whether the data user posted is valid.
For example, when the user first goes to the registration page, they have not posted any data so $_POST['email'] will generate PHP warnings because they don't exist. That's why I check whether data has been posted before I validate.
Does this make sense?
function validate_email($str) {
$str = trim(strtolower($str));
if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
return false;
} else {
return $str;
}
}
function validate_password($str) {
$str = trim($str);
if(strlen($str) < 5 || strlen($str) > 70) {
return false;
} else {
return $str;
}
}
$email = false;
$password = false;
$errorMessage = false;
if(!empty($_POST['email'])) {
$email = validate_email($_POST['email']);
if($email) {
if(!empty($_POST['password'])) {
$password = validate_password($_POST['password']);
if($password) {
createNewUser($email,$password);
} else {
$errorMessage = "The password is not valid";
}
} else {
$errorMessage = "The password is not valid";
}
} else {
$errorMessage = "Email address is invalid";
}
} else {
$errorMessage = "Email address is invalid";
}
if($errorMessage) echo $errorMessage;
Whenever you have nested if()s you can flip the logic "inside out":
if (A)
if (B)
if (C)
final()
change to:
if (!A) return
if (!B) return
if (!C) return
final()
In your case instead of returning you could throw an exception.
try {
validateAndCreateNewUser();
}
catch(ValidationError $e) {
display($e->getMessage());
}
You don't need the empty checks at that point, move them to the validation functions.
For example:
function validate_email($str) {
if(empty($str)) {
return false;
}
$str = trim(strtolower($str));
if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
return false;
} else {
return $str;
}
}
$email = validate_email($_POST['email']);
if($email) {
// your code
}
This is a bit cleaner:
function validate_email($str) {
if (empty($str)) return false;
$str = trim(strtolower($str));
if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
return false;
} else {
return $str;
}
}
function validate_password($str) {
if (empty($str)) return false;
$str = trim($str);
if(strlen($str) < 5 || strlen($str) > 70) {
return false;
} else {
return $str;
}
}
$email = false;
$password = false;
$errorMessage = false;
$email = validate_email($_POST['email']);
if($email) {
$password = validate_password($_POST['password']);
if($password) {
createNewUser($email,$password);
} else {
$errorMessage = "The password is not valid";
}
} else {
$errorMessage = "Email address is invalid";
}
if($errorMessage) echo $errorMessage;

PHP If statement not working when checking an Array

I have this If statement to check user submitted data. The data is first turned into an array which is then passed to a function where this if statement is located.
$errCount = 0;
$errMSG ='';
// Check Name
if ($submitData['FullName'] != '') {
if (strlen ($submitData['FullName']) < 4) {
$errCount + 1;
$errMSG .='The Full Name was too short!';
}
} else {
$errCount + 1;
$errMSG .='The Full Name Field was left blank!';
}
When this is run, even with an empty string, none of the errors are being triggered.
Am I missing something?
Thanks!
You are not assigning values to $errCount varaible when incrementing it;
$errCount = 0;
$errMSG ='';
$submitData['FullName']='';
// Check Name
if ($submitData['FullName'] != '') {
if (strlen ($submitData['FullName']) < 4) {
$errCount=$errCount + 1; // or u can write $errCount++;
$errMSG .='The Full Name was too short!';
}
} else {
$errCount=$errCount + 1; // or u can write $errCount++;
$errMSG .='The Full Name Field was left blank!';
}
echo $errMSG;
echo $errCount;
This will work.....
$errCount = 0;
$errMSG ='';
// Check Name
if(isset($submitData['FullName']) && strlen ($submitData['FullName'])>0 && strlen ($submitData['FullName'])<4)
{
$errCount++;
$errMSG .='The Full Name was too short!';
}
else if($submitData['FullName'] == '')
{
$errCount++;
$errMSG .='The Full Name Field was left blank!';
}
else
{
//success
}

help with array

What am i doing wrong here? The username string is less than 2 chars but it still dont set error[]?
Register:
$errors = array();
$username = "l";
validate_username($username);
if (empty($errors)) {
echo "nothing wrong here, inserting...";
}
if (!empty($errors)) {
foreach ($errors as $cur_error)
$errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>';
}
function validate_username($username) {
$errors = array();
if (strlen($username) < 2)
$errors[] = "Username too short";
else if (strlen($username) > 25)
$errors[] = "Username too long";
return $errors;
}
It's because you are not assigning the return value of validate_username() to any variable.
Try
$errors = validate_username($username);
Change validate_username($username); to $errors = validate_username($username);
Your function is affecting a local variable named errors, not the global errors that you may have been expecting.
Further, your code can be cleaned up a little bit as follows
$username = "l";
$errors = validate_username($username);
// No errors
if ( empty($errors) ) {
echo "nothing wrong here, inserting...";
}
// Errors are present
else {
foreach ( $errors as $cur_error ) {
$errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>';
}
}
function validate_username($username) {
$errors = array();
$len = strlen($username);
if ( $len < 2 ) {
$errors[] = "Username too short";
} elseif ( $len > 25 ) {
$errors[] = "Username too long";
}
return $errors;
}
you're not returning it the right way, you need:
$errors = validate_username($username)
you forgot to assign $errors
$errors = validate_username($username);
**//TRY THIS INSTEAD**
$errors = array();
$username = "l";
**$errors = validate_username($username);**
if (empty($errors)) {
echo "nothing wrong here, inserting...";
}
if (!empty($errors)) {
foreach ($errors as $cur_error)
$errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>';
}
function validate_username($username) {
$errors = array();
if (strlen($username) < 2)
$errors[] = "Username too short";
else if (strlen($username) > 25)
$errors[] = "Username too long";
return $errors;
}

Categories