Codeigniter deleting files in a directory not working - php

I am trying to delete pdf files from a folder. I have written the delete_files function as follows
public function delete_files($company_id)
{
$this->load->model('search_model');
$company = $this->search_model->get_company($company_id);
$username = $company[0]['username'];
$path=$this->config->base_url('/uploads/'.$username . '/' . 'uploaded');
$this->load->helper("file"); // load the helper
delete_files($path, true); // delete all files/folders
}
when i did echo $path; it shows the right path where i want the files deleted but when i run the entire function nothing happens and i just get a white screen.

You need to use path to file and not resource locator.
$path = FCPATH . "uploads/$username/uploaded";

try this code
Use
$path = FCPATH . "uploads/$username/uploaded";
unset($path);

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);
}

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);

Laravel: load images stored outside 'public' folder

I'm trying to display an image stored outside the 'public' folder in my view. These are simple profile images whose paths are stored in the DB. The path looks like
/Users/myuser/Documents/Sites/myapp/app/storage/tenants/user2/images/52d645738fb9d-128-Profile (Color) copy.jpg
Since the image is stored a DB column for each user, my first thought was to create an Accessor in the User model to return the image. I tried:
public function getProfileImage()
{
if(!empty($this->profile_image))
{
return readfile($this->profile_image);
}
return null;
}
That produced unreadable characters in the view. I also tried file_get_contents() in place of read file. Any suggestions about how this might be accomplished?
How about this (just tested it myself and it works):
The view:
<img src="/images/theImage.png">
Routes.php:
Route::get('images/{image}', function($image = null)
{
$path = storage_path().'/imageFolder/' . $image;
if (file_exists($path)) {
return Response::download($path);
}
});
Here is a slightly modified version of #Mattias answer. Assume the file is in the storage/app/avatars folder which is outside the web root.
<img src="/avatars/3">
Route::get('/avatars/{userId}', function($image = null)
{
$path = storage_path().'/app/avatars/' . $image.'.jpg';
if (file_exists($path)) {
return response()->file($path);
}
});
Probably needs and else. Also I have wrapped mine inside the middleware auth Route Group which means you have to be logged in to see (my requirements) but I could do with more control over when it is made visible, perhaps alter the middleware.
EDIT
Forgot to mention that this is for Laravel 5.3.
Here's what I came up with:
I'm trying to show the images in the view, not download. Here's what I came up with:
Note that these images are stored above the public folder, which is why we have to take extra steps to display the image in the view.
The view
{{ HTML::image($user->getProfileImage(), '', array('height' => '50px')) }}
The model
/**
* Get profile image
*
*
*
* #return string
*/
public function getProfileImage()
{
if(!empty($this->profile_image) && File::exists($this->profile_image))
{
$subdomain = subdomain();
// Get the filename from the full path
$filename = basename($this->profile_image);
return 'images/image.php?id='.$subdomain.'&imageid='.$filename;
}
return 'images/missing.png';
}
public/images/image.php
<?php
$tenantId = $_GET["id"];
$imageId = $_GET["imageid"];
$path = __DIR__.'/../../app/storage/tenants/' . $tenantId . '/images/profile/' . $imageId;
// Prepare content headers
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
$length = filesize($path);
header ("content-type: $mime");
header ("content-length: $length");
// #TODO: Cache images generated from this php file
readfile($path);
exit;
?>
If somebody has a better way, please enlighten us!! I'm very interested.

(PHP) Returning picture from a directory

In my Product Class, there is a function called pictures() which returns the file address of the picture of a product. It's something like this:
public function picture()
{
$file = "images/pictures/products/" . $this->id . ".png";
if(file_exists($file))
return $file;
else
return false;
}
It works fine when running the code on the administration area of the website (which is located on /admin/ directory)
But when I call this function from the index.php which is not on the /admin/ directory it always returns false. What should I do? The only way I figured to solve this is by creating a parameter on the picture() function, like: picture($directory_prefix) then that way I'll call the function with picture("/admin/"). But there's gotta be a better way than this...
Place your resources in a directory under the web root. Then the path would be:
$file = $_SERVER['HTTP_HOST']."/images/pictures/products/" . $this->id . ".png";

Categories