php - file_get_contents 得到错误的结果

标签 php nginx caching file-get-contents symlink

更新

我解决了问题并发布了答案。但是,我的解决方案并不是 100% 理想。我宁愿只使用 clearstatcache(true, $target)clearstatcache(true, $link) 从 cache 中删除 symlink ) 但这不起作用。

我也宁愿首先阻止符号链接(symbolic link)的缓存,或者在生成符号链接(symbolic link)后立即从缓存中删除符号链接(symbolic link)。不幸的是,我没有那么幸运。由于某种原因,创建符号链接(symbolic link)后 clearstatcache(true) 不起作用,但它仍然会被缓存。

我很乐意将赏金奖励给任何可以改进我的answer的人。并解决这些问题。

编辑

我尝试通过每次运行 clearstatcache 时生成一个文件来优化我的代码,这样我只需要为每个符号链接(symbolic link)清除一次缓存。由于某种原因,这不起作用。每次路径中包含 symlink 时都需要调用 clearstatcache,但为什么呢?一定有一种方法可以优化我的解决方案。

<小时/>

我正在使用 PHP 7.3.5nginx/1.16.0。有时,使用符号链接(symbolic link)时,file_get_contents会返回错误的值。问题是删除并重新创建符号链接(symbolic link)后,其旧值仍保留在缓存中。有时返回正确的值,有时返回旧值。它看起来是随机的。

我尝试清除缓存或阻止缓存:

function symlink1($target, $link)
{
    realpath_cache_size(0);
    symlink($target, $link);
    //clearstatcache(true);
}

我真的不想禁用缓存,但我仍然需要 file_get_contents 达到 100% 的准确性。

编辑

我无法发布我的源代码,因为它太长且复杂,因此我创建了一个最小的、可重现的示例(index.php)来重现问题:

<h1>Symlink Problem</h1>
<?php
    $dir = getcwd();
    if (isset($_POST['clear-all']))
    {
        $nos = array_values(array_diff(scandir($dir.'/nos'), array('..', '.')));
        foreach ($nos as $no)
        {
            unlink($dir.'/nos/'.$no.'/id.txt');
            rmdir($dir.'/nos/'.$no);
        }
        foreach (array_values(array_diff(scandir($dir.'/ids'), array('..', '.'))) as $id)
            unlink($dir.'/ids/'.$id);
    }
    if (!is_dir($dir.'/nos'))
        mkdir($dir.'/nos');
    if (!is_dir($dir.'/ids'))
        mkdir($dir.'/ids');
    if (isset($_POST['submit']) && !empty($_POST['id']) && ctype_digit($_POST['insert-after']) && ctype_alnum($_POST['id']))
    {
        $nos = array_values(array_diff(scandir($dir.'/nos'), array('..', '.')));
        $total = count($nos);
        if ($total <= 100)
        {
            for ($i = $total; $i >= $_POST['insert-after']; $i--)
            {
                $id = file_get_contents($dir.'/nos/'.$i.'/id.txt');
                unlink($dir.'/ids/'.$id);
                symlink($dir.'/nos/'.($i + 1), $dir.'/ids/'.$id);
                rename($dir.'/nos/'.$i, $dir.'/nos/'.($i + 1));
            }
            echo '<br>';
            mkdir($dir.'/nos/'.$_POST['insert-after']);
            file_put_contents($dir.'/nos/'.$_POST['insert-after'].'/id.txt', $_POST['id']);
            symlink($dir.'/nos/'.$_POST['insert-after'], $dir.'/ids/'.$_POST['id']);
        }
    }
    $nos = array_values(array_diff(scandir($dir.'/nos'), array('..', '.')));
    $total = count($nos) + 1;
    echo '<h2>Ids from nos directory</h2>';
    foreach ($nos as $no)
    {
        echo ($no + 1).':'.file_get_contents("$dir/nos/$no/id.txt").'<br>';
    }
    echo '<h2>Ids from using symlinks</h2>';
    $ids = array_values(array_diff(scandir($dir.'/ids'), array('..', '.')));
    if (count($ids) > 0)
    {
        $success = true;
        foreach ($ids as $id)
        {
            $id1 = file_get_contents("$dir/ids/$id/id.txt");
            echo $id.':'.$id1.'<br>';
            if ($id !== $id1)
                $success = false;
        }
        if ($success)
            echo '<b><font color="blue">Success!</font></b><br>';
        else
            echo '<b><font color="red">Failure!</font></b><br>';
    }
?>
<br>
<h2>Insert ID after</h2>
<form method="post" action="/">
    <select name="insert-after">
        <?php
            for ($i = 0; $i < $total; $i++)
                echo '<option value="'.$i.'">'.$i.'</option>';
        ?>
    </select>
    <input type="text" placeholder="ID" name="id"><br>
    <input type="submit" name="submit" value="Insert"><br>
</form>
<h2>Clear all</h2>
<form method="post" action="/">
    <input type="submit" name="clear-all" value="Clear All"><br>
</form>
<script>
    if (window.history.replaceState)
    {
        window.history.replaceState( null, null, window.location.href );
    }
</script>

这似乎很可能是 Nginx 配置出现问题。没有这些行可能会导致问题:

fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;

这是我的 Nginx 配置(您可以看到我已包含以上几行):

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name www.websemantica.co.uk;
    root "/path/to/site/root";
    index index.php;

    location / {
        try_files $uri $uri/ $uri.php$is_args$query_string;
    }

    location ~* \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_param   QUERY_STRING            $query_string;
        fastcgi_param   REQUEST_METHOD          $request_method;
        fastcgi_param   CONTENT_TYPE            $content_type;
        fastcgi_param   CONTENT_LENGTH          $content_length;

        fastcgi_param   SCRIPT_FILENAME         $realpath_root$fastcgi_script_name;
        fastcgi_param   SCRIPT_NAME             $fastcgi_script_name;
        fastcgi_param   PATH_INFO               $fastcgi_path_info;
        fastcgi_param   PATH_TRANSLATED         $realpath_root$fastcgi_path_info;
        fastcgi_param   REQUEST_URI             $request_uri;
        fastcgi_param   DOCUMENT_URI            $document_uri;
        fastcgi_param   DOCUMENT_ROOT           $realpath_root;
        fastcgi_param   SERVER_PROTOCOL         $server_protocol;

        fastcgi_param   GATEWAY_INTERFACE       CGI/1.1;
        fastcgi_param   SERVER_SOFTWARE         nginx/$nginx_version;

        fastcgi_param   REMOTE_ADDR             $remote_addr;
        fastcgi_param   REMOTE_PORT             $remote_port;
        fastcgi_param   SERVER_ADDR             $server_addr;
        fastcgi_param   SERVER_PORT             $server_port;
        fastcgi_param   SERVER_NAME             $server_name;

        fastcgi_param   HTTPS                   $https;

        # PHP only, required if PHP was built with --enable-force-cgi-redirect
        fastcgi_param   REDIRECT_STATUS         200;

        fastcgi_index index.php;
        fastcgi_read_timeout 3000;
    }

    if ($request_uri ~ (?i)^/([^?]*)\.php($|\?)) {
        return 301 /$1$is_args$args;
    }
    rewrite ^/index$ / permanent;
    rewrite ^/(.*)/$ /$1 permanent;
}

目前我在https://www.websemantica.co.uk上有上面的例子.

尝试在表单中添加一些值。每次都应该以蓝色显示 Success!。有时会以红色显示 Failure!。可能需要多次页面刷新才能从 Success! 更改为 Failure!,反之亦然。最终,每次都会显示 Success!,因此一定存在某种缓存问题。

最佳答案

这太依赖操作系统级别了。那么,尝试跳出框框思考怎么样?尝试通过readlink读取文件的真实位置,并使用该真实位置路径怎么样?

$realPath = shell_exec("readlink " . $yourSymlink);
$fileContent = file_get_contents($realPath);

关于php - file_get_contents 得到错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58712126/

相关文章:

ruby-on-rails - 缓存Rails Assets 时的NGinX权限问题

java - cachingHttpclient 不能忽略 header "Cache-Control: no-cache"

php - 如何从父选择 PHP 填充子下拉菜单

php, date() 没有返回正确的日期/时间

ruby-on-rails - Rails 部署 : 4 small servers or 1 big server?

swift - 如何将值附加到字典内的字典中(Swift 4)

ruby-on-rails - Elasticache redis 缓存未命中但 key 存在。

php - xdebug 配置显示错误版本的 php

php - Cakephp3将多个Mysql表标准化为1个模型表/实体

linux - Nginx : the rule( location =/) in server context do not work