How can unlink () find the file to delete?
My application has a field " Photo
" to store the url. It uses sfWidgetFormInputFileEditable
widgets for the layout. To remove the old image when loading a new image, I use unlink before setting the value in the redirected setter and it works !!!
if (file_exists($this->_get('photo')))
unlink($this->_get('photo'));
- Photos are saved in files uploads / photos and when saving '
Photo
' only the filenamexxx-yyy.zzz
(not the full path) is saved . However, I want to know how does symfony / php know the full path of the file to be deleted?
Part 2: I use sfThumbnailPlugin
to create sketches. So the actual code looks like this:
public function setPhoto($value)
{
if(!empty($value))
{
Contact::generateThumbnail($value); // delete current Photo & create thumbnail
$this->_set('photo',$value); // setting new value after deleting old one
}
}
public function generateThumbnail($value)
{
$uploadDir = sfConfig::get('app_photo_upload'); // path to upload folder
if (file_exists($this->_get('photo')))
{
unlink($this->_get('photo')); // delete full-size image
// path to thumbnail
$thumbpath = $uploadDir.'/thumbnails/'.$this->get('photo');
// read a blog, tried setting dir manually, doesn't work :(
//chdir('/thumbnails/');
// tried closing the file too, doesn't work! :(
//fclose($thumbpath) or die("can't close file");
//unlink($this->_get('photo')); // doesn't work; no error :(
unlink($thumbpath); // doesn't work, no error :(
}
$thumbnail = new sfThumbnail(150, 150);
$thumbnail->loadFile($uploadDir.'/'.$value);
$thumbnail->save($uploadDir.'/thumbnails/'.$value, 'image/png');
}
- Why can't I remove a thumbnail using the unlink () function? ops sequence is incorrect? Is it because the old thumbnail is showing in the widget
sfWidgetFormInputFileEditable
?
I spent hours trying to figure this out, but couldn't cover up the real reason. Thanks in advance.
a source to share
Solved and Surprised
OK, here is the code that worked after adding some echoes ...
public function generateThumbnail($value)
{
$uploadDir = sfConfig::get('app_photo_upload'); // path to upload folder
// path to thumbnail
$thumbpath = $uploadDir.'/thumbnails/'.$this->get('photo');
if (file_exists($uploadDir.$this->_get('photo')))
{
>> unlink($uploadDir.$this->_get('photo')); // delete full-size image
>> unlink($thumbpath); // delete thumn
}
//thumbnail generation code
}
Supposedly unlink($this->_get('photo'))
never worked. Infact, the if (fileExists) block was never entered, but the file was deleted. I think it was sfWidgetFormInputFileEditable
automatically deleting the complete image when loading a new one.
Thanks Martin and Kanak
a source to share