2013-03-03 113 views
0

我设置了一个配置文件的网站,该网站将使用parse_ini_file方法来读取。其中一个选项是某些操作之前的秒数。我试着将该值设置为60*60*24*3拿到秒3天的价值:处理中的.ini设置的时间间隔的文件

[mailer] 
; Number of seconds before trial expiration an email should be sent 
seconds  = 60*60*24*3; 

但变量只是读入PHP作为字符串“60 * 60 * 24 * 3”。出于安全原因,我不想使用eval。有没有什么办法可以让这个(a)更容易使用,(b)更直观的阅读比简单地列出给定日期的秒数?

+0

你怎么打算知道每个地方*可能*需要处理的INI发起的设置?通过dint,INI文件通常是一组有限的键和值集。所以感觉这些值应该是预先计算出来的(您已经在设置的上面注释中指出了这些值)。这就是说,有[bcMathParser](http://www.bestcode.com/math-parser-php-docs/)。 – 2013-03-03 16:40:35

+0

@JaredFarrish - 我知道,因为我是写它的人。我会指定哪些条目可以被“处理”,哪些条目不会。 – eykanal 2013-03-03 16:44:40

+0

似乎可能有很多麻烦和“脆弱”(对我来说)手动操作很容易。我的意见,当然。 – 2013-03-03 16:51:17

回答

-1

重命名您的INI到PHP和写这样

# Number of seconds before trial expiration an email should be sent 
$cfg['somesection']['someparam'] = 'foo'; 
... 
$cfg['mailer']['seconds'] = 60*60*24*3; 

或使用屏幕计算器做数学和粘贴结果作为值。

+1

这可能是一个很好的解决方法,但它并没有真正回答这个问题。 – eykanal 2013-03-03 16:33:07

1

您可以使用supported date and time formats使人类可读的字符串,然后可将其用于以秒来初始化和计算差值:

$diff = "3 days 5 hours 10 seconds"; 
$now = strtotime('2010-04-01 00:00:00'); // No leap year funny business 
$then = strtotime($diff, $now); 
$diff = $then - $now; 

echo " 
Now: " . date('r', $now) . " 
Then: " . date('r', $then) . " 
Diff (seconds): $diff"; 

https://ignite.io/code/51338967ec221e0d3b000000

注:约闰年的关注是否会正确计算秒数(添加/删除一天?)。如果可以的话,应该单独测试。

以上输出:

Now: Thu, 01 Apr 2010 00:00:00 +0000 
Then: Sun, 04 Apr 2010 05:00:10 +0000 
Diff (seconds): 277210 

那么这将让你做的事:

[mailer] 
; Period before trial expiration an email should be sent. 
; Use PHP-supported time statements in an expression to 
; specify an interval, such as 3 days, or 72 hours, etc. 
; See: http://www.php.net/manual/en/datetime.formats.php 
expires  = 3 days; 

正如我在评论中指出,你也可以使用DateTimeInterval::createFromString()DateTime::diff做同样的事情。

我会注意到,以及是获取字符串格式正确,但并不难,有时会比你想象的复杂。对于简单的字符串像3 days这并不难,但是3d工作。这样计算时间应进行验证,并提供给个人设置,如果输入的内容配置错误是不是一个有效的表达式,或者是“越界”到什么预期(过去也许?)。