Search code examples
phpzend-frameworkdelete-fileunlink

Intermittent unlink not functioning


The below code allows me to delete files SOMETIMES. I have checked permissions on the files and folders and they exist and are given proper access. Sometimes when I press the remove button; it removes the file and sometimes it simply refreshes the page and nothing happens. Is there anything I can do to make unlink work correctly? Am I missing something in the code below? This is in ZEND.

public function delimageAction()
{
    $request = $this->getRequest();

    if ($request->isPost()) {
        // Get the image name
        $imageName = $request->getParam('file');

        $old = getcwd();
        chdir(APPLICATION_PATH . "/../public/images/blog/"); // Change directory to the files
        fclose(APPLICATION_PATH . "/../public/images/blog/" . $imageName);

        // Delete it
        unlink(APPLICATION_PATH . "/../public/images/blog/" . $imageName)

        chdir($old); // Return to old directory
    }
    $this->_helper->redirector('blog', 'index');
}

Solution

  • Remove the two chdir calls since they serve no purpose, and the fclose which will result in an error. Beyond that you need to check the error log to see what is causing the deletion to fail, it could be permissions related. You could also check the return value for unlink, since it should return false if it doesn't work.

    As hinted in the comments, there is quite a big security hole in your script as it allows a malicious user to delete any file in your application. You need to sanitise the 'file' param to ensure the path supplied is within the public/images/blog/ folder.