mrdotb's avatar

image upload / delete need advices

Hello, I'm looking for best practices about image upload / delete. Currently I'm doing things like this:

public function store(ArticleRequest $request)
    {
        $data = $request->all();
        if (Input::hasfile('image')) {
            $file = Input::file('image');
            $path = public_path('assets/images');
            $fileName = $file->getClientOriginalName();
            $file->move($path, $fileName);
            $data['image_url'] = $fileName;
        }
        Article::create($data);

        return redirect('dashboard/article');
    }

 public function destroy($id)
    {
        $article = Article::findOrFail($id);
        if($article['image_url']){
            $pathToImage = public_path('assets/images/').$article['image_url'];
            File::delete($pathToImage);
        }
        $article->delete();
        return redirect('dashboard/article');
    }

How can I improve this ? Thanks

0 likes
4 replies
tobe81cwb's avatar
Level 2

This is more a tip than best practices:

  • Be carefully with the filename. Imagine that a user upload a picture with name 'my_avatar.png', and then another user upload another image with same name. The old file will be overwrite or a exception can occur. To correct this, on File::move, generate a unique name (don't use getClientOriginalName for this. If you need the original name for some reason, save this information on another place like a database).

  • Check too if the file is a valid image, and restrict the size and resolution.

  • In my projects, I put the 'upload' folder on a config file, than, if I need, I can change the upload folder without change any class.

  • I recommend check the intervention package too (http://image.intervention.io/).

mrdotb's avatar

Thank you for your tip tobe I just add max:2000 in my rules

'image'=>'image|mimes:jpeg,jpg,png,bmp,gif,svg|max:2000'

But, when I ->move($file) , then I got a file without extension in my directory should I concate it with ->getClientOriginalExtension() ?

tobe81cwb's avatar

you can concate with original extension, or you can check the image type (png, gif, bmp, jpg, etc) and if is the case, convert the image to jpg and force the extension to always '.jpg'.

I prefer to always to convert the image to jpg (check the intervention package) to reduce disk usage on the server, but if you need the original quality or better quality than a jpg file, convert to png or maintain the original file and get the extension.

vadimsg's avatar

Do something like this

$file       = Input::file('cover');
$filePath   = $file->getRealPath();
$fileName   = str_random(30) . '.' . $file->getClientOriginalExtension();

$fileResize = Image::make($filePath)
    ->fit(286, 156)
    ->save(public_path() . '/uploads/images/' . $fileName);

Please or to participate in this conversation.