Exoon
Exoon

Reputation: 1553

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?

Upvotes: 3

Views: 1266

Answers (3)

maxhb
maxhb

Reputation: 8865

Use PHP function lstat():

$stat = lstat('/var/www/html/files/myfile.rar');
print_r($stat);

Gives you loads of information like atime (last access), ctime (time created) and mtime (last modify).

Upvotes: 2

Will
Will

Reputation: 24709

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));
}

Upvotes: 3

Viktor
Viktor

Reputation: 51

Probably, you can't get attributes of symlink. You can create file where you can store the information about link.

Upvotes: -4

Related Questions