dtbiszu7724 2018-03-28 10:36
浏览 178
已采纳

PHP 7.1“require / include”结果不是最新的

I have a file containing:

<?php
    return '2000-01-01 00:00:00';
?>

and I have this code:

<?php

    $oldValue = require 'file.php';
    $now = new DateTime();
    $handle = fopen('file.php', "w");
    fputs($handle, "<?php
return '" . $now->format('Y-m-d H:i:s') . "';");
    fclose($handle);
    $newValue = require 'file.php';

    echo "Old value: $oldValue ";
    echo "New value: $newValue ";
?>

The output with PHP 5.3 is:

Old value: 2000-01-01 00:00:00 New value: 2018-03-28 10:33:12

The output with PHP 7.1 is:

Old value: 2000-01-01 00:00:00 New value: 2000-01-01 00:00:00

In the two cases, the string in the file changes.

Can some one help me to update the new value with PHP 7.1?

Note: it's not the real problem. It's just an abstraction of the problem to make things more simple and comprehensible. So please, no lessons of PHP best practices. I just like to get a good response to my question.

Thanks :)

  • 写回答

2条回答 默认 最新

  • douzhang7728 2018-03-28 11:05
    关注

    As commented by iainn The issue is that the PHP server is caching the file once it's loaded and is not re-calling the file from disc on the second require, instead calling it from it's memory cache.

    As you have stated that:

    "the content of the file changes "

    then the issue is the new contents are not passed to the script, instead using the memory of the older contents.

    Therefore call clearstatcache() to force clear the cached file data. This should be placed after the new data is written to update the file, and before the file is called for a second time.

    If this does not work then the file data may be cached elsewhere in its route.

    <?php
    
        $oldValue = require 'file.php';
        $now = new DateTime();
        $handle = fopen('file.php', "w");
        fputs($handle, "<?php
    return '" . $now->format('Y-m-d H:i:s') . "';");
        fclose($handle);
        clearstatcache();           // THIS line should help you 
        $newValue = require 'file.php';
    
        echo "Old value: $oldValue ";
        echo "New value: $newValue ";
    ?>
    

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?