在afterDelete()中删除文件 - CakePHP

时间:2011-06-01 10:23:11

标签: php file cakephp delete-file

我有一个上传模型 - 包含用户上传的图片。

在控制器内,我正在打电话:

$this->Upload->delete($id);

从数据库中删除记录的工作正常,但我也想删除相应的图像文件。

我用不同的变量尝试了很多不同的东西..等等,并找到了this link类似的问题,但是 - 似乎什么都没有用 - 我甚至无法用任何变量删除它这些尝试:

//at the bottom of my Upload model
function afterDelete() {
    //NONE OF THESE WORK - is this even being called?
    unlink('/img/uploads/rest_logo.jpg');
    unlink('app/webroot/img/uploads/rest_logo.jpg');
    unlink('/app/webroot/img/uploads/rest_logo.jpg');
    unlink('img/uploads/rest_logo.jpg');
    unlink(WWW_ROOT . 'img/uploads/rest_logo.jpg');
    unlink(WWW_ROOT . '/img/uploads/rest_logo.jpg');
    return true;
}

显然我想把它改成动态文件名,但是现在,我甚至无法在硬编码我能想到的所有不同路径时删除它。

有没有办法测试这里发生了什么?像回声或......什么?

非常感谢任何帮助或指示。

5 个答案:

答案 0 :(得分:14)

App::uses('File', 'Utility');

// new File(string $path, boolean $create = false, integer $mode = 493) 
// $mode  = 493 default

$file = new File(WWW_ROOT . 'img/uploads/rest_logo.jpg', false, 0777);
if($file->delete()) {
   echo 'image deleted.....';
}

Detail about File Utility

答案 1 :(得分:2)

我尝试删除afterDelete()中的文件并没有发现任何问题..它对我有用..

    function afterDelete() {
        if(unlink(WWW_ROOT."/img/uploads/2.png")) {
            echo "Successful";
        }
        else echo "Unsuccessful";
}

我不知道您的代码有什么问题...也许您的问题是如何删除其记录后删除相同的文件。为此,您可以使用beforeDelete()函数将图像名称存储在某个变量中,然后在afterDelete()中使用它。

答案 2 :(得分:1)

这是我使用的afterDelete,它在我的项目中完美运行,尝试并看到:

public function afterDelete() {
    $file = new File($this->data['MyModel']['file_path']);
    $file->delete();
}

答案 3 :(得分:0)

我假设你不能使用debug或普通的echo print_r($ val,1);.您可以使用php mail()函数向自己邮寄此代码的结果:

$perms = fileperms('/the/path/the_file.ext');

它应该像0755.

你也可以回应所有这些并放置一个骰子('死!');在函数的最后,看看会发生什么。 无论哪种方式,如果你没有收到电子邮件或执行停止,就会出现问题。

顺便说一句,这可能是正确的道路:取消链接(WWW_ROOT。'img / uploads / rest_logo.jpg');

答案 4 :(得分:-2)

我打算给你解决方案。最后你可以看到我使用unlink()函数,我可以向你保证它是有效的。

我在Component中使用this函数和另一组ImageFunction

function getImageAbsolutePath( $upload_id ){
    //To use the model in the Component
    $this->Upload = ClassRegistry::init('Upload');

    $options = array(
        'conditions' => array(
            'Upload.id' => $upload_id
        )
    );

    $upload = $this->Upload->find( 'first', $options );

    if( isset( $upload['Upload'] ) && $upload['Upload']['id'] > 0 ){
        $imgPath = WWW_ROOT . "files" . DS . "uploads" . DS . $upload['Upload']['name'];
    }else{
        $imgPath = "";
    }

    return $imgPath;

}

在控制器中

        $filePath = $uploadComponent->getImageAbsolutePath( $id );

        if( $filePath != '' && file_exists( $filePath ) ){
            if ($this->Upload->delete($id)) {
                unlink($filePath);
            }
        }