Website Form Validation - php

I am currently designing a website and database solution which allows an administrator to login and view/add/edit/delete data held in the database.
What is the best way to go about form validation for details the person will enter into these forms;
i.e. dates must have the convention xx/xx/xx

There are many different ways of validating such data but the most popular one is using regular expressions. You probably also want to check other things after validating the data format.
For instance if you want to check your date you can do the following:
function checkDateFormat($date)
{
//match the format of the date
if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)) {
//check weather the date is valid of not
if(checkdate($parts[2],$parts[3],$parts[1]))
return true;
else
return false;
} else {
return false;
}
}
This will not only check the format of the date (in this case yyyy/mm/dd but you can modify it slightly to support yy/mm/dd or whichever order you want) but also will check if it is a valid date (e.g. 2001/02/31 is not a valid date).

You can do this native or by libraries like.
Native:
//If form was submitted
if ($_POST['submitted']==1) {
// check date format, ...
if ($_POST[date]){
$date = $_POST[date]; //If date was entered
}
...
}
Or by library: http://pear.php.net/package/HTML_QuickForm2
<?php
require_once 'HTML/QuickForm2.php';
require_once 'HTML/QuickForm2/Rule/Required.php';
require_once 'HTML/QuickForm2/Rule/Regex.php';
$form = new HTML_QuickForm2('tutorial');
$username = $form->addElement('text', 'username');
$form->addElement('submit', null, array('value' => 'Send!'));
$username->addRule(new HTML_QuickForm2_Rule_Required(
$username, 'Username is required!'
));
....

Related

How can I save a datetime data from an input in a table

I'm working on a website in php with the laravel framework and I have a database in phpmyadmin, I have a form and 2 inputs of type datetime-local, when I select the datetime from the inputs and then I send the form I get this error.
The datetime data that I would like to insert into my Table of my database in that's error, it's:
26, 2018-10-11T05:00, 2018-10-12T05:00. That's letter 'T' I think it's was me bring problems. Is possible to change that letter to a blank space? Possibly using javascript, o before the function store() of my Controller save the record in my database, can do something to save the datetime data from the inputs.
I put the code of the function store()
public function store(Request $request){
$hours = new HoursNew();
try {
/*HERE ARE THE NAMES FROM THE INPUTS IN MY FORM,
ALSO THE NAMES OF THE FIELDS OF MY TABLE IN MY DATABASE*/
$hours->id = $request->id;
$hours->time_start = $request->time_start;
$hours->time_end = $request->time_end;
$hours->estate_time_id = $request->estate_time_id;
$hours->court_id = $request->court_id;
$hours->save();
} catch (\Illuminate\Database\QueryException $e) {
Session::flash('error', 'Ups! We have some problems to process your operation');
return redirect()->route('ListHours.store');
}
Session::flash('message', "It's OK");
return redirect()->route('ListHours.store');
}
For each of the Request fields that dont conform to the database datetime requirements you will have to reformat then like this for example
$date = DateTime::createFromFormat('Y-m-d\Th:i', $request->time_start);
$hours->time_start = $date->format('Y-m-d H:i:s');
You could use php DateTime's format function to put it into the correct format:
http://php.net/manual/en/datetime.format.php
Laravel also has Carbon in it by default: https://carbon.nesbot.com/docs/
I normally use Y-m-d H:i:s for my format string, but both of the docs show additional formatting options.
you need to format the date-time
example
edited
$hours->time_start = date('Y-m-d H:i:s', strtotime($request->time_start));
Try to convert the date before calling save() function like this -
$hora_inicio = new DateTime($request->hora_inicio);
$hora_inicio = $hora_inicio->format('Y-m-d h:i:s');
$hora_fin = new DateTime($hora_fin);
$hora_fin = $hora_inicio->format('Y-m-d h:i:s');
and then assign these variables to your object.

Use of Preg_match to Determine Mobile Number or Email

I'm asking if there are better ways of determining what string has been inputted, either a phone number or an email, here are my already working code
public function InviteFriend($invitation)
{
// Initialize Connection
$conn = $this->conn;
// Check what type of Invitation it is
if (preg_match_all('~\b\d[- /\d]*\d\b~', $invitation, $res) > 0) {
$type = 'phone';
} else if (preg_match_all('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i', $invitation, $res) > 0) {
$type = 'email';
}
echo $type;
}
But my concern is if a user typed both phone and email in the same string, which of the if statement would be picked and which would be ignored? and is my way of determining which type of string proper or is there a more efficient way?
Thanks
There are two anchors almost available in all regex flavors which you have used in your second regex for validating an email address, shown as ^ and $ and meant as beginning and end of input string respectively.
You should use them for first validation as well. Your phone number validation lacks a good validation since it validates an arbitrary sequence of strings like 1------- --------5 that doesn't look like a phone number and much more things since it doesn't match against whole string (missing both mentioned anchors). So I used \d{10} to indicate a 10-digit phone number that you may want to change it to meet your own requirements, this time more precisely.
You don't really want that kind of email validation either. Something more simpler is better:
public function InviteFriend($invitation)
{
if (preg_match('~^\d{10}$~', $invitation)) {
$type = 'phone';
} else if (preg_match('~^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$~i', $invitation)) {
$type = 'email';
}
echo $type ?? 'Error';
}

How to check date type in a variable in PHP

I have an array in which dates are likes 01/10/2015 22:53:00 or 08/19/2016. i want to check that whether it is a date or not. If somebody put a text or other type in the field(Excel array), which i am putting into a variable, then it should generate an error that this is not a date.
I have searched but did not found success. Any help would be appreciated.
Try this (simple preg_match):
//your date
$date = '01/10/2015 12:12:23';
//check format
if(preg_match("/^[0-9]{1,2}\\/[0-9]{2}\\/[0-9]{4}$/", $date) OR preg_match("/^[0-9]{1,2}\\/[0-9]{2}\\/[0-9]{4} [0-9]{2}\\:[0-9]{2}\\:[0-9]{2}$/", $date)) {
echo 'OK';
}else {
echo 'BAD';
}
Try this:
$this->form_validation->set_rules(
'date',
'date time',
'regex_match[(0[1-9]|1[0-9]|2[0-9]|3(0|1))-(0[1-9]|1[0-2])-\d{4}]'
);

php time validation without zero in hours

I want to validate for a 24 hour format.
The below code accepts 1:05:24 which is wrong, as it should instead only accept 01:05:24
try
{
foreach ($arr as $key=>$item)
{
if (date('H:i:s', strtotime($item[1])))
{
} else {
throw new Exception('Invalid Time Format');
}
}
}
catch (Exception $e)
{
echo $exp = $e->getMessage();
}
The following use of preg_match will differentiate between the two cases you have mentioned.
However, note that neither this nor the method that you mentioned in the question will correctly detect an invalid time such as 00:99:99.
If you require that, you need a different method, the easiest of which is probably to parse out the numbers and run this function on it.
<?php
$mydate_bad = "1:05:70";
$mydate_good = "01:05:24";
print (preg_match("/^\d\d:\d\d:\d\d$/", $mydate_bad)); # Returns 0
print (preg_match("/^\d\d:\d\d:\d\d$/", $mydate_good)); # Returns 1
?>
Based on the code you've provided, one way would be the following:
$php_date = date('H:i:s', strtotime($item[1]));
if ($php_date && $php_date == $item[1]) {
// valid date
}
This will check that a date could be created as in your code, and it will also ensure that the resulting date in the format H:i:s corresponds to what the user entered.
However, in terms of user-friendliness, if you can create a date from the user input, it might be better just to accept it and add the leading 0 yourself if it is missing. Simply use $php_date in favor of $item[1] afterwards.

Store a user-input date string as datetime

I'm using php, and need to parse a date string formatted as dd/mm/yyyy and store it in MySql.
How can I convert the string to a datetime variable in a MySql table?
Probably the best way would be using this: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date
SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');
-> '2004-04-31'
Or equivalent PHP functions like:
http://www.php.net/manual/en/function.date-parse-from-format.php (from PHP 5.3)
A generic PHP function would look like
function convertDate($dateString) {
return date('Y-m-d H:i:s',strtotime(str_replace('/','-',$dateString)));
}
or
function convertDate($dateString) {
$a = explode($dateString('/'));
return "{$a[2]}-{$a[1]}-{$a[0]} 00:00:00";
}
First of all you should store a configuration for the required format date, maybe something like this:
Knowing that the ISO_DATE FORMAT is "Y-m-d"
You must save the output configuration somehow, at least the separator.
If you know the separator and you know the format into which the date is entered than you can validate it using checkdate(), and also transform it into the ISO standard by exploding the values by the predefined separator.
I have a validation object that tells me if a field is of a certain type (String,Date,Datetime,Integer,Float) then formats the parameters sent to SQL :
as an example, let's say i get this array from my html form into PHP:
$_POST["DATA"] = array("name"=>"Koko bongo","age"=>12,"graduation_date"=>"12/06/1986");
and we define a validation array, like this:
$validator= array("name"=>"string","age"=>"integer","graduation_date"=>"date");
I have a configuration for each table which makes this automated but you can do it customly inplace by having an evalAndFormatType function that works like this
function evalAndFormatType($value,$type) {
switch strtolower($type) {
case "integer":
$item = is_numeric($value) && !strstr($value,DECIMAL_SEPARATOR) ? intval($item) :false;
break;
case "Date":/*we suppose that somehow we now the order, how you do it it is your decision: configuration array,constants etc*/
$check = explode(DATE_SEPARATOR,$value);
$item = sizeof($check) == 3 && checkdate(intval($check[1]),intval($check[0]),intval($check[2])) ? $check[2]."-".$check[1]."-".$check[0] : false;
break;
default:
throw Exception("Unknown type ".$type);
break;
}
return $item;
}
now, in your code you can say
$_DATA = $_POST["DATA"]; // the previously defined array
$errMsg = array();
foreach($_DATA as $k=>$v) {
$_DATA[$k] = evalAndFormat($v,$validator[$k]);
if($_DATA[$k] === false) {
$errMsg[$k] = "requires type ".$validator[$k];
}
}
if(empty($errMsg)){
$sql= ....WHATEVER USING THE INFO
} else {
return $errMsg;
/*this can be used to show errors nicely near your text boxes by parsing the expected keys or sending it by JSON etc
or
you could create a string out of it by using locale data that you might have which could output something like
Required fields: Graduation date[invalid type],Name,Age ... etc
"/
I hope this answers your question and also explains my "strange" approach on it.
}

Categories