What are the best practices for handling date inputs from HTML forms in PHP?

When handling date inputs from HTML forms in PHP, it is important to validate and sanitize the input to ensure it is in the correct format and prevent any malicious code injection. One common approach is to use the PHP DateTime class to parse and validate the date input before processing it further.

// Validate and sanitize date input from HTML form
$date = $_POST['date'];
$dateObj = DateTime::createFromFormat('Y-m-d', $date);

if($dateObj){
    $formattedDate = $dateObj->format('Y-m-d');
    // Proceed with further processing using $formattedDate
} else {
    // Handle invalid date input
    echo "Invalid date format. Please enter a date in the format YYYY-MM-DD.";
}