DeleteAction.php
1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace thread\actions\fileapi;
use Yii;
use yii\base\Action;
use yii\helpers\FileHelper;
use yii\web\Response;
/**
* Class DeleteAction
*
* @package thread\actions\fileapi
* @author FilamentV <vortex.filament@gmail.com>
* @copyright (c), Thread
*/
class DeleteAction extends Action
{
/**
* @var string Path to directory where files has been uploaded
*/
public $path;
/**
*
* @var string
*/
public $paramName = 'key';
/**
*
* @var array
*/
public $thumb = [];
/**
*
*/
public function init()
{
//default path
if ($this->path === null) {
$this->path = Yii::getAlias('@temp');
}
$this->path = FileHelper::normalizePath($this->path) . DIRECTORY_SEPARATOR;
}
/**
* @return array
*/
public function run()
{
$error = 'file don\'t exist';
if (($file = Yii::$app->getRequest()->post($this->paramName))) {
$filename = FileHelper::normalizePath($this->path . '/' . $file);
if (is_file($filename)) {
$error = (unlink($filename)) ? 'file deleted' : 'can not delete file';
}
//delete thumb
if (!empty($this->thumb)) {
foreach ($this->thumb as $thumb) {
$filename = FileHelper::normalizePath($this->path . '/' . $thumb . $file);
if (is_file($filename)) {
unlink($filename);
}
}
}
}
if (Yii::$app->getRequest()->isAjax) {
Yii::$app->getResponse()->format = Response::FORMAT_JSON;
}
$result = ['error' => $error];
return $result;
}
}