How to stop an invalid date from being sent to a database - php

I require a date to be entered in the correct format, and if it isn't then an error is shown. My PHP program looks like this:
if (empty($_POST["date"])) {
$dateErr = "Date is required";
} else {
$date = test_input($_POST["date"]); etc
This is just the standard way of showing error for an improper date format. But my problem is that even though an error is shown, there is nothing that is stopping that date (in the wrong format) from being passed into the database. When I check my database, I see that date and it is not what I want. Is there a way that a date written in the wrong format can be blocked from ending up on my database? Like a filter, I mean.

Use the powerful DateTime class, DateTime::createFromFormat is useful here, it returns a new DateTime instance or FALSE on failure.
So it will go this way:
if (empty($_POST["date"])) {
$dateErr = "Date is required";
} else {
$format = 'Y-m-d'; // write your format here
$date = DateTime::createFromFormat($format, $_POST["date"]);
if($date)
{
// add to database
}
Also your database field should be set as datetime which has the format Y-m-d, so before you insert it you have to format it to Y-m-d using PHP, like:
$date->format('Y-m-d');
That will return a proper string to insert in your database.

You should use a function to check whether the date given is in the appropriate format before you begin your db transaction. You can do this in the following approach using regular expressions as #Subhanker mentioned to match to the following format 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])$/", $_POST['date']))
{
//Start DB transaction here
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$form_date = mysqli_real_escape_string($con, $_POST['date']);
$sql="INSERT INTO dates_table (dates)
VALUES ('$form_date')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}else{
$dateErr = "Date is required";
}
Please let me know if you have any questions!

You can use strtotime to do your checking. No regex needed
$date = strtotime($_POST["date"]);
if($date === false) $dateErr = "Unrecognized Date format";
else $date = date('m/d/Y', $date); // Set your own date format here

if (preg_match("/^(19|20)\d\d[\-\/.](0*[1-9]|1[012])[\-\/.](0*[1-9]|[12][0-9]|3[01])$/", $date )){//This will match the input in format YYYY-MM-DD
//Date ok
}else{
//Invalid Date
}

Related

How to check string on date in laravel?

How to check string on date in laravel?
I want to handle the situation if string doesn't date for example like "it's some not date string".
I try it code, but it doesn't work I have next error:
InvalidArgumentException : A two digit month could not be found
Data missing
My code:
if (Carbon::createFromFormat('m-d-Y', $rowMatrix[4]) !== false) {
//
}
You can use DateTime for this purpose :
$dateTime = DateTime::createFromFormat('d/m/Y', $rowMatrix[4]);
$errors = DateTime::getLastErrors();
if (!empty($errors['warning_count'])) {
// Not a date
}
Or you can check it like this :
if (date('Y-m-d H:i:s', strtotime($rowMatrix[4])) == $rowMatrix[4]){
// it's a date
}
You can use try/catch block:
try {
$date = Carbon::createFromFormat('m-d-Y', $rowMatrix[4])
} catch(InvalidArgumentException $e) {
$date = 'Not a date';
}
But a much better way is to use Laravel validation date_format rule to make sure the string is a date:
'some_date_field' => 'date_format:"m-d-Y"',

from php string to mysql date

What I'm trying to do is insert credit card info from a form to my mysql database.
First of all,
the input format for the expire date will be MM / YY(with or without spaces) on the form and i'm trying to concat the "20" string to the year but I always get "20 YY" as a result, which cannot be recognised from mysql as a date.
I want to get the expire date to fit a format so later on it can be altered into a MySQL format. Any ideas?
This is my code so far:
<?php
$cc_number="";
$cc_expire="";
$cc_cvc="";
$cc_number=$_POST['number'];
$cc_expire=$_POST['expiry'];
$cc_cvc=$_POST['cvc'];
$cc_pid=$_SESSION['pid'];
/*edit the expire date*/
$pieces=explode("/", $cc_expire);
$expire_dd="01";
$expire_mm=$pieces[0];
$expire_yy="20".$pieces[1];
$expire_yy=trim($expire_yy, "\x00..\x1F");
//$cc_expire = $expire_yy.$expire_mm.$expire_dd;
//$cc_expire = date('Y-m-d', strtotime(str_replace('-', '/', $cc_expire)));
echo "expire_yy = ".$expire_yy;
//echo "cc_expire = ".$cc_expire;
if (isset($_POST["submit"])) {
if (empty($cc_number) || empty($cc_cvc) || empty($cc_expire)) {
echo "<p align='center'><font color='red'><br><br><br><br>All fields are mandatory.</font></p>";
}
else {
$cc_expire = date('Y-m-d', strtotime($cc_expire));
$sql = "INSERT INTO credit_card (credit_card_number, cvc, expiration_date, pid)
VALUES ('$cc_number', '$cc_cvc', '$cc_expire', $cc_pid)";
if ($dbconn->query($sql)) {
//echo "<script> window.location.assign('../card.php'); </script>";
}
else {
echo "<p align='center'><font color='red'><br><br><br><br>Something went wrong.</font></p>";
}
}
}
?>
I want for all the cards to get a mySql DATE format which will be 01-MM-YYYY.
strtotime() should work for you. learn more here http://www.w3schools.com/php/func_date_strtotime.asp
Depending on how the data looks like in $cc_expire you may need to parse it first so this first:
$cc_expire = "28-".str_replace(" ","-",cc_expire);
Which should give dd-mm-yyyy format (I've had a issue using '/' before when changing dateformat)
Then do:
$mysqldate = date("Y-m-d H:i:s", strtotime($cc_expire));
This should convert the cc_expire to mysql format ready for insertion.

How can I validate UTC date

I'd like to validate UTC date, sent by the POST request, before inserting it into my database.
$date = "2014-08-11T16:32:13.000Z"
What is the best way to check if the date is correct?
try {
$dt = new DateTime($date);
// $dt->format(DateTime::ATOM); // contains valid date
}catch(Exception $exception) {
// invalid $date
}

How to verify valid date and format, error for each

I am using a date format YYYY-MM-DD. I am looking to check for proper format and date validity and echo an appropriate error message for each. My result is echoing an invalid date even when date is valid:
//validate date
if (!preg_match('/^(\d{4})-(\d{2})-(\d{2})$/',$date))
{
$dateErr = "Format must be \"YYYY-MM-DD\"" ;
}
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $postedDate, $datebit))
{
return checkdate($datebit[2] , $datebit[3] , $datebit[1]);
}
else
{
$dateErr = "Must be valid date." ;
}
if you are going to grab the values for use later anyway...
$YYYY=substr($date,0,4);
$DD=substr($date,7,2);
$MM=substr($date,5,2);
checkdate($MM,$DD,$YYYY);
if you are actually concerned about the format of the string for insertion into sql or something, you could filter it through date() or something

PHP/SQL - DateTime class - how to add automaticlly time if it's not inserted by the user

Now I sq use the DateTime class to convert to different time formats and I find it very useful except one feature. Before when the user try to add date but for some reason skip the time I got 00:00:00 for the time which was good enough for me. Now, with the DateTime class if the time is not included it return error.
Here is my code:
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time']);
if($dt === false)
{
throw new Exception("Invalid date");
}
$formattedDate = $dt->format('Y-m-d H:i:s');
Every time I try to insert date without time I get Invalid date error. Is there a way to insert zeros on the place of the time, except getting error for this?
Thanks
Leron
Some simple pre-validation:
$date['event_time'] = trim($date['event_time']);
if (preg_match('/^\d{2}\.\d{2}\.\d{4}$/', $date['event_time'])) {
$date['event_time'] .= ' 00:00:00';
} else if (!preg_match('/^\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}:\d{2}$/', $date['event_time'])) {
die('Invalid format');
}
If you don't want to use regex I guess this should work too. If i was you I would use #deceze solution instead of this :P but for the sake of completeness, here it is:
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time']);
if($dt === false)
{
$data['event_time'] = trim($data['event_time']);
$data['event_time'] .= " 00:00:00";
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time')
if ($dt === false) {
throw new Exception("Invalid date");
}
}
$formattedDate = $dt->format('Y-m-d H:i:s');

Categories