How can I prevent the same file being included twice when using hardlinks?

65 Views Asked by At

How can I prevent the same file being included twice? Here is my source code:

<?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();

I receive:

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

It's not working with realpath because it just returns the path of the link, not the target. I've tried with readlink but unfortunately that only works for symlinks.

1

There are 1 best solutions below

0
On

I have a working solution. It's not ideal but for a quick fix it will do, until I am able to make sure the same files are never included twice:

<?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();

Thanks to BugFinder for suggesting I use fileinode.