Home » Php » php – Renaming a 900kb pdf file takes long time

php – Renaming a 900kb pdf file takes long time

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am trying to rename() a 900 KiB PDF file in PHP. It is taking a long time to rename it for some reason. I thought it should be instant.

This is on a CentOS server. While the file is being renamed I can get properties and it seems like rename() is copying and replacing the old file with new renamed file.

The old name and new name paths are in the same directory.

Has anyone stumbled upon this issue before?


Code:

    //If exists change name and then return path
    $pieces = explode("@", $filename);
    $newName = $pieces[0].' '.$pieces[2];

    rename($uidPath.$filename, $uidPath.$newName);

    if (preg_match('/pdf/', $pieces[2]))
    {
        $result['status'] = '1';
        $result['path'] = 'path to file';
    } 
    else 
    {
        $result['status'] = '1';
        $result['path'] = 'path to file';
    }
How to&Answers:

PHP is for some reason very slow to release file lock on fclose(), so if you are writing to the file prior to moving it you might have to wait for a bit. I’ve had this very problem with a low priority background job, so I didn’t really look into why this happens or what I can do to prevent it – I just added 1 second sleep between fclose() and rename.