How can PHP functions like strtotime and checkdate be used to validate user input for dates before inserting them into a database?

When inserting user input for dates into a database, it is important to validate the input to ensure it is in the correct format and is a valid date. PHP functions like strtotime can be used to convert a date string into a Unix timestamp, while checkdate can be used to verify if a date is valid. By using these functions in combination, you can validate user input for dates before inserting them into a database.

$user_input = "2022-12-31";

// Validate user input for date
if (strtotime($user_input) === false) {
    echo "Invalid date format";
} elseif (!checkdate(date('m', strtotime($user_input)), date('d', strtotime($user_input)), date('Y', strtotime($user_input)))) {
    echo "Invalid date";
} else {
    // Insert validated date into database
    $validated_date = date('Y-m-d', strtotime($user_input));
    // Insert $validated_date into database
    echo "Date inserted into database: " . $validated_date;
}