Answer the question
In order to leave comments, you need to log in
How to delete a file from the server?
Hello!
I ran into such a problem: I have files that I added to the folder myself and they are safely deleted using actionDeletephoto, but if I upload a file using actionCreatephoto, then only the entry from the database is deleted, and the file remains on the server. Please, tell me how to solve this problem.
Controller:
protected function findPhoto($id)
{
if(($model=Photo::findOne($id))!==null)
{
return $model;
}
else{
throw new NotFoundHttpException('The requested page does not exits.');
}
}
public function actionDeletephoto($id)
{
$photo=$this->findPhoto($id);
if(file_exists(\Yii::getAlias('@frontend').'/web/img/image/'.$photo->name))
{unlink(\Yii::getAlias('@frontend').'/web/img/image/'.$photo->name);}
$photo->delete();
return $this->redirect(['photo']);
}
public function actionCreatephoto()
{
$model = new FileUploud();
$photo = new Photo();
if($model->load(Yii::$app->request->post()))
{
$file=UploadedFile::getInstance($model,'file');
$model->uploadFile($file);
$photo->saveImage($model->uploadFile($file));
}
return $this->render('createphoto', [
'model' => $model,
'photo' => $photo,
]);
}
class FileUploud extends Model
{
public $file;
public function uploadFile(UploadedFile $files)
{
$this->file=$files;
$filename=strtolower(md5(uniqid($files->baseName)).'.'.$files->extension);
$files->saveAs(\Yii::getAlias('@frontend').'/web/img/image/'.$filename);
return $filename;
}
Answer the question
In order to leave comments, you need to log in
Feel sorry for disk space?) Send files to AWS s3 and store it all there for a penny. And you don't have to delete anything.
Use events
https://www.yiiframework.com/doc/api/2.0/yii-db-ba...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question