Remove unused Images/files from upload folder laravel - laravel

I have laravel5.4 application.I want to remove unused images/files from my upload folder which is not available in my database.
For example :
I have 50 images in my upload folder for user profile but some of the image not use for any user.i think he removed or update his image from frontend.
Yes i know we need to code to remove file when user update or remove profile picture at a time also delete from upload folder.but my app run from many time and i want to remove unused file using script not manually beacause i have lot's of files so it's hard to check and remove file manually.anyone can you please help me for create any function for remove file from folder.
Sorry for my bad English.

I use something like this in my AdminController to remove images by clicking on a button.
Maybe you need to change the path or extensions
public function deleteUnusedImages()
{
$file_types = [
'gif',
'jpg',
'jpeg',
'png'
];
$directory = public_path();
$files = File::allFiles($directory);
foreach ($files as $file)
{
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, $file_types)) {
if(DB::table('users')->where('votes', '=', $file)->count())
continue; // continue if the picture is in use
echo 'removed' . basename($file)."<br />";
unlink($file); // delete if picture isn't in use
}
}
}

Related

user uploaded images should be stored in the project like public/userprofileimage.jpg or it will be affected by version control

Consider the case where a user uploaded his profile image and it was placed in the project as public/userprofileimage.jpg when the repository was at version 1.0.0.
The project was then pulled from GitHub, changed, or new code was added, and it was pushed to the repository, becoming version 2.0.0.
How can I add the latest uploaded photos to the repository each time a user uploads something?
Will the user-uploaded picture be in 2.0.0?
or the image will be lost 
What should I do with the user-uploaded images if that's the case so they don't get lost in version control?
if($request->hasFile('image1') && $request->hasFile('image2') && $request->hasFile('image3') && $request->hasFile('image4')){
$formFields['media'] =
$request->file('image1')->store('postUploads','public') . ','
. $request->file('image2')->store('postUploads','public') . ','
. $request->file('image3')->store('postUploads','public') . ','
. $request->file('image4')->store('postUploads','public');
}
and did that
php artisan storage:link
l retrieve the image like that
<img src="{{asset('storage/' . $image)}}" class="md:w-48 m-2 rounded" alt="">
is that the right way?
thanks
A better approach
use Illuminate\Support\Facades\Validator;
public function store(Request $request){
$validate = Validator::make($request->all(), [
$request->file('image1') => 'required|mimes:jpg,png,jpeg',
$request->file('image2') => 'required|mimes:jpg,png,jpeg',
$request->file('image3') => 'required|mimes:jpg,png,jpeg',
$request->file('image4') => 'required|mimes:jpg,png,jpeg',
]);
if( $validate->fails() ){
return response($validate->errors(), 400);
}
//anything below here means validation passed. You can then store your images
$path1 = $request->file('image1')->store('profile_pictures','public');
$path2 = $request->file('image2')->store('profile_pictures','public');
$path3 = $request->file('image3')->store('profile_pictures','public');
$path4 = $request->file('image4')->store('profile_pictures','public');
}
Note that this can even be further simplified by saving your images to an array. I did not use that approach as I am not sure whether all the images are profile images or will be used differently.
Your images will be stored in /storage/profile_pictures and Laravel will automatically generate an image name for you.
On your view you can call the images using the asset helper as below
<img src="{{ asset($path1) }}"/>
This is assuming you are sending the image paths individually, which also can be simplified based on your application. Hope this give you an idea.

Get image from resources folder - Laravel

Can I get and display an image in view from a resources folder instead of public folder? If yes, how can I do that?
resources folder should not be used to store images
That's not where public, static assets (like images, js, css etc) should be.
Put them inside public/ folder
The resources/assets/ directory is for storing pre-processed assets, so to speak.
For example, if you have 3 different CSS files but want to merge them
into one and render that new single file in the browser (to increase
page load speed). In this scenario, the 3 CSS files will be put
somewhere inside resources/assets/.
These files can then be processed, and the new merged file will go inside public.
Reference:
https://laracasts.com/discuss/channels/laravel/image-assets?page=1
You can make a route specifically for displaying images.
Route::get('/resources/app/uploads/{filename}', function($filename){
$path = resource_path() . '/app/uploads/' . $filename;
if(!File::exists($path)) {
return response()->json(['message' => 'Image not found.'], 404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
now you can go to localhost/resources/app/uploads/filename.png and it should display the image.reference How to get image from resources in Laravel?
But again say that resources folder should not be used to store images That's not where public, static assets (like images, js, css etc) should be. as #sehdev says his answer..
Anwsear to your question is in Laravel's doc: https://laravel.com/docs/5.7/helpers#method-app-path
$path = base_path('resources/path/to/img_dir');
You can create an symlink:
ln -s /path/to/laravel/resources/images /path/to/laravel/public/images
Although as other users have already pointed out, the resource directory is not intended to be used publicly.
I agree with #sehdev.
However, if you still want to serve your image from resources directory, here is a solution that gets the job done.
In your view:
<img src="/your-image" />
In Route:
Route::get('/your-image', function ()
{
$filepath = '/path/to/your/file';
$file = File::get($filepath);
$type = File::mimeType($filepath);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
$response->header("Content-Length", File::size($filepath));
return $response;
})
this is not the best solution. I suggest you to move your assets to public directory.
Edit: Use laravel functions. I suggest not to take file path from url because it may subject to Directory Traversal.

laravel blade include files with relative path

In laravel blade system when we want to include a partial blade file we have to write the full path every time for each file. and when we rename a folder then we will have to check every #include of files inside it. sometimes it would be really easy to include with relative paths. is there any way to do that?
for example we have a blade file in this path :
resources/views/desktop/modules/home/home.blade.php
and I need to include a blade file that is near that file :
#include('desktop.modules.home.slide')
with relative path it would be something like this :
#include('.slide')
is there any way to do this?
if someone still interest with relative path to current view file, put this code in the boot method of AppServiceProvider.php or any provider you wish
Blade::directive('relativeInclude', function ($args) {
$args = Blade::stripParentheses($args);
$viewBasePath = Blade::getPath();
foreach ($this->app['config']['view.paths'] as $path) {
if (substr($viewBasePath,0,strlen($path)) === $path) {
$viewBasePath = substr($viewBasePath,strlen($path));
break;
}
}
$viewBasePath = dirname(trim($viewBasePath,'\/'));
$args = substr_replace($args, $viewBasePath.'.', 1, 0);
return "<?php echo \$__env->make({$args}, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>";
});
and then use
#relativeInclude('partials.content', $data)
to include the content.blade.php from the sibling directory called partials
good luck for everyone
you need to create custom blade directive for that, the native include directive doesn't work like that.
read this page to learn how to create custom blade directive :
https://scotch.io/tutorials/all-about-writing-custom-blade-directives
\Blade::directive('include2', function ($path_relative) {
$view_file_root = ''; // you need to find this path with help of php functions, try some of them.
$full_path = $view_file_root . path_relative;
return view::make($full_path)->render();
});
then in blade file you can use relative path to include view files :
#include2('.slide')
I tried to tell you the idea. try and test yourself.
There’s now a package doing both relative and absolute includes (lfukumori/laravel-blade-include-relative) working with #include, #includeIf, #includeWhen, #each and #includeFirst directives. I just pulled it in a project, it works well.
A sleek option, in case you want to organise view files in sub-folders:
public function ...(Request $request) {
$blade_path = "folder.subfolder.subsubfolder.";
$data = (object)array(
".." => "..",
".." => $..,
"blade_path" => $blade_path,
);
return view($data->blade_path . 'view_file_name', compact('data'));
}
Then in the view blade (or wherever else you want to include):
#include($blade_path . 'another_view_file_name')

I am using the upload function of codeigniter but how do I attach the image uploaded on the server once I edit that item?

I have been successful in using the File Uploading Library to upload my files on the server (mostly images).
My problem is when I need to update that specific item, I need to browse for photo again. Is there a way I can just attach the image uploaded already in the server to my upload button? I am thinking to make a media page like that of the wordpress but is there any starting point that anyone knows who can point me to? Thanks so much!
You can use a hidden field...check this example
View
<?php echo form_upload("vLogo", $campaign->vLogo , "id='vLogo'"); ?>
<?php echo form_hidden("vLogo_old", $campaign->vLogo , "id='vLogo_old'"); ?>
Controller
(Edit function)
//The way you do when you click on browse and select a file
if(isset($_FILES['vLogo']['tmp_name']) && !empty($_FILES['vLogo']['tmp_name']))
{
$this->load->library('upload', $config);
// Initialaizing Logo upload
$this->upload->initialize($config);
if ( !$this->upload->do_upload('vLogo')){
$logo_error = array('vLogo' => $this->upload->display_errors());
}
else{
$data1 = array('upload_data' => $this->upload->data());
}
}
else
{
//The browse filed is empty..So hidden input is taken
$data1['upload_data']['file_name'] = $post['vLogo_old'];
}

File upload in joomla module

I have been searching this for quite a while but couldn't find a solution to match my need. I am developing a module for Joomla 2.5 . I need functionality to allow users to upload images/any file type from the backend in module configuration.
Question : How can I add field for file upload in joomla module.
Thanks!
Just a sample from the joomla docs:
<?php
//Retrieve file details from uploaded file, sent from upload form
$file = JRequest::getVar('file_upload', null, 'files', 'array');
//Import filesystem libraries. Perhaps not necessary, but does not hurt
jimport('joomla.filesystem.file');
//Clean up filename to get rid of strange characters like spaces etc
$filename = JFile::makeSafe($file['name']);
//Set up the source and destination of the file
$src = $file['tmp_name'];
$dest = JPATH_COMPONENT . DS . "uploads" . DS . $filename;
//First check if the file has the right extension, we need jpg only
if ( strtolower(JFile::getExt($filename) ) == 'jpg') {
if ( JFile::upload($src, $dest) ) {
header("Location: http://".$_SERVER["HTTP_HOST"]."/administrator"); Redirect to a page of your choice
} else {
echo "error !"; //Redirect and throw an error message
}
} else {
echo "Wrong extension !"; //Redirect and notify user file is not right extension
}
?>
For more detailed information and full example(s): http://docs.joomla.org/How_to_use_the_filesystem_package
Keep in mind that your HTML form must include
enctype="multipart/form-data"
otherwise you will not get any result with the joomla function!

Resources