【问题标题】:How can I prevent the same file being included twice when using hardlinks?使用硬链接时,如何防止同一文件被包含两次?
【发布时间】:2020-04-06 11:26:32
【问题描述】:

如何防止同一个文件被包含两次?这是我的源代码:

<?php

error_reporting(-1);
ini_set('display_errors', 'On');
ini_set('html_errors', 0);

if (!file_exists('ccc.php'))
    link('bbb.php', 'ccc.php');
if (!file_exists('ddd.php'))
    link('bbb.php', 'ddd.php');
require_once realpath('ccc.php');
require_once realpath('ddd.php');

$bbb = new Bbb();
echo $bbb->bb();

我收到:

Fatal error: Cannot declare class Bbb, because the name is already in use in /path/to/ddd.php on line 2

它不适用于realpath,因为它只返回链接的路径,而不是目标。我试过readlink,但不幸的是这只适用于符号链接。

【问题讨论】:

  • 你可以用 ls -i 获取inode,看看它是否已经被你使用了?
  • @BugFinder 这不会导致性能问题吗?当然,必须有一种方法可以在不使用exec 的情况下获取php 中的链接目标。
  • 好吧php.net/manual/en/function.fileinode.php 似乎也这样做了......
  • 我正在尝试找到一种方法来反转fileinode,以便我收到链接的目标但没有运气。
  • 我不认为你可以。硬链接隐藏可见性,我记得软链接有一个计数器..

标签: php hyperlink realpath readlink


【解决方案1】:

我有一个可行的解决方案。这并不理想,但可以快速修复它,直到我能够确保相同的文件永远不会包含两次:

<?php

error_reporting(-1);
ini_set('display_errors', 'On');
ini_set('html_errors', 0);

if (!file_exists('ccc.php'))
    link('bbb.php', 'ccc.php');
if (!file_exists('ddd.php'))
    link('bbb.php', 'ddd.php');

function includeFile($fileName)
{
    foreach (get_included_files() as $file)
    {
        if (fileinode($file) === fileinode($fileName))
            return null;
    }
    require_once $fileName;
}
includeFile('ccc.php');
includeFile('ddd.php');

$bbb = new Bbb();
echo $bbb->bb();

感谢BugFinder 建议我使用fileinode

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-08
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    相关资源
    最近更新 更多