Mysql TIMESTAMP: how to validate string in PHP

Viewed 289

In database there is a column in TIMESTAMP type. From console user can enter date in one of these format:

TIMESTAMP(14)   YYYYMMDDHHMMSS
TIMESTAMP(12)   YYMMDDHHMMSS
TIMESTAMP(10)   YYMMDDHHMM
TIMESTAMP(8)    YYYYMMDD
TIMESTAMP(6)    YYMMDD
TIMESTAMP(4)    YYMM
TIMESTAMP(2)    YY

As mysql docs says: all elements can be separate by any punctuation symbol.

Is there is a way to validate, string variable in php code for conformity of mysql TIMESTAMP format?
Example migration:

    $this->createTable('tweet',[
        'id' => Schema::TYPE_PK,
        'text' => Schema::TYPE_STRING.' NOT NULL',
        'date_written' => Schema::TYPE_TIMESTAMP.' NOT NULL',
        'date_imported' => Schema::TYPE_TIMESTAMP.' NOT NULL',
    ],"ENGINE=InnoDB DEFAULT CHARSET=utf8");

Action:

 public function actionIndex()
    {
        $stdin = fopen("php://stdin", "r");

        /**
         * @var TweetShow $tweetShow
         */
        $tweetShow = Yii::$app->get('tweetshow');

        $tweetShow->showStatisticInformMessage();

        $dateAndTime = fgets($stdin);
        try {
            strtotime($dateAndTime);
        } catch (\Exception $e) {
            echo "\033[01;31mНеверный формат даты!!!\n";
            die();
        }

FROM HERE I WANT TO BE SURE that dateAndTime has mysql TIMESTAMP format

    /**
     * @var TweetStatistic $tweetStatistic
     */
    $tweetStatistic = Yii::$app->get('tweetstatistic');

    $statistic = $tweetStatistic->getHashtagsStatisticByDate($dateAndTime);

    $tweetShow->statisticByHashtags($statistic, $dateAndTime);
}

strtotime bad solution. user can enter any string which can be parse in unix time.

0 Answers
Related