Removing an image from server - php

I am trying to delete the images from the server using unlink() function. This is deleting the image name from the database, but the image is not deleted from the server, what am i doing wrong?
public function actionDelete()
{
if(Yii::$app->request->isAjax)
{
$id = $_POST['id'];
$product=Product::find()->where(['id'=>$id])->one()->delete();
$delete=CategoryProduct::find()->where(['product_id'=>$id])->all();
foreach($delete as $del)
{
$del->delete();
}
$imgfile="<?php echo Yii::$app->request->baseUrl;?>/web/assets/uploads/<?php echo $product->image;?>";
unlink($imgfile);
echo json_encode(TRUE);die;
}
echo json_encode(FALSE);die;
}

Its is best to set an alias for the upload path (best place will be config/bootstrap.php)so that we can have standard name to all the upload folder. i.e
Yii::setAlias('image_uploads', dirname(dirname(__DIR__)) . '/web/assets/uploads');
You can use the same for saving and deleting the file.
Saving will be like
move_uploaded_file($tmp_file, \Yii::getAlias('#image_uploads/products/') . $product->image);
or
You can use Yii Methods i.e for e.g.
$this->imageFile->saveAs($orignal_file_full_path); // where imageFile in input type file
Deleting will be something like:
unlink (\Yii::getAlias('#image_uploads/products/') . $product->image);
the Core idea is to use real paths for deleting and saving rather then URLs

Related

Laravel 5.5 get file after uploading with Storage

In my Laravel 5.5 project I am having a problem in showing uploaded files. I uploaded the files using Storage. The part of store action of the controller is indicated below.
if ($request->hasFile('content_uz'))
{
$path = $request->file('content_uz')->store('/content/lesson'.$topic->lesson->id.'/topic'.$topic->id);
$data->content_uz = $path;
}
if ($request->hasFile('content_ru'))
{
$path = $request->file('content_ru')->store('/content/lesson'.$topic->lesson->id.'/topic'.$topic->id);
$data->content_ru = $path;
}
Uploading happened successfully. The path to uploaded 'content_uz' file is stored with "storage/app/content/lesson2/topic3" path and content_uz column is stored in my db as below:
content\lesson2\topic3\WSjrlG9a1ermGDOvRJTjn9iEIhfFvhVzjaOs6l79.mp4
How can I display the files in my Blade template? I searched the web, but with no result.
You can use method like this,
public function showFile() {
header("Content-type: video/mp4");
return Storage::get($filePath);
}
I hope this will help.
You may access the files of storage directory by two ways.
If your files are publicly accessible then you may follow laravel public disk.
If your files are protected or private then you may declare a route to access the files.
Route::get('content/{lesson}/{topic}/{file}', function($lesson, $topic, $file)
{
//Check access logic
$filePath = '/content/' . $lesson . '/' . $topic . '/' . $file;
return Storage::get($filePath);
});

How to Delete Images from Public/Images Folder in laravel 5 (URL Data)

how to delete images file from public/images folder in laravel 5 ??
i found some example from this site, but i know they are just using the file name in their record table, but i'm using something like URL e.g localhost/project/uploads/filename.jpg on my record table. so if i tried like this :
$image_path = $data->image; // the value is : localhost/project/image/filename.format
if(File::exists($image_path)) {
File::delete($image_path);
}
the file is not deleted
help pls, thanks
If you want to delete image from your server, you have to reference location of file in directory server, means you could not reference by url link to delete it.
Commonly, Laravel 5 file is locate in public folder.
Example: your files are located in public/images
$image_path = "/images/filename.ext"; // Value is not URL but directory file path
if(File::exists($image_path)) {
File::delete($image_path);
}
If I can delete image from server by reference URL then Google is the first target :)
You can use the normal PHP delete file keyword ( #unlink )
$image_path = "the name of your image path here/".$request->Image;
if (file_exists($image_path)) {
#unlink($image_path);
}
This is what I do to delete an image:
public function SliderDelete(String $slider_id)
{
$slider = Slider::findOrFail($slider_id);
$image_path = public_path("\storage\images\sliders\\") .$slider->photo;
if(File::exists($image_path)) {
File::delete($image_path);
}
else{
$slider->delete();
//abort(404);
}
$slider->delete();
return response()->json(['success'=>'Slider deleted successfully!']);
}
in laravel 8 you do it like
// import Storage class
use Illuminate\Support\Facades\Storage;
Storage::disk('public')->delete('path-of-file');
you can use disk of your choice like
Storage::disk('s3')->delete('path-of-file');
$filename = public_path($fileloc);
if(File::exists($filename)) {
File::delete($filename);
}
call this function and pass two parameter
$filepath = path where your file exist
$filename = name of your file
public static function UnlinkImage($filepath,$fileName)
{
$old_image = $filepath.$fileName;
if (file_exists($old_image)) {
#unlink($old_image);
}
}
public function destroy($id)
{
$imagePath = YourModelName::select('image')->where('id', $id)->first();
$filePath = $imagePath->image;
if (file_exists($filePath)) {
unlink($filePath);
YourModelName::where('id', $id)->delete();
}else{
YourModelName::where('id', $id)->delete();
}
}
To be able to delete the image it should be in the following form :
"/uploads/img1.jpg" where uploads directory is in the public directory then use the following code:
$image_path = puplic_path("/uploads/img1.jpg")
if (file_exists($image_path)) {
File::delete($image_path);
}
Here is the correct and easy way .
if (file_exists(public_path() . '/storage/gallery/images/'. $item->image)) {
unlink(public_path() . '/storage/gallery/images/'. $item->image);
}

How to delete the specific image in folder using codeigniter?

I am using code-igniter. In my project i would like to delete the specific image in folder(artical_images). If i try to use delete_files() option it deletes all the images in the folder when use the code like,
public function delete_post($value='$id')
{
$query=$this->db->query("select artical_profile from articals where artical_id='$value' ");
$img_name=$query->result()[0]->artical_profile;
//echo $img_name;
delete_files('./artical_images/',TRUE);
// $this->db->where('artical_id',$value);
//$this->db->delete('articals');
exit();
}
But when i include the specific image name taken from db and include with delete file path it doesn't work.The code is below,
public function delete_post($value='$id')
{
$query=$this->db->query("select artical_profile from articals where artical_id='$value' ");
$img_name=$query->result()[0]->artical_profile;
//echo $img_name;
delete_files('./artical_images/$img_name',TRUE);
// $this->db->where('artical_id',$value);
//$this->db->delete('articals');
exit();
}
even i included the realpath option it also not works,
public function delete_post($value='$id')
{
$query=$this->db->query("select artical_profile from articals where artical_id='$value' ");
$img_name=$query->result()[0]->artical_profile;
$img_name=realpath(APPPATH . '/artical_images/$img_name');
delete_files('$img_name',TRUE);
echo $img_name;
// $this->db->where('artical_id',$value);
//$this->db->delete('articals');
exit();
}
please give some idea to delete the files,
$this->load->helper("file");
delete_files($path);
delete_files uses a directory path to delete all the files in the directory. It applies the recursive unlink command to delete files.
To delete particular file, You can use unlink with the proper file path.
e.g. unlink(FILE_PATH);

Upload a file to specific folder using WordPress

I need help for how to upload a file in WordPress, I don't want to upload files into the default path of media files i.e. into uploads/../.., I want to upload my files into wp-content/uploads/my_folder, I just created one file in wp-admin folder and added some functionality there, from that form I want to upload my file (not creating plugin).
Is it possible to do like this? If yes then how? If no then what I want to do for uploading file?
I tried the following solution for it:
$path_array = wp_upload_dir();
$upload_path = $path_array['baseurl'].'/myfoldername/';
$target_path = $upload_path."/".$file_name;
$file_name = $_FILES['fieldname']['name'];
$tmp_name = $_FILES["fieldname"]["tmp_name"];
upload_user_file($_FILES,$upload_path); // Called this function
In functions.php of my theme, I defined the above called function upload_user_file() like as follows:
function upload_user_file( $file = array(),$path) {
if(!empty($file))
{
$uploaded=move_uploaded_file($file['fieldname']['tmp_name'],$path.$file['fieldname']['name']);
if($uploaded)
{
echo "Uploaded successfully ";
}
else
{
echo "Some error in upload ";
print_r($file['error']);
}
}
}
Please help me for this issue.
Thanks.
It's not working because of FILES array loses its values very soon..
Upload it in the same code where you called function it will work...
Thanks cale_b its really helpful.

Silverstripe Image Upload is changing name

I am uploading an image and while storing the image, I am setting the Filename like 'assets/Uploads/54f092af271b9.png' but after saving, the Filename fields loses some part. It becomes 'assets/54f092af271b9.png' losing the "Uploads/" directory altogether. Is it supposed to happen?
Here's the codes:
<?php
$img = new Image();
$baseName = pathinfo($file, PATHINFO_BASENAME);
$fileName = 'assets/Uploads/' . $baseName;
var_dump($fileName);
$img->Name = $baseName;
$img->Filename = $fileName;
$img->OwnerID = ($memberID = Member::currentUserID()) ? $memberID : 0;
$img->write();
var_dump($img->Filename); exit;
Output is:
assets/Uploads/54f092af271b9.png
assets/54f092af271b9.png'
Any ideas?
I was able to replicate the issue with the code you provided. After a bit of digging around, here is what I found.
It all starts in the onAfterWrite function in File class (which Image extends). Fired after you called write (obviously), this calls updateFilesystem where this line sets the Filename property with the result of the getRelativePath function call.
At the time of writing, getRelativePath looks like this:
public function getRelativePath() {
if($this->ParentID) {
// Don't use the cache, the parent has just been changed
$p = DataObject::get_by_id('Folder', $this->ParentID, false);
if($p && $p->exists()) return $p->getRelativePath() . $this->getField("Name");
else return ASSETS_DIR . "/" . $this->getField("Name");
} else if($this->getField("Name")) {
return ASSETS_DIR . "/" . $this->getField("Name");
} else {
return ASSETS_DIR;
}
}
Looking at that code, the issue you have comes from ParentID not being set on your record when you wrote it to the DB so the second condition is run instead returning the result of ASSETS_DIR . "/" . $this->getField("Name").
So that is the problem addressed, now for a solution. Silverstripe wants a parent folder, you've just got to give it one.
Fortunately there is a great little function on the Folder class called find_or_make which does what the name says, either finds the folder record in the filesystem and DB or it will generate it for you.
Note: In my own testing, while I had an "Uploads" folder, I did not have a corresponding DB record so this function wrote that for me an returned the result.
I then used the result to give the image I was writing to the DB a ParentID and it made the second var_dump return the same value as the first.
This is all you need to add to your code before calling write:
$parentFolder = Folder::find_or_make('Uploads');
$img->setParentID($parentFolder->ID);

Categories