Laravel 5.1 Upload Files Security - php

How can I set a security in my upload files that only pdf, doc, jpeg, png and docx can be uploaded?
I'm just trying it but I don't know if it is the right thing to do... just experimenting.. ^_^ But after all it didn't function ^^ ... actually i've got an error.. Try to help me guys for this?
Here's my Controller.php
public function index()
{
$entries = Fileentry::where('user_id',Auth::user()->id)->get();
return view('fileentries.index', compact('entries'));
}
public function store(UploadFiles $request)
{
if($request->file('filename'))
{
$file = $request->file('filename');
$filename = $file->getFilename().'.'.$extension;
$fileExt = $file->getClientOriginalExtension();
$mime = $file->getClientMimeType();
$original_filename = $file->getClientOriginalName();
$description = UploadFiles::input('description');
$user_id = Auth::user()->id;
$file->save();
// Move the file now
$updatedFileName = $filename.'.'.$fileExt;
$file->move('path/to/destination/folder', $updatedFileName);
return redirect('upload');
}
else
{
echo "nothing happen";
}
}
Here's my View.blade.php
#extends('layouts.app')
#section('content')
<form action="{{route('addentry', [])}}" method="post" enctype="multipart/form-data">
<input name="_token" type="hidden" value="{!! csrf_token() !!}" />
<input type="file" name="filefield" required>
<br>
Description <br>
<input type="textarea" name="description">
<br>
<input type="submit">
</form>
<h1> List of your Entries</h1>
<div class="row">
<ul class="thumbnails">
#foreach($entries as $entry)
<div class="col-md-2">
<div class="thumbnail">
<img src="{{route('getentry', $entry->filename ) }}" alt="ALT NAME" class="img-responsive" />
<p>{{ $entry->description }} </p>
{{$entry->original_filename}}
</div>
</div>
#endforeach
</ul>
</div>
nI#endsection
Thank you guys in advance ^^

Make a FormRequest object by issuing the following command:
php artisan make:request YourFormRequest
Now, in your rules method:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'filename' => 'mimes:pdf,doc,jpeg,png,docx',
// and other validation rules...
];
}
Now update your controller:
/**
* Store the form values.
* Don't forget to import the YourFormRequest class
*
* #param \App\Http\Requests\YourFormRequest $request
* #return \Illuminate\Http\Redirect|string
*/
public function store(YourFormRequest $request)
{
if($request->file('filename')) {
$file = $request->file('filename');
$fileName = $file->getClientOriginalName();
$fileExt = $file->getClientOriginalExtension();
$fileMime = $file->getClientMimeType();
// and rest of the file details
// Move the file now
$updatedFileName = $fileName.'.'.$fileExt;
$file->move('path/to/destination/folder', $updatedFileName);
// or using the Storage class, it is the same
// as what you have written.
}
}
UPDATE 1:
In your YourFormRequest file, replace the authorize method:
/**
* Authorize the request.
*
* #return bool
*/
public function authorize()
{
return true; // replace false with true.
}
Hope this helps you out. Cheers.

Related

Unable to upload image through form?

Here's my HTML:
<label for="attachement1">Attach a file: <small style="color:#999;">(type: zip/rar and below 10mb)</small></label>
<input type="file" name="file1"/><br/>
<label for="snapshot">Snapshot / Thumbnail:</label>
<input type="file" name="thumbnail" required/><br/>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-primary" name="Submit" value="Publish" />
Here is the code in my controller file (for the update function):
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'thumbnail' => 'mimes:jpg,jpeg,png|max:800',
'file1' => 'mimes:rar,zip|max:10000',
]);
$file1=$request->file('file1');
if(is_null($request->file('file1'))){
$p=pages::where('id', '=', $request['id'])->first();
$attmt1=$p->attachment;
}
else
{
$upload_dir='uploads';
$attmt1=$file1->getClientOriginalName();
$move=$file1->move($upload_dir, $attmt1);
}
if(is_null($request->file('thumbnail'))){
$p=pages::where('id', '=', $request['id'])->first();
$image=$p->thumbnail;
}
else
{
$img=$request->file('thumbnail');
$upload_dir='thumbnails';
$image=$img->getClientOriginalName();
$move=$img->move($upload_dir, $image);
//end thumbnail process
}
$mypage->title = $request->title;
$mypage->body = $request->body;
//$mypage->thumbnail = $request->thumbnail;
$mypage->slug = str_slug($request->slug, '-');
$mypage->menu_name = $request->menu_name;
$mypage->save();
return redirect()->route('menupages.index')->with('message', 'Page updated successfully.');
}
When I try to edit an item and upload an image (.jpg format), and click submit, I get a "The thumbnail must be a file of type: jpg, jpeg, png." I checked the database and the file was not recorded.
For some reason, it is detecting the image as some foreign image file type even though it is .jpg.
Are you Add enctype="multipart/form-data" on your form?
<form method="post" Action= "" enctype="multipart/form-data">
</form
When you want to upload something, you always need to add the following code to your form.
enctype="multipart/form-data"
If you don't do this, you can't upload something.
Did you add this to your html form?
I got help from a developer on this so I will post how we were able to solve the problem.
Here's the full revised code for the function:
Controller:
public function update(Request $request, $id)
{
$this->validate($request, [
'thumbnail' => 'mimes:jpg,jpeg,png|max:300000',
'file1' => 'mimes:rar,zip|max:10000',
]);
$file1 = $request->file('file1');
if(is_null($request->file('file1'))){
// $p=pages::where('id', '=', $request['id'])->first();
$p = MenuPage::find($request['id']);
$attmt1 = $p['attachment'];
}
else
{
$upload_dir = 'uploads';
$attmt1 = $file1->getClientOriginalName();
$file1->move($upload_dir, $attmt1);
}
if(is_null($request->file('thumbnail'))){
// $p=pages::where('id', '=', $request['id'])->first();
$p = MenuPage::findOrFail($request['id']);
$image = $p->thumbnail;
}
else
{
$img = $request->file('thumbnail');
$upload_dir = 'thumbnails';
$image = $img->getClientOriginalName();
$img->move($upload_dir, $image);
//end thumbnail process
}
//$check=pages::where('id', $request['id'])
//->update([
// 'title' => $title,
// 'body' =>$body,
// 'thumbnail' =>$thumbnail,
// 'slug' =>$slug,
// 'school' =>$school,
// 'attachment' =>$attmt1,
// 'menu_name' =>$menu_name,
// ]);
$mypage = MenuPage::find($id);
$mypage->title = $request->title;
$mypage->body = $request->body;
$mypage->thumbnail = $image;
$mypage->attachment = $attmt1;
$mypage->slug = str_slug($request->slug, '-');
$mypage->menu_name = $request->menu_name;
$mypage->save();
return redirect()->route('menupages.index')->with('message', 'Page updated successfully.');
}
View file (the bottom part):
<label for="attachement1">Attach a file: <small style="color:#999;">(type: zip/rar and below 10mb)</small></label>
<input type="file" name="file1"/><br/>
<label for="snapshot">Snapshot / Thumbnail:</label>
<input type="file" name="thumbnail" required/><br/>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input name="_method" type="hidden" value="PUT">
<input type="submit" class="btn btn-primary" name="Submit" value="Publish" />

Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, object given, called in laravel

I'm trying to post an image from a one to many relationship while also doing the CRUD (create part), but I am having some trouble doing it. I keep on getting this error
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, object given, called in
Whenever I try to use associate to define the relationship together with user_info with user_image table. I have already used the array function to make it into an array but it still gave me this error. So what should I do?
createController:
public function create1(){
return view('create1');
}
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($file = $request->hasFile('input_img')) {
$file = array();
$file = $request->file('input_img') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create($file);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
return redirect('/home');
}
HomeController(this is where I print out my information)
public function getInfo($id) {
$data = personal_info::where('id',$id)->get();
$data3=UserImage::where('user_id',$id)->get();
return view('test',compact('data','data3'));
blade.php (how I show the image in view)
#foreach ($data3 as $object9)
<img width="100" height="100" src="{!! $object9->signature !!}">
#endforeach
UserImage model(in table I used binary format to store in DB)
class UserImage extends Eloquent
{
protected $fillable = array('userImage','user_id');
public function user_infos() {
return $this->belongsTo('App\user_info', 'user_id', 'id');
}
class user_info extends Eloquent
{
protected $fillable = array('Email', 'Name');
protected $table = user_infos';
protected $primaryKey = 'id';
public function UserImages() {
return $this->hasOne('App\UserImage','user_id');
}
}
create1.blade.php(this is how I upload the image)
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="" ></img>
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
You should give an array while passing data to create method like this. Currently, you are passing the file object.
$UserImage = UserImage::create(['file' => $request->file('input_img')]);

One to one relationship while doing CRUD (create part)

I am having some trouble doing a one to one relationship with user_info table and userImage table. When I try to upload my image, it didn't save into my database and it user_id is 0. I managed to successfully do a one to many and one to one relationship in the past but not with CRUD together. Can anyone help me? Best to give me some example for me to refer or advice on what should I do. Thanks in advance
Here are my current codes:
createController:
public function create1(){
return view('create1');
}
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($request->hasFile('input_img')) {
$file = $request->file('input_img');
$fileName = $file->getClientOriginalName();
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create(['file' => $request->file('input_img')]);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
return redirect('/home');
}
HomeController(this is where I print out my information)
public function getInfo($id) {
$data = personal_info::where('id',$id)->get();
$data3=UserImage::where('user_id',$id)->get();
return view('test',compact('data','data3'));
blade.php (how I show the image in view)
#foreach ($data3 as $object9)
<img width="100" height="100" src="{!! $object9->userImage!!}">
#endforeach
UserImage model(in table I used binary format to store in DB)
class UserImage extends Eloquent
{
protected $fillable = array('userImage','user_id');
public function user_infos() {
return $this->belongsTo('App\user_info', 'user_id', 'id');
}
class user_info extends Eloquent
{
protected $fillable = array('Email', 'Name');
protected $table = user_infos';
protected $primaryKey = 'id';
public function UserImages() {
return $this->hasOne('App\UserImage','user_id');
}
}
create1.blade.php(this is how I upload the image)
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="" ></img>
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
You need to check out Laravel relations to clean up that code and simplify a lot of steps.
Change this line
$UserImage->user_infos()->associate($user_info);
For this
$UserImage->user_id = $user_info;
Take in mind that you're overriding the value of $UserImage inside that method.

Laravel 5.4 image gallery

I am building a Laravel web application where I need a dynamic image gallery, I build a backend admin panel where I can add images, I succeed to add and save the images to the database but I can not edit or delete them.
The error is:
ErrorException in UrlGenerationException.php line 17: Missing required parameters for [Route: galleries.update] [URI:
backend/galleries/{gallery}]. (View: /var/www/html/tryout101/resources/views/backend/gallery/edit.blade.php)
This my route code:
<?php
/*backend access*/
Route::group(['prefix' => '/backend'], function() {
/*The route Dashboard main page */
Route::get('/' , 'AdminController#index')->name('dashboard');
Route::resource('galleries' , 'GalleriesController');
});
This the Controller code:
<?php
namespace App\Http\Controllers;
use App\Gallery;
use Illuminate\Http\Request;
use Image;
use Illuminate\Support\Facades\Input;
class GalleriesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$gallery = Gallery::all();
return view('backend.gallery.library', compact('gallery'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('backend.gallery.uploadform');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$gallery = new Gallery();
$this->validate($request, [
'title' => 'required',
'image' => 'required'
]);
$gallery->title = $request->title;
$gallery->description = $request->description;
if($request->hasFile('image')) {
$file = Input::file('image');
$filename = time(). '-' .$file->getClientOriginalName();
$gallery->image = $filename;
$file->move(public_path().'/images/', $filename);
}
$gallery->save();
return $this->create()->with('success', 'Image Uploaded
Successfully');
}
/**
* Display the specified resource.
*
* #param \App\Gallery $gallery
* #return \Illuminate\Http\Response
*/
public function show(Gallery $gallery)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Gallery $gallery
* #return \Illuminate\Http\Response
*/
public function edit(Gallery $gallery)
{
if(!$gallery){
return redirect('dashboard')->with(['fail'=>'post not found']);
}
return view('backend.gallery.edit',compact('gallery'));
}
public function update(Request $request, Gallery $gallery)
{
$this->validate($request, [
'title'=>'required|max:120',
'image'=>'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$gallery->title = $request->title;
$gallery->description = $request->description;
if($request->hasFile('image')) {
$file = Input::file('image');
$filename = $file->getClientOriginalName();
$gallery->image = $filename;
$file->move(public_path().'images/', $filename);
}
$gallery->update();
return Redirect()->route('dashboard')->with(['success'=> 'post
successfully updated']);
}
public function destroy(Gallery $gallery)
{
//
}
}
/This is my edit page/
#extends('layouts.backend-master')
#section('styles')
<link rel="stylesheet" href="">
#endsection
#section('content')
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<h1>File Upload</h1>
<form action="{{route('galleries.update')}}" method="post"
enctype="multipart/form-data">
<div class="input-group">
<label for="title">Title</label>
<input type="text" name="title" id="title"/>
</div>
<div class="input-group">
<label for="description">Description</label>
<textarea type="text" name="description" id="description" rows="8">
</textarea>
</div>
<div class="input-group">
<label for="image">Select image to upload:</label>
<input type="file" name="image" id="file">
</div>
<button type="submit" class="btn">Update</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
<input type="hidden" name="gallery" value="{{$gallery->id}}">
</form>
#endsection
#section('scripts')
#endsection
The fact is that the route 'galleries.update' requires a Gallery
Therefore, you should give him which Gallery you want to go to when calling the route function with that route
Thus, I think that changing
route('galleries.update')
into
route('galleries.update', $gallery)
will make everything fine

Posting content into the database with an image using Laravel

I'm trying to post some stuff into the database using laravel, but It seems not to work...
This is what I get:
The HTML:
{{ Form::open(array('role' => 'form')) }}
<div class="form-body">
<div class="form-group">
<label>Titel</label>
<input type="text" class="form-control" name="title" placeholder="Titel komt hier">
</div>
<div class="form-group">
<label>Textarea</label>
<textarea class="form-control" name="message" rows="5" placeholder="Uw bericht..."></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile1">Nieuws afbeelding</label>
<input type="file" name="img">
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn green" value="Oplsaan" />
</div>
{{ Form::close() }}
#if ($errors->any())
<ul>
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
</ul>
#endif
That displays all well....
Exept when I try to 'post' the news, because that is what I try to do, it just refreses the page. The URL to that page is mydomain.com/admin/news/write
My router looks like this:
Route::resource('admin/news/write', 'AdminController#create');
First it was authenticated in a group:
Route::group(array('before' => 'auth'), function()
{
Route::resource('admin', 'AdminController');
Route::resource('admin/news/write', 'AdminController#create');
});
This all works, but when I change the Route::resource('admin/news/write', 'AdminController#create'); to Route::post('admin/news/write', 'AdminController#create'); I get an error, that I can't see...
Good, now my controller:
public function store()
{
$rules = array(
'title' => 'required',
'message' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->passes())
{
if (Input::only('title', 'message'))
{
return Redirect::to('admin/news/write')->with('message', 'Het nieuws werd gemaakt!');
}
}
else
{
return Redirect::to('admin/news/write')->with('message', "Er ging iets mis: ")->withErrors($validator);
}
}
The problem is, I don't know how I can store an image to
/public/pictures/news
And then store the full file name into the database, if someone could help me out... I need a response quick, beacause I have a deadline... :{
Kindest regards
First you need to tell your form using the laravel helper that this is going to be uploading a file...
Form::open(['method'=>'POST', 'role' => 'form', 'files' => true])
In your controller you want to get the file from the input
$imgFile = Input::file('img');
Now to move the file from the temporary location it's been uploaded, to a more permanent location call the following (where $filename is what you want to call the uploaded file)...
$dir = '../storage/app/upload/';
$imgFile->move($dir.$filename);
The path for the root of the app from here is ../ (one up from public) so..
../storage/app/upload/ would be a great location to use for uploaded files.
You can then just write:
$dir.$filename;
back to the database - job done :)
Edit :: -- Your Controller --
Your controller for parsing this is based on resources...
So your route will be:
Route::group(array('before' => 'auth'), function()
{
Route::resource('admin', 'AdminController');
}
Your controller itself will have a structure such as (remembering this: http://laravel.com/docs/4.2/controllers#restful-resource-controllers):
class AdminController extends BaseController {
public function index(){...}
public function create(){...}
public function
//The store() method is an action handled by the resource controller
//Here we're using it to handle the post action from the current URL
public function store()
{
$imgFile = Input::file('img');
//processing code here....
}
public function show(){...}
public function edit(){...}
public function update(){...}
public function destroy(){...}
}
I fixed the issue.
My controller:
<?php
class AdminNewsController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return View::make('admin.news.create');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return View::make('admin.news.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$rules = array(
'title' => 'required',
'message' => 'required',
'publish' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
//process the storage
if ($validator->fails())
{
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/news/create')->withErrors($validator);
}else{
//store
$news = new News;
$news->title = Input::get('title');
$news->message = Input::get('message');
$news->img_url = Input::file('img')->getClientOriginalName();
$news->posted_by = Auth::user()->username;
$news->published_at = time();
$news->published = Input::get('publish');
$news->save();
//save the image
$destinationPath = 'public/pictures/news';
if (Input::hasFile('img'))
{
$file = Input::file('img');
$file->move('public/pictures/news', $file->getClientOriginalName());
}
//redirect
Session::flash('success', 'Nieuws succesvol aangemaakt!');
return Redirect::to('admin/news/create');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
My create.blade.php
<div class="portlet-body form">
{{ Form::open(['method'=>'POST', 'role' => 'form', 'files' => true]) }}
<div class="form-body">
<div class="form-group">
<label>Titel</label>
<input type="text" class="form-control" name="title" placeholder="Titel komt hier">
</div>
<div class="form-group">
<label>Textarea</label>
<textarea class="form-control" name="message" rows="5" placeholder="Uw bericht..."></textarea>
</div>
<div class="form-group">
<label>Nieuws afbeelding</label>
{{ Form::file('img') }}
</div>
<div class="form-group">
<label>Bericht publiceren?</label>
<div class="radio-list">
<label class="radio-inline">
<span>
{{ Form::radio('publish', '1') }}
</span>
<b style="color:green">Publiceren</b>
</label>
<label class="radio-inline">
<span>
{{ Form::radio('publish', '0', true) }}
</span>
<b style="color:red">Niet publiceren</b>
</label>
</div>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn green" value="Oplsaan" />
</div>
{{ Form::close() }}
</div>
Then It all work!
Thanks to Matt Barber for the help!

Categories