源码位置:extdatephp_date.c
代码如下 | 复制代码 |
/* {{{ proto int strtotime(string time [, int now ]) Convert string representation of date and time to a timestamp */ PHP_FUNCTION(strtotime) { char *times, *initial_ts; int time_len, error1, error2; struct timelib_error_container *error; long preset_ts = 0, ts; timelib_time *t, *now; timelib_tzinfo *tzi; tzi = get_timezone_info(TSRMLS_C); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, “sl”, ×, &time_len, &preset_ts) != FAILURE) { /* We have an initial timestamp */ now = timelib_time_ctor(); initial_ts = emalloc(25); snprintf(initial_ts, 24, “@%ld UTC”, preset_ts); t = timelib_strtotime(initial_ts, strlen(initial_ts), NULL, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper); /* we ignore the error here, as this should never fail */ timelib_update_ts(t, tzi); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, t->sse); timelib_time_dtor(t); efree(initial_ts); } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, “s|l”, ×, &time_len, &preset_ts) != FAILURE) { /* We have no initial timestamp */ now = timelib_time_ctor(); now->tz_info = tzi; now->zone_type = TIMELIB_ZONETYPE_ID; timelib_unixtime2local(now, (timelib_sll) time(NULL)); } else { RETURN_FALSE; } if (!time_len) { timelib_time_dtor(now); RETURN_FALSE; } t = timelib_strtotime(times, time_len, &error, DATE_TIMEZONEDB, php_date_parse_tzfile_wrapper); error1 = error->error_count; timelib_error_container_dtor(error); timelib_fill_holes(t, now, TIMELIB_NO_CLONE); timelib_update_ts(t, tzi); ts = timelib_date_to_int(t, &error2); timelib_time_dtor(now); timelib_time_dtor(t); if (error1 || error2) { RETURN_FALSE; } else { RETURN_LONG(ts); } } /* }}} */ |
strtotime函数在使用strtotime(“-1 month”)求上一个月的今天时会出一些状况,
因此也引出写这篇文章,本文包括如下内容:
strtotime函数的一些用法
strtotime函数的实现基本原理
strtotime(“-1 month”)求值失败的原因
strtotime函数的一些用法
1、 strtotime(“JAN”)和strtotime(“January”)
这两个用法的效果是一样的,都是返回指定月份的今天,如果指定月份没有今天,则顺延到下一个月。 如在2011-03-31计算二月,代码:
echo date("Y-m-d H:i:s", strtotime("feb", strtotime("2011-03-31")));
程序会输出: 2011-03-03 00:00:00。 从表象来看,这个结果也许不一定是我们想要的,但是这也算是一种解决方案,这种方案是由什么决定的呢? strtotime函数在执行月份的计算时只计算了月份,相当于直接将月份设置为指定的月份的值,而如jan,january都会有一个对应内部数值。
2、 first关键字
first是一个辅助型的关键字,它可以与星期,天等可以指定确认值的关键字组合使用,如求2011年的第一个星期天:
echo date("Y-m-d H:i:s", strtotime("second sunday", strtotime("2011-01-01"))), "<br />";
在PHP的源码中,对于first与星期和天的组合使用是分开的,即first day对应一个处理操作, 在最终的C实现中,天的值指定为1,即time结构中的d字段指定为1,如下代码:
switch (time->relative.first_last_day_of) {
case 1: /* first */
time->d = 1;
break;
case 2: /* last */
time->d = 0;
time->m++;
break;
}
3、previous和next关键字
与first类似,previous关键字可以与星期,天组合使用,表示指定时间的前一个星期几或前一天。如下所示代码:
echo date("Y-m-d H:i:s", strtotime("previous sunday", strtotime("2011-02-01"))), "<br />";
程序会输出:2011-01-30 00:00:00
程序求2011-02-01的前一个星期天。
next关键字与previous相反,它表示下一个星期几或后一天。
4、 last关键字
last关键字既可以作为上一个,也可以作为最后一个。如求上一个星期天的日期:
echo date("Y-m-d H:i:s", strtotime("last sunday", strtotime("2011-02-05"))), "<br />";
程序会输出: 2011-01-30 00:00:00
当程序作为最后时,其应用场景是指定日期所在月的最后一天,相当于date(“t”)的结果。如求2000年2月的最后一天:
echo date("Y-m-d H:i:s", strtotime("last day", strtotime("2000-02-01"))), "<br />";
first、previous、last和this关键字在re文件中属于同一组。
5、 back和front关键字
这两个关键字是对一天中的小时的向前和向后操作,其调用格式如下:
echo date("Y-m-d H:i:s", strtotime("back of 24", strtotime("2011-02-01"))), "<br />";
echo date("Y-m-d H:i:s", strtotime("front of 24", strtotime("2011-02-01"))), "<br />";
back表示将时间设置指定小时值的后一个小时的15分的位置。如果是24点,则算到第二天的0点15分。
front表示将时间设置指定小时值的前一个小时的45分的位置。如果是0点,则算前一天的23点45分。
上面的代码输出:2011-02-02 00:15:00 2011-02-01 23:45:00。 其中back of和front of后接的数组必须大于等于0并且小于等于24。
strtotime函数的实现基本原理
官方文档对于strtotime函数的说明是这样的:本函数预期接受一个包含美国英语日期格式的字符串并尝试将其解析为 Unix 时间戳 (自 January 1 1970 00:00:00 GMT 起的秒数),其值相对于 now 参数给出的时间,如果没有提供此参数则用系统当前时间。
这是一个标准PHP内置函数,从PHP4起就已经存在。strtotime函数是以一个扩展的方式加载进来的,在ext/date目录下有其全部实现。 作为一个标准的内置函数,其定义格式也是标准的,如下:
PHP_FUNCTION(strtotime)
// 处理输入,对于是否有第二个参数有没的处理
// 调用相关函数,实现字符串的解析和结果计算
// 返回结果
}
在输入处理中,先识别两个参数都存在的情况并进行处理,如果不是此种状态,则处理第二个参数不存在的情况, 如果都没有,则报错,返回FALSE。
strtotime函数的第一个参数是一个字符串,对于这个字符串,由于其复杂性,PHP使用了其词法解析一样的工具:re2c。在/ext/date/lib目录下,从parse_date.re文件我们可以看到其原始的re文件。 当用户以参数的形式传入一个字符串,此字符串将交给此程序处理,针对其字符串的不同,匹配不同的处理函数。 如strtotime(“yesterday”)调用,分析字符串时,将匹配yesterday字符串,此字符串对应函数如下:
代码如下 | 复制代码 |
'yesterday' { DEBUG_OUTPUT("yesterday"); TIMELIB_INIT; TIMELIB_HAVE_RELATIVE(); TIMELIB_UNHAVE_TIME(); s->time->relative.d = -1; TIMELIB_DEINIT; return TIMELIB_RELATIVE; } |
这里有几个关键的结构体:
代码如下 | 复制代码 |
typedef struct Scanner { int fd; uchar *lim, *str, *ptr, *cur, *tok, *pos; unsigned int line, len; struct timelib_error_container *errors; struct timelib_time *time; const timelib_tzdb *tzdb; } Scanner; typedef struct timelib_time { timelib_sll y, m, d; /* Year, Month, Day */ timelib_sll h, i, s; /* Hour, mInute, Second */ double f; /* Fraction */ int z; /* GMT offset in minutes */ char *tz_abbr; /* Timezone abbreviation (display only) */ timelib_tzinfo *tz_info; /* Timezone structure */ signed int dst; /* Flag if we were parsing a DST zone */ timelib_rel_time relative; timelib_sll sse; /* Seconds since epoch */ unsigned int have_time, have_date, have_zone, have_relative, have_weeknr_day; unsigned int sse_uptodate; /* !0 if the sse member is up to date with the date/time members */ unsigned int tim_uptodate; /* !0 if the date/time members are up to date with the sse member */ unsigned int is_localtime; /* 1 if the current struct represents localtime, 0 if it is in GMT */ unsigned int zone_type; /* 1 time offset, * 3 TimeZone identifier, * 2 TimeZone abbreviation */ } timelib_time; typedef struct timelib_rel_time { timelib_sll y, m, d; /* Years, Months and Days */ timelib_sll h, i, s; /* Hours, mInutes and Seconds */ int weekday; /* Stores the day in 'next monday' */ int weekday_behavior; /* 0: the current day should *not* be counted when advancing forwards; 1: the current day *should* be counted */ int first_last_day_of; int invert; /* Whether the difference should be inverted */ timelib_sll days; /* Contains the number of *days*, instead of Y-M-D differences */ timelib_special special; unsigned int have_weekday_relative, have_special_relative; } timelib_rel_time; |
s->time->relative.d = -1;所表示的意思是当前时间的相对天数是-1。 这只是中间词法解析的中间结果,但是最后结果是通过这些中间结果计算出来的。
strtotime(“-1 month”)求值失败的原因
虽然strtotime(“-1 month”)这种方法对于后一个月比前一个月的天数的情况会求值失败,但是从其本质上来说,这并没有错。 PHP这样实现也无可厚非。只是我们的需求决定了我们不能使用这种方法,因此我们称其为求值失败。
我们来看它的实现过程,由于没有第二个参数,所以程序使用默认的当前时间。 第一个参数传入的是-1 month字符串,这个字符串所对应的re文件中的正则为:
reltextunit = (('sec'|'second'|'min'|'minute'|'hour'|'day'|'fortnight'|'forthnight'|'month'|'year') 's'?) | 'weeks' | daytext;
relnumber = ([+-]*[ t]*[0-9]+);
relative = relnumber space? (reltextunit | 'week' );
最终relative会对应一系列操作,程序会识别出前面的-1 和后面的month字符串,month对应一种操作类型:TIMELIB_MONTH。 在此之后,根据识别出来的数字和操作类型执行操作,如下代码:
case TIMELIB_MONTH: s->time->relative.m += amount * relunit->multiplier; break;
如上代码,则是直接记录月份的相对值减一。 但是对于类似于3月31号这样的情况,2月没有31号,程序会自动将日期计算到下一个月。
接口是一种约束形式,其中只包括成员定义,不包含成员实现的内容。用接口(interface),你可以指定某个类必须实现哪些方法,但不需要定义这些方法的具体内容。 我们可以通过interface来定义一个接口,就像定义一个标准的类一样,但其中定义所有的方法都是空的。
接口中定义的所有方法都必须是public,这是接口的特性。
实现
要实现一个接口,可以使用implements操作符。类中必须实现接口中定义的所有方法,否则会报一个fatal错误。如果要实现多个接口,可以用逗号来分隔多个接口的名称。
Note:
实现多个接口时,接口中的方法不能有重名。
Note:
接口也可以继承,通过使用extends操作符。
常量
接口中也可以定义常量。接口常量和类常量的使用完全相同。它们都是定值,不能被子类或子接口修改。
范例
Example #1 接口代码示例
<?php
// 声明一个'iTemplate'接口
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
// 实现接口
// 下面的写法是正确的
class Template implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
// 下面的写法是错误的,会报错:
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
?>
Example #2 Extendable Interfaces
<?php
interface a
{
public function foo();
}
interface b extends a
{
public function baz(Baz $baz);
}
// 正确写法
class c implements b
{
public function foo()
{
}
public function baz(Baz $baz)
{
}
}
// 错误写法会导致一个fatal error
class d implements b
{
public function foo()
{
}
public function baz(Foo $foo)
{
}
}
?>
Example #3 多个接口间的继承
<?php
interface a
{
public function foo();
}
interface b
{
public function bar();
}
interface c extends a, b
{
public function baz();
}
class d implements c
{
public function foo()
{
}
public function bar()
{
}
public function baz()
{
}
}
?>
Example #4 使用接口常量
<?php
interface a
{
const b = 'Interface constant';
}
// 输出接口常量
echo a::b;
// 错误写法,因为常量的值不能被修改。接口常量的概念和类常量是一样的。
class b implements a
{
const b = 'Class constant';
}
?>
HTML:
代码如下 | 复制代码 |
<link rel="stylesheet" type="text/css" href="cssmin.php?get=base,style1,style2,global&path=css/&v=20131023" /> <script type="text/javascript"" width=100% src="jsmin.php?get=jquery-1.6.4.min.js,minjquery.js,minjquery.ui.js,test.js,global.js&path=js/&v=20131023"></script> |
PHP:
代码如下 | 复制代码 |
//输出JS header ("Content-type:Application/x-javascript; Charset: utf-8"); if(isset($_GET)) { $files = explode(",", $_GET['get']); $str = ''; foreach ($files as $key => $val){ $str .= file_get_contents($_GET['path'].$val); } $str = str_replace("t", "", $str); //清除空格 $str = str_replace("rn", "", $str); $str = str_replace("n", "", $str); // 删除单行注释 $str = preg_replace("///s*[a-zA-Z0-9_x7f-xff][a-zA-Z0-9_x7f-xff]*/", "", $str); // 删除多行注释 $str = preg_replace("//*[^/]**//s", "", $str); echo $str; } //输出CSS header ("content-type:text/css; charset: utf-8"); if(isset($_GET)) { $files = explode(",", $_GET['get']); $fc = ''; foreach ($files as $key => $val){ $fc .= file_get_contents($_GET['path'].$val.".css"); } $fc = str_replace("t", "", $fc); //清除空格 $fc = str_replace("rn", "", $fc); $fc = str_replace("n", "", $fc); $fc = preg_replace("//*[^/]**//s", "", $fc); echo $fc; } |
只是个简单原型,没有封装。另外,合并后的文件记得配合缓存。
附上一个相关的开源项目:
http://code.google.com/p/minify/
很多站长都兼职卖域名(赚点小外块,不要鄙视),都希望能够在自己的网站上实现域名查询,看看域名是否可以购卖,现在我们就来讲讲用PHP+AJAX如何实现国际域名查询系统。
PHP+AJAX 域名查询预备知识
本查询系统利用 PHP 和 JQUery 的 Ajax 功能实现了对域名信息的查询(这里主要实现了域名是否已经注册的查询)。系统主要用到了万网提供的域名查询 API 接口,相关知识点罗列如下:
JQUery Ajax 的实现:这部分内容具体可以参见 JQuery API 文档或本站即将推出的《JQUery 教程》。
file_get_contents 函数:把整个文件读入一个字符串,这里用于读取一个网页(万网 API 返回结果页面)。
simplexml_load_string 函数:用于解析一个 xml 文档到对象中。
strrpos 函数:用于定位字符串第一次出现的位置,这里用来搜索关键字。
域名查询系统需求分析
根据用户输入的域名,查询该域名是否已经被注册。
对域名注册信息(whois)进行查询,该功能本教程没有实现,可以参考已有功能来实现。
页面/文件信息
domain.html:表单提交及查询结果信息显示页面。
domain_check.php:处理查询域名信息的 PHP 文件。
万网域名查询 API 接口
接口采用HTTP,POST,GET协议。
调用URL:http://panda.www.net.cn/cgi-bin/check.cgi
参数名称:area_domain 值为标准域名,例:5idev.com
调用举例:http://panda.www.net.cn/cgi-bin/check.cgi?area_domain=5idev.com
返回XML:
代码如下 | 复制代码 |
<?xml version="1.0" encoding="gb2312"?> <property> <returncode>200</returncode> <key>5idev.com</key> <original>211 : Domain name is not available</original> </property> |
XML 结果说明:
returncod:接口调用状态。
key:表示当前 check 的域名。
original:域名 check 的结果。
original 有4个结果:
210 : Domain name is available:表示域名可以注册
211 : Domain name is not available:表示域名已经被注册
212 : Domain name is invalid:表示域名参数传输错误
214 : Unknown error:表示未知错误或查询异常
domain.html 页面关键代码
domain.html 页面实现了表单 Ajax 提交及域名查询结果信息显示。完整的代码如下(注意是utf-8编码):
代码如下 | 复制代码 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1 <body> </body> |
这里利用 JAuery 实现了 Ajax GET 方式的表单提交,并对输入的表单进行了初步非空检测。
域名查询 PHP 代码
下面是完整的用于查询域名信息和回应 Ajax 请求 PHP 源代码:
代码如下 | 复制代码 |
<?php $domain = htmlspecialchars(trim($_GET['domain'])); if( !$domain ){ echo '请输入要查询的域名,如:5idev.com'; exit; } // 调用万网域名查询API $area_domain = iconv("utf-8", "gb2312",$domain); $domain_api = 'http://panda.www.net.cn/cgi-bin/check.cgi?area_domain='.$area_domain; $contents = file_get_contents($domain_api); $xml = simplexml_load_string($contents); if (!empty($xml)) { switch($xml->original) { case '210 : Domain name is available':$result = '该域名可以注册';break; case '211 : Domain name is not available':$result = '该域名已经被注册';break; case '212 : Domain name is invalid':$result = '域名参数错误,请输入的域名格式';break; case '214 : Unknown error':$result='查询异常,请稍后再试';break; } } else { // 备用,只能查询国际域名 $url = 'http://www.checkdomain.com/cgi-bin/checkdomain.pl?domain='.$_GET<'domain'>; $fp = file_get_contents($url); if( strpos($fp, ', has already been registered') ){ $result = '该域名已经被注册'; } else { $result = '该域名可以注册'; } } echo '<b>'.$domain.'</b>:'.$result; ?> |
需要注意的几个问题
支持中文域名查询。
由于域名要在页面显示,因此利用 htmlspecialchars 函数做了特殊 html 代码转换,以防止非法输入,更严格的可以使用正则表达式做检测。
由于万网接口提供的是 gb2312 编码,因此在这里利用进行了 iconv() 函数进行了编码转换,如果不使用 utf-8 编码则无需转换。
如果使用 gb2312 编码,在返回 Ajax 结果是可能需要将显示结果进行 gb2312 到 utf-8 编码的转换。
当万网接口无法返回结果时,启用备用接口进行查询,但只能查询国际域名。
当PHP运行在FastCGI模式时,PHP FPM提供了一个名为fastcgi_finish_request的方法.按照文档上的说法,此方法可以提高请求的处理速度,如果有些处理可以在页面生成完后再进行,就可以使用这个方法.
听起来可能有些茫然,我们通过几个例子来说明一下:
代码如下 | 复制代码 |
<?php echo '例子:'; fastcgi_finish_request(); /* 响应完成, 关闭连接 */ /* 记录日志 */ file_put_contents('log.txt', '生存还是毁灭,这是个问题.'); ?> |
通过浏览器访问此脚本, 结果发现并没有输出相应的字符串,但却生成了相应的文件.由此说明在调用fastcgi_finish_request后,客户端响应就已经结束,但与此同时服务端脚本却继续运行!
合理利用这个特性可以大大提升用户体验,趁热打铁再来一个例子:
代码如下 | 复制代码 |
<?php echo '例子:'; file_put_contents('log.txt', date('Y-m-d H:i:s') . " 上传视频n", FILE_APPEND); fastcgi_finish_request(); sleep(1); file_put_contents('log.txt', date('Y-m-d H:i:s') . " 转换格式n", FILE_APPEND); sleep(1); file_put_contents('log.txt', date('Y-m-d H:i:s') . " 提取图片n", FILE_APPEND); ?> |
代码里用sleep模拟一些耗时的操作,浏览时没有被堵塞,程序却都执行了,具体看日志.
末了给您提个醒,Yahoo在Best Practices for Speeding Up Your Web Site中提到了Flush the Buffer Early,也就是利用PHP中的flush方法把内容尽快发到客户端去,它和本文介绍的fastcgi_finish_request有些许的类似.
另外, 从代码的可移植性讲的话, 可以在代码中附上如下代码:
代码如下 | 复制代码 |
if (!function_exists("fastcgi_finish_request")) { function fastcgi_finish_request() { } } |
不会造成代码部署在非fpm环境下造成问题.