Uploading file with php - php

I have the following set up in a Code Igniter application, however the file is not being passed through to the file uploader class. This is the second form on the page, just for reference and I have checked that they are both closed correctly.
The output I am getting is You did not select a file to upload. when I have been selecting an valid image.
View
<form action="../albums/upload" class="form-horizontal" method="post">
<div class="form-group">
<input type="file" name="userfile" required="" class="form-control">
</div>
<div class="form-group">
<div class="col-md-4 col-md-offset-4">
<input type="submit" id="upload" name="upload" class="btn btn-success" value="Upload">
</div>
</div>
</form>
Controller
public function upload() {
if($this->input->post('userfile')){
$this->model_photo->do_upload();
}
}
Model
function do_upload() {
$path = base_url().'res/image/';
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png|tif|tiff',
'upload_path' => $path
);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
echo $error['error']; //echo debugging purposes
} else {
$data = array('upload_data' => $this->upload->data());
echo $data['upload_data']; //echo debugging purposes
}
}

in your <form> add enctype="multipart/form-data"
<form action="../albums/upload" class="form-horizontal" method="post" enctype="multipart/form-data">

Related

Why doesn't my php laravel application store my image?

I've looked at code from other people and try to implement the same thing, but the application could not store the image to the desire folder, would you please have a look at what the reason is? Thank you!
Here is my code for route:
Route::post('upload_pic', 'UploadController#storePhoto');
Here is my code for the php laravel template:
<div class="panel-body">
<form action="{{url('/upload_pic')}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="upload-user-photo">Upload Photos</label>
<input type="file" name="image" class="form-control" placeholder="Upload Student Image, Size:207(W)x408(H)">
</div>
<div class="row">
<div class="col-sm-4">
<input class="btn btn-success" type="submit" value="Upload Student Photo" name="submit">
</div>
</div>
</form>
</div>
Here is my code in the controller:
public function storePhoto(Request $request){
$valid = $request->validate([
'image' => 'required|image|mimes:jpg,png,jpeg,|dimensions:max_width=272,max_height=408,min_width=271,min_height=407'
]);
$data = new Postimage();
$file = $request->file('image');
$filename = $file->getClientOriginalName();
// dd($filename);
$file -> move(public_path('./public/img/student_photos'),$filename);
$data['image'] = $filename;
$data->save();
return redirect('/upload')->with('success', 'Photo Uploaded');
}
Your problem is somewhere here
$filename = $file->getClientOriginalName();
$file -> move(public_path('./public/img/student_photos'),$filename);
First, the file comprises only the file extension. Instead, you should have something like this $filename = 'name.' . $file->getClientOriginalName(); Notice the dot in 'name.'
Secondly, no need to add public to the file path string. So it should be $file->move(public_path('img/student_photos'),$filename);
Finally, make sure the upload folder exists and is writeable

move_uploaded_file is not fetching path in laravel

Here is my controller
public function createAdmin()
{
$photo=$_FILES['bannerPic']['name'];
$tempname=$_FILES['bannerPic']['tmp_name'];
// echo $tempname." ".$photo;
move_uploaded_file($tempname, 'picture/banner/'.$photo);
$data=[
'sliderPic' => $photo,
];
dd($data);
// \App\Models\Banner::create($data);
// return view('Banner');
}
here is my route
Route::post('/BannerEdit', [App\Http\Controllers\BannerController::class,
'createAdmin']);
here is my blade form
<form action="{{ url('') }}/BannerEdit" method="post" class="col-12"
enctype="multipart/form-data">
#csrf
<div class="mb-3 col-12">
<label class="col-4 text-label form-label">Banner Photo*</label>
<input type="file" name="bannerPic" class="form-control input-rounded col-4 mb-3"
required>
</div>
<div class="mb-3 text-end">
<input type="submit" class="btn btn-primary" value="Upload">
</div>
</form>
When i submit the data it Gives me an Error as
move_uploaded_file(picture/banner/favicon.jpg): Failed to open stream: No such file or directory
But this Directory Exists
And i checked with full pathof localhost then it does not supports http path
You need to use getcwd() function like this:
$dirpath = realpath(dirname(getcwd()));
So your controller code will be:
public function createAdmin()
{
$photo=$_FILES['bannerPic']['name'];
$tempname=$_FILES['bannerPic']['tmp_name'];
// echo $tempname." ".$photo;
$dirpath = realpath(dirname(getcwd()));
move_uploaded_file($tempname, $dirpath.'/'.$photo);
$data=[
'sliderPic' => $photo,
];
dd($data);
// \App\Models\Banner::create($data);
// return view('Banner');
}
let me know if it works.. if not then we'll modify $dirpath variable
PS: this solution will work on server. are you working on server or in localhost?
EDIT:
Other solution is to use below function to get proper directory structure:
$dirpath = public_path('picture/banner/');

Error in adding new item to my database using codeigniter

I have been getting this error while submiting a form using codeigniter. I need help even though I have been following the documentation.
I am using 2.x version of codeigniter
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Products::$input‐
Filename: core/Model.php
Line Number: 52
Fatal error: Call to undefined function post() in /opt/lampp/htdocs/gamingplace/application/models/product_model.php on line 63
This is the code in my model
//add new product
public function addProduct(){
$data = array(
'category_id' => $this->input‐>post('category_id'),
'title' => $this->input‐>post('title'),
'description' => $this->input‐>post('description'),
'price' => $this->input‐>post('price')
);
if($_FILES['image']['error'] == 0){
$data['image'] = $this->upload->file_name;
return $this->db->insert('products',$data);
}
}
}
This is the code in my controller
public function addProduct()
{
if($_FILES['image']['error'] == 0){
//setting image preferences
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'jpg|png|jpeg|PNG|JPEG|JPG';
$config['overwrite'] = false;
$config['quality'] = '100%';
$config['remove_spaces'] = true;
$config['max_size'] = '90';// in KB
$this->load->library('upload',$config);
echo $this->input->post('image');
if( ! $this->upload->do_upload('image'))
{
$this->session->set_flashdata('message_failed', $this->upload->display_errors('', ''));
redirect('dashboard');
}else{
//Image Resizing
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['maintain_ratio'] = FALSE;
$config['width'] = 311;
$config['height'] = 162;
$this->load->library('image_lib',$config);
if ( ! $this->image_lib->resize()){
$this->session->set_flashdata('message_failed', $this->image_lib->display_errors('', ''));
}
//calling a model an its method to add a new product to the database
if($this->product_model->addProduct()){
$upload_data = $this->upload->data();
$this->session->set_flashdata('message', 'A new product,'. $upload_data['file_name'].'has been added!');
redirect('dashboard');
}
}
}
}
}
And my view
<!-- Modal -->
<script src="<?php echo base_url(); ?>assets/js/validation.js" charset="utf-8"></script>
<div class="modal fade" id="addProduct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Product</h4> <em>if the product category is not in the select option,
go to add category link to add category before adding this product</em>
</div>
<div class="modal-body">
<?php echo validation_errors('<div class="alert alert-danger">','</div>') ?>
<form role= "form" action="<?php echo base_url()?>products/addProduct" method="post" name="form" onsubmit="return validate(this)" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="title" class="form-control" placeholder="Enter name of product" required>
</div>
<div class="form-group">
<label>Brief Description of Product</label>
<textarea name="description" rows="8" cols="80" class="form-control">
This is a brand made by Gucci Company. Made of cotton, bla bla bla
</textarea>
</div>
<label>Select Category</label>
<div class="form-group">
<select class="form-control" name="category_id">
<?php foreach (get_categories_h() as $popular): ?>
<option value="<?php echo$popular->id?>"><?php echo $popular->name ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Enter or choose price</label>
<input type="number" id="price" class="form-control" name="price_old" required>
</div>
<input type="hidden" name="price" class="form-control" id="mainPrice"required>
<div class="form-group">
<input type="file" name="image" id="image" class="form-control" required accept="image/*" onChange="validateImage(this.value)">
</div>
<button type="submit" name="submit" class=" form-control btn btn-success">Add</button>
</form>
</form>
</div>
</div>
</div>
</div>
I think you may have a few issues going on with your code, but let's first focus on your question/error you mentioned. In your controller function, you are not passing the post to the model. You need to do something like this in the controller:
$addProduct = $this->product_model->addProduct($_POST);
if($addProduct){
$upload_data = $this->upload->data();
$this->session->set_flashdata('message', 'A new product,'. $upload_data['file_name'].'has been added!');
redirect('dashboard');
}
In the model function, you need to first let the function know there is an incoming parameter, then adjust how you are assigning the fields to the data array.
public function addProduct($post){
$data = array(
'category_id' => $post["category_id"],
'title' => $post["title"],
'description' => $post["description"],
'price' => $post["price"]
);
return $this->db->insert('products',$data);
}
After that, I noticed that you have some other FILES logic in your model. That will likely error out, too. I believe that is going to have to be done in the controller, not the model. Once you do the upload in the controller, you can pass the file name into the model as well.
$upload_data = $this->upload->data();
$addProduct = $this->product_model->addProduct($_POST, $upload_data['file_name']);
if($addProduct){
$this->session->set_flashdata('message', 'A new product,'. $upload_data['file_name'].'has been added!');
redirect('dashboard');
}
Then, adjust the model.
public function addProduct($post, $fileName){
$data = array(
'category_id' => $post["category_id"],
'title' => $post["title"],
'description' => $post["description"],
'price' => $post["price"],
'image' => $fileName
);
return $this->db->insert('products',$data);
}
Hope this helps.

Laravel 5.1 File Upload isValid() on string?

So I am making a function for file uploading in my project.
however, when I try it I get this error : Call to a member function isValid() on string
My code for the upload function :
public function upload(Request $request){
$file = array('profielfoto' => $request->input('profielfoto'));
$rules = array('profielfoto' => 'required',);
$validator = Validator::make($file,$rules);
if($validator->fails()){
return redirect('/profiel')->withInput()->withErrors($validator);
}
else{
if($request->input('profielfoto')->isValid()){ //<- gives error
$destinationPath = 'assets/uploads';
$extension = $request->input('profielfoto')->getClientOriginalExtension();
$fileName = rand(1111,9999).'.'.$extension;
$request->input('profielfoto')->move($destinationPath,$fileName);
Session::flash('alert-success', 'Foto uploaden gelukt');
return redirect('/profiel');
}
else{
Session::flash('alert-danger', 'Foto uploaden mislukt');
return redirect('/profiel');
}
}
}
The form in the blade view on the 4th line from down below is the location for the input!
<form method="POST" action="/profiel/upload" files="true">
{!! csrf_field() !!}
<input type="hidden" name="_method" value="PUT">
<input type="hidden" class="form-control id2" id="id2" name="id" value="{{$user->id}}">
<img src="assets/images/avatar.png" alt="gfxuser" class="img-circle center-block">
<div class="form-group center-block">
<label class="center-block text-center" for="fotoinput">Kies uw foto</label>
<input class="center-block" type="file" name="profielfoto" id="profielfoto">
</div>
<button type="submit" class="btn btn-success"><span class="fa fa-check" aria-hidden="true"></span> Verander foto</button>
</form>
You must ask isValid() to a file, not to the name of the file. That's why you get the error. You can get the file through $request->file() or through Input::file() :
else{
if( $request->file('profielfoto')->isValid()){ //<- gives error
Also your form should include the correct enctype to send files:
<form enctype="multipart/form-data">
I think you should use as this.
$file = $request -> file('Filedata');
if (!$file -> isValid()) {
echo Protocol::ajaxModel('JSEND_ERROR', 'not an valid file.');
return;
}
Add attribute on
enctype="multipart/form-data"

image uploading is not working in CodeIgniter

when I click button then it will return error "You did not select a file to upload." and My image is not uploaded!
now please help me what can I do?
my view is
<form action="insertform" enctype="multipart" name="form" method="post" id="contact-form" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="name">Image Upload:</label>
<div class="controls">
<input type="file" class="input-large" name="image" id="image">
</div>
<form>
my controller is:
public function upload()
{
$this->load->helper(array('form', 'url'));
$config['upload_path'] = FCPATH."upload";
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('xyz', $error);
} else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('xyz', $data);
}
}
I think the file input name should be "userfile", not "image".
CI file upload file control default name is userfile.
If you want to change the it's name to customized one, then you have to pass the new name to upload function like :
if ( ! $this->upload->do_upload("image")) // image is your new name for file control
Firstly,
either change the do_upload function call to:
if ( ! $this->upload->do_upload('image'))
OR
change the input name to this:
<input type="file" class="input-large" name="userfile" id="image">
Secondly,
change your form enctype to:
enctype="multipart/form-data"

Categories