i have a function to upload new and update images for a profile. What i am looking for now is a function to delete the ‘old’ image, after update or if the user wants to delete his profile image.
I cannot find any function in the api to delete a file…
I tried to delete the files as you suggest using unlink and got following error.
unlink(/Users/monaye/Dropbox/website/umenoki-yii/protected/../images/) [<a href='function.unlink'>function.unlink</a>]: Operation not permitted
This is my actionUpdate
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
$model->patientPic=CUploadedFile::getInstance($model,'patientPic');
if(isset($_POST['Patients']))
{
$model->patientPic=CUploadedFile::getInstance($model,'patientPic');
if($model->save()) {
$imageName = Patients::model()->find('ID=?',"$model->ID");
unlink(Yii::app()->basePath."/../images/".$imageName);
$model->patientPic->saveAs(Yii::app()->basePath."/../images/".$model->patientPic->name);
$this->redirect(array('view','id'=>$model->ID));
}
}
$this->render('update',array(
'model'=>$model,
));
}
Looks like you are trying to delete a directory. Check the $imageName value before unlink and make sure you have write permissions for images directory.
I was able to make it work. Code is not pretty, so I myself not really satisfied. Please let me know if you have cleaner and simpler way to achieve this.
Also, I am more of JS guy and get used to Firebug’s console.log to get value of $valuable but not sure hot to do it in yii. I usually just echo out $valuable but not working within actionUpdate function.
Thank you for the help.
public function actionUpdate($id)
{
$model=$this->loadModel($id);
if(isset($_POST['Patients']))
{
// Define image's location
$imageLocation = Yii::app()->basePath."/../images/";
// query table where ID = currnet ID
$patientInfo = Patients::model()->find("ID = ".$model->ID);
// if patientPic(image) field in table is not empty
// delete images
if(!empty($patientInfo->patientPic)){
unlink($imageLocation.$patientInfo->patientPic);
}
// get fileuploaded info
$imageInfo = CUploadedFile::getInstance($model,'patientPic');
// replace all space in file name with _
$imageName = str_replace(" ","_",$imageName->name);
// Adding yearmonthdate_time to file name
$imageName = date("Ymd_Gi")."_".$imageName;
// ready to update database with new filename
$model->patientPic=$imageName;
if($model->save()) {
// can't use $imageName since it only contain file name
// saveAs need $imageInfo -> tempName
$imageInfo->saveAs($imageLocation.$imageName);
$this->redirect(array('view','id'=>$model->ID));
}
}
$this->render('update',array(
'model'=>$model,
));
}