简体   繁体   English

使用PHP验证rfc2616日期字符串

[英]Validating rfc2616 date string with PHP

For security, requests to a PHP webservice will require a Date: header. 为了安全起见,对PHP Web服务的请求将需要一个Date:标头。

I need to calculate if the Date: header is within 15 minutes of the computer clock. 我需要计算Date:标头是否在计算机时钟的15分钟内。 I can easily do this by comparing 我可以通过比较轻松地做到这一点

$dt = new DateTime($_SERVER['HTTP_DATE']);

to the actual date. 到实际日期。 However, strotime also supports formats such as "now", which will always be 'valid'. 但是,strotime还支持诸如“ now”之类的格式,这些格式将始终为“有效”。

Is there a straightforward way to make sure people specify an absolute date. 有没有一种直接的方法来确保人们指定一个绝对日期。 Strictly checking RFC2616 is even better, but not a requirement. 严格检查RFC2616甚至更好,但不是必需的。

See: http://www.ietf.org/rfc/rfc2616.txt section 3.3.1 请参阅: http//www.ietf.org/rfc/rfc2616.txt第3.3.1节

Did some research and it looks like you can solve this using strptime() . 做了一些研究,看起来您可以使用strptime()解决此问题。 Note that this is untested, and I'm just guessing that strptime() will properly convert the string to GMT based on the supplied timezone. 请注意,这未经测试,我只是猜测strptime()会根据提供的时区将字符串正确转换为GMT。 This should at least get you started. 这至少应该让您入门。

$in = $_SERVER['HTTP_DATE'];
$out = 0;

$strptime_patterns = array(
    // Matches: Sun, 06 Nov 1994 08:49:37 GMT
    '%a, %d %h %Y %H:%M:%S %z',
    '%a, %d %h %Y %H:%M:%S %Z',
    // Matches: Sunday, 06-Nov-94 08:49:37 GMT
    '%A, %d-%h-%y %H:%M:%S %z',
    '%A, %d-%h-%y %H:%M:%S %Z',
    // Matches: Sun Nov  6 08:49:37 1994
    '%a %h %e %H:%M:%S %Y'
);

foreach ($strptime_patterns as $pat) {
    if ($arr = strptime($in, $pat)) {
        $out = mktime($arr['tm_hour'], $arr['tm_min'], $arr['tm_sec'], $arr['tm_mon'], $arr['tm_mday'], $arr['tmp_year'] + 1900);
        break;
    }
}

if ($out > gmmktime()) {
    // Invalid date - in the future
} elseif ($out >= gmmktime() - (15 * 60)) {
    // Valid, not expired
} elseif ($out > 0) {
    // Valid date, but expired
} else {
    // Invalid date
}
$request_time = strtotime($_SERVER['HTTP_DATE']);
$server_time = time();
$difference = abs($request_time - $server_time);
if($difference <= (15 * 60)) {
    //good to go
}

This just converts them both to Unix timestamps and compares them to make sure they're less than or equal to 15 minutes apart. 这只是将它们都转换为Unix时间戳,并进行比较以确保它们之间的间隔小于或等于15分钟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM