【问题标题】:Dates and Math in PHPPHP 中的日期和数学
【发布时间】:2014-02-27 20:12:56
【问题描述】:

我授权网站的付费会员在 30 天内与非会员分享优质内容。这是我想要完成的任务:

首先,订阅者填写表格以生成发送给好友的电子邮件,该电子邮件会生成内容登录页面的 URL。因为我不希望他们轻易能够操纵它,所以我所做的只是将一个 base64 编码的日期附加到着陆页 URL。

$url = "http://www.example.com/video_landing_page.php?" . base64_encode(date('Y-m-d'));

收件人会收到一个类似于http://www.example.com/video_landing_page.php?MjAxNC0wMi0yNg==的链接

在登录页面上,我解析了 url 以获取查询并对其进行解码:

$url = $_SERVER['PHP_SELF'];
$url_components = parse_url($url);
$query = $url_components['query'];
$decodedQuery = base64_decode($query);

现在,如果自创建 url 30 天后,我想显示一条错误消息,这就是我卡住的地方。我已经尝试过这样但没有得到我需要的东西:

if ((strtotime($decodedQuery) + strtotime('+30 Days')) > date('Y-m-d){
    Display error Message
} else {
    Display Success Message
} 

但计算出来的结果并不正确。有任何想法吗?或者有没有更好的方法来做到这一点?

【问题讨论】:

    标签: php base64 strtotime date-math


    【解决方案1】:

    您正在使用可以轻松操作base64(),而是在您的数据库中存储一个唯一的id,存储创建记录的日期。现在使用id 来创建 url 而不是使用日期,也将为每条记录节省几个字节。

    现在当用户访问时,使用唯一的id 从数据库中获取日期并使用strtotime() 与当前时间进行比较。


    例如...假设X先生得到一个类似的URL

    http://demo.com/landingpage.php?uid=454566
    

    landingpage.php 使用..

    $store_id = (isset($_GET['uid'])) ? $_GET['uid'] : ''; 
    // Validate, fetch the row from DB and count, if not 1 than throw error, 
    // if it returns one than go ahead
    
    // Or you can use INTERVAL 30 DAY < NOW() if you want MySQL to do the job for you
    // Than just compare the row count.. or if you want to do with PHP
    
    if(strtotime($fetched_db_time) < strtotime('-30 days')){
        //Record is 30 days older
    }
    

    您也可以通过将数字替换为字母来为此创建自己的散列机制,但最好使用唯一 ID 概念,因为您不必在丢失编码的情况下泄露 url 中的数据。

    【讨论】:

      【解决方案2】:

      有什么想法吗?

      您正在将 Unix 时间戳记与字符串进行比较。这行不通(如你所料)。

      if ((strtotime($decodedQuery) + strtotime('+30 Days')) > date('Y-m-d){
      

      应该是:

      if ((strtotime($decodedQuery) + strtotime('+30 Days')) > time()){
      

      这会比较两个 Unix 时间戳。

      或者有没有更好的方法来实现这一点?

      是的。使用DateTime(),因为它们是可比的:

      $now = new DateTime();
      $inOneMonth = new DateTime($decodedQuery);
      $inOneMonth->modify('+1 month');
      if ($inOneMonth > $now){
      

      【讨论】:

        【解决方案3】:
        1. (strtotime($decodedQuery) + strtotime('+30 Days') 结果到当前日期加上 30 天(以秒为单位)加上解码查询的时间(以秒为单位)。
        2. 您将自纪元以来的秒数与字符串进行比较

        【讨论】:

          【解决方案4】:

          试试,

          if (strtotime($decodedQuery) < strtotime('-30 Days')) {
           //$decodedQuery is more than 30 days in the past
          }
          

          【讨论】:

            【解决方案5】:

            试试

            if(strtotime($decodedQuery.' + 30 Days')  > date('Y-m-d) )
            

            但是,base64 很弱

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2010-09-24
              • 2023-01-25
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多