douchen5971 2015-02-26 20:10
浏览 25

php错误检查mysql日期

caveat: i am new to php

I'm reading in 2 dates from a form in a mysql format (i.e. YYYY-MM-DD) and trying to error check them both for validity and that one is less than the other

if(!empty($day1) && !empty($day2)){
 $sndate=array();
 $sndate = explode('-',$day1);
 $sndtnum = implode($sndate);
 $sndtnum = (int) $sndtnum;

 $unsndate=array();
 $unsndate = explode('-',$day2);
 $unsndtnum = implode($unsndate);
 $unsndtnum = (int) $unsndtnum;
  if (!checkdate($sndate[1],$sndate[2],sndate[0]) || !checkdate($unsndate[1],$unsndate[2],unsndate[0]) || $unsndtnum<$sndtnum)
  { $error=True; $errtext .="Date field is filled in wrong 
";
  }else {$error=False;}
}

This does not seem to work. I'm pretty sure it's because of the checkdate, but i'm not positive that there isn't also an issue with the implode/cast.

Any ideas on how to fix this?

  • 写回答

1条回答 默认 最新

  • doujiexin1136 2015-02-26 22:22
    关注

    Apart from the sndate[0] and unsndate[0] variables missing their dollar signs, your check will actually not work if an evil user put non-numeric chars in $day1 (e.g. 2015-09abc-01 will be considered as less than 2015-05-01).

    The following approach validates the dates by transforming them from a known format into a DateTime object and then back again, making sure that the two formatted dates are equal:

    $f = 'Y-m-d';
    $ok1 = ($d1 = DateTime::createFromFormat($f, $day1)) && $d1->format($f) == $day1;
    $ok2 = ($d2 = DateTime::createFromFormat($f, $day2)) && $d2->format($f) == $day2;
    
    if ($ok1 && $ok2 && $d1 <= $d2) {
        // Ok
    } else {
        // Error
    }
    

    Hope this helps :)

    评论

报告相同问题?

悬赏问题

  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题