Exoon Exoon - 4 months ago 16
PHP Question

PHP Check how old a symlink file is

I have a download script which is creating a link to a file using

symlink()
. I'm trying to create a script to delete the links after they are 1 hour old. However, when I try and check how old the file is with
filemtime()
, I just get the modification time of the actual original (target) file and not the symlink.

Here's my current code:

$filename = '/var/www/html/files/myfile.rar';

if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}


What should i do to check the last modified time of the actual symlink instead of the file?

Answer

Correct, filemtime() and stat() will follow symlinks, but lstat() will not.

This function is identical to the stat() function except that if the filename parameter is a symbolic link, the status of the symbolic link is returned, not the status of the file pointed to by the symbolic link.

For example:

<?php

function getSymlinkMtime($symlinkPath)
{
    $stat = lstat($symlinkPath);

    return isset($stat['mtime']) ? $stat['mtime'] : null;
}

could be used in place of filemtime().

Your full example, in that approach, would be:

<?php

$filename = '/var/www/html/files/myfile.rar';

if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", getSymlinkMtime($filename));
}
Comments