MagentoMan
MagentoMan

Reputation: 573

Sanitizing a Date

I am using a javascript date picker that allows the user to select a date. However, I would like to also sanitize the posted date data before entering into the database. I am not seeing any sanitize filter here: https://www.php.net/manual/en/filter.filters.sanitize.php

What would be the best method to sanitize a date before entering into a database?

This would be the original value from the post:

$datepick = $_POST['date'];
// wich is 04/12/2014

Then I convert it for the database:

$date = date("Y-m-d", strtotime($datepick));

Thanks!

Upvotes: 6

Views: 22084

Answers (5)

$date_string = "2024-11-05";
if(isDate($date_string))echo "It is a valid date";
else echo "Not a valid date";

function isDate($string){// Specify the expected date format
    $date = DateTime::createFromFormat('Y-m-d', $string); 
    return $date && $date->format('Y-m-d') === $string;
}

Upvotes: 0

Justin Levene
Justin Levene

Reputation: 1677

I found the easiest is:

$date = trim($_GET['date'])==='' ? false : new DateTime(trim($_GET['date']));
if($date) $date= $date->format('Y-m-d');

With the above $date will either be a sanitised date string or false if it failed.

Upvotes: 0

Fawad
Fawad

Reputation: 43

This expression can be used to support both 12/12/2016 and 12-12-1993 formats.

filter_var (preg_replace("([^0-9/] | [^0-9-])","",htmlentities($input)));

Upvotes: 2

ReverseEMF
ReverseEMF

Reputation: 536

Formatting the date sanitizes it, because:

  1. If the formatter succeeds, then it will only be a date, with syntax controlled by the format string.
  2. If it fails, then FALSE is returned.

This is true of:

DateTime::format
DateTimeImmutable::format
DateTimeInterface::format
date_format()
Date($format, $date_string)

Upvotes: 5

Paul Denisevich
Paul Denisevich

Reputation: 2414

If your date is like "03/02/2014" then you can simply clean your variable by regexp:

$date = preg_replace("([^0-9/])", "", $_POST['date']);

This allows only digits (0-9) and fwd slash (/).

Upvotes: 18

Related Questions