Why can i not upload images to my folder anymore? - php

This was something I had working a few weeks back but after I made some changes to my view file images are now no longer being saved into my assets/uploads folder. I keep getting back the error - You did not select a file to upload. This is despite having made sure the path is definitely correct. What am i doing wrong here?
Here is my controller:
<?php
class HomeProfile extends CI_Controller
{
function HomeProfile()
{
parent::__construct();
$this->load->model("profiles");
$this->load->model("profileimages");
$this->load->helper(array('form', 'url'));
}
function upload()
{
$config['path'] = './web-project-jb/assets/uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '10000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$img = $this->session->userdata('img');
$username = $this->session->userdata('username');
$this->profileimages->putProfileImage($username, $this->input->post("profileimage"));
//fail show upload form
if (! $this->upload->do_upload())
{
$error = array('error'=>$this->upload->display_errors());
$username = $this->session->userdata('username');
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
$this->load->view('homeprofile/upload_fail', $error);
$this->load->view('homeprofile/homeprofileview', $viewData, array('error' => ' ' ));
$this->load->view('shared/footer');
//redirect('homeprofile/index');
}
else
{
//successful upload so save to database
$file_data = $this->upload->data();
$data['img'] = base_url().'./web-project-jb/assets/uploads/'.$file_data['file_name'];
// you may want to delete the image from the server after saving it to db
// check to make sure $data['full_path'] is a valid path
// get upload_sucess.php from link above
//$image = chunk_split( base64_encode( file_get_contents( $data['file_name'] ) ) );
$this->username = $this->session->userdata('username');
$data['profileimages'] = $this->profileimages->getProfileImage($username);
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$username = $this->session->userdata('username');
}
}
function index()
{
$username = $this->session->userdata('username');
$data['profileimages'] = $this->profileimages->getProfileImage($username);
$viewData['username'] = $username;
$viewData['profileText'] = $this->profiles->getProfileText($username);
$this->load->view('shared/header');
$this->load->view('homeprofile/homeprofiletitle', $viewData);
$this->load->view('shared/nav');
//$this->load->view('homeprofile/upload_form', $data);
$this->load->view('homeprofile/homeprofileview', $data, $viewData, array('error' => ' ' ) );
$this->load->view('shared/footer');
}
}
Here is my view:
<div id="maincontent">
<div id="primary">
<?//=$error;?>
<?//=$img;?>
<h3><?="Profile Image"?></h3>
<img src="<?php echo'$img'?>" width='300' height='300'/>
<?=form_open_multipart('homeprofile/upload');?>
<input type="file" name="img" value=""/>
<?=form_submit('submit', 'upload')?>
<?=form_close();?>
<?php if (isset($error)) echo $error;?>
</div>
</div>
Your help is much appreciated

The Codeigniter Upload class says "You did not select a file to upload" because it's looking for the key userfile in the $_FILES array.
From the docs: http://codeigniter.com/user_guide/libraries/file_uploading.html
$this->upload->do_upload()
Performs the upload based on the preferences you've set. Note: By
default the upload routine expects the file to come from a form field
called userfile... If you would like to set your own field name
simply pass its value to the do_upload function:
$field_name = "some_field_name";
$this->upload->do_upload($field_name)
So you have two choices, change
<input type="file" name="img">
to
<input type="file" name="userfile">
... or change
$this->upload->do_upload()
to
$this->upload->do_upload('img')

Related

CodeIgniter make file uploads optional

I have found some examples of making the uploads optional but so far it hasn't work for me. I might have missed something so I'm hoping someone might catch it? This is the link to what I am following
https://blog.smalldo.gs/2013/03/optional-file-upload-field-codeigniter/
So far I am able to edit the product if I don't upload a file but if I upload a file, I get a you did not select a file to upload error. Please help. Thank you.
Controller
public function editProduct(){
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
$this->form_validation->set_rules('inputproductname', 'Name', 'trim|required');
$this->form_validation->set_rules('inputproductdescription', 'Description', 'trim|required');
$this->form_validation->set_rules('inputproductprice', 'Price', 'trim|required');
$inputproductname = $this->input->post('inputproductname');
$inputproductdescription = $this->input->post('inputproductdescription');
$inputproductprice = $this->input->post('inputproductprice');
$inputdateadded = date('Y-m-d');
$inputcurrentproductid = $this->input->post('inputcurrentproductid');
$inputcurrentproductstatus = $this->input->post('inputcurrentproductstatus');
$config['upload_path'] = $this->getProductImageFolderPath();
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = 3000;
$config['remove_spaces'] = TRUE;
$config['overwrite'] = TRUE;
$config['file_name'] = $inputproductname;
$this->load->library('upload', $config);
if($this->form_validation->run()==false){
$data['product'] = $this->ProductsModel->getProduct($inputcurrentproductid);
$data['edit'] = "true";
$data['message']='';
$data['inputcurrentproductid'] = $inputcurrentproductid;
$data['inputcurrentproductstatus'] = $inputcurrentproductstatus;
$this->load->view('control/controlMenu/navigationLink');
$this->load->view('control/controlProducts/productDetail',$data);
$this->load->view('control/controlMenu/navigationJquery');
}else{
if(isset($_FILES['upload'])&&$_FILES['upload']['size']>0){
if(!$this->upload->do_upload()){
$this->session->set_flashdata('Form',$this->upload->display_errors());
redirect('Control/ProductDetail/'.$inputcurrentproductid."/".$inputcurrentproductstatus);
}else{
$extension = $this->upload->data('file_ext');
$productdetails = array(
'name'=>$inputproductname,
'description'=>$inputproductdescription,
'price'=>$inputproductprice,
'imagePath'=>$config['upload_path'].$config['file_name'].$extension,
'dateAdded'=>$inputdateadded
);
$this->db->trans_start();
$this->ProductsModel->editProduct($inputcurrentproductid,$productdetails);
$error = $this->db->error();
$this->db->trans_complete();
if($this->db->trans_status()===false){
}else{
$this->session->set_flashdata('Form', $inputproductname . ' has been altered on the database');
redirect('/Control/Products');
}
if($error!=''){
$this->session->set_flashdata('Form',$error["message"]);
redirect('/Control/Products');
}
}
}else{
$productdetails = array(
'name'=>$inputproductname,
'description'=>$inputproductdescription,
'price'=>$inputproductprice
);
$this->db->trans_start();
$this->ProductsModel->editProduct($inputcurrentproductid,$productdetails);
$error = $this->db->error();
$this->db->trans_complete();
if($this->db->trans_status()===false){
}else{
$this->session->set_flashdata('Form', $inputproductname . ' has been altered on the database');
redirect('/Control/Products');
}
if($error!=''){
$this->session->set_flashdata('Form',$error["message"]);
redirect('/Control/Products');
}
}
}
You didn't tell the upload library from which field to take the file.
$this->upload->do_upload() // <-- no argument for this method provided
If no field name is provided, by default it tries to get the file from userfile field [docs], but your file input is called upload as seen in the code sample. So you should do
if(!$this->upload->do_upload("upload")){
Also, note that on the client side the form with file field should be declared as
<form method="post" action="some_action" enctype="multipart/form-data" />
otherwise file field will be empty too.

Is there a better way of multipart/form-data validation

I have a multipart/form-data with an image upload and some personal data, so I want to include file upload in form validation, I can successfully do this.
However, I now find that there is an issue, ie even if my other form fields have errors and upload file field with no error, then image uploads to folder, how to prevent this, I mean, in my case, If name, email, file fields validation is ok then only file should upload, if name filed validation fails and file field validation ok then file should not upload
here is the code I use:
In Controller:
<?php
public $_rules = array(
'name'=>array('field'=>'name', 'label'=>'Name', 'rules'=>'trim|required'),
'email'=>array('field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|valid_email'),
'profile_img'=>array('field'=>'profile_img', 'label'=>'Design', 'rules'=>'callback__profile_upload')
);
public function profile()
{
$this->load->library('upload');
$rules = $this->_rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==TRUE){
die('success');
}else {
$this->data['content'] = 'frontend/pages/place_order';
$this->load->view('frontend/_layout_main', $this->data);
}
}
function _profile_upload(){
if($_FILES['profile_img']['size'] != 0 && !empty($_FILES['profile_img']) ){
$upload_dir = './profile_pics/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir);
}
$config['upload_path'] = $upload_dir;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = 'profile_img_'.substr(md5(rand()),0,7);
$config['overwrite'] = false;
$config['max_size'] = '5120';
$this->upload->initialize($config);
if (!$this->upload->do_upload('profile_img')){
$this->form_validation->set_message('_profile_upload', $this->upload->display_errors());
return false;
}
else{
$this->upload_data['file'] = $this->upload->data();
return true;
}
}
else{
$this->form_validation->set_message('_profile_upload', "No file selected");
return false;
}
}
IN VIEW:
<?php echo form_open_multipart();?>
<?php $name_err = (!empty(form_error('name'))) ? 'err' : ' ';
echo form_input('name',set_value('name'), array('placeholder'=>'Name','class'=>" {$name_err } "));
?>
<?php $email_err = (!empty(form_error('email'))) ? 'err' : ' ';
echo form_input('email',set_value('email'), array('placeholder'=>'EMail','class'=>" {$email_err } "));
?>
<?php
echo form_error('profile_img');
echo form_upload(array('name' =>'profile_img', 'class' => 'inputfile inputfile-4', 'id' => 'profile_img'));
?>
<li><input type="submit" class="special" value="Submit" /></li>
Try once like this.I think for images not need to set rules like other fields.
public $_rules = array(
'name'=>array('field'=>'name', 'label'=>'Name', 'rules'=>'trim|required'),
'email'=>array('field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|valid_email'),
);
And
public function profile()
{
$this->load->library('upload');
$rules = $this->_rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==TRUE){
die('success');
}else {
if ($this->_profile_upload()) { //return true if file uploaded successfully otherwise error
$this->data['content'] = 'frontend/pages/place_order';
$this->load->view('frontend/_layout_main', $this->data);
}
}
}
yes that is very obvious that your file get uploads even any other fields' validation failed. You have to initiate image uploading only after form validation success.
For that simply validate file specific requirement in that callback, and do actual uploads after successful form validation.
I have got a solution from codexWorld, I have asked same question over there, and they replied with a tutorial, If anybody still looking for a solution here is the link
http://www.codexworld.com/codeigniter-file-upload-validation/
in the validation call back, we just want to do the file type check
public function _profile_upload($str){
$allowed_mime_type_arr = array('image/jpeg','image/pjpeg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['file']['name']);
if(isset($_FILES['file']['name']) && $_FILES['file']['name']!=""){
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message('_profile_upload', 'Please select only pdf/gif/jpg/png file.');
return false;
}
}else{
$this->form_validation->set_message('_profile_upload', 'Please choose a file to upload.');
return false;
}
}
and in the main function we just want to do the same as normal, using do_upload and specifying the upload config items, anyhow there will be a second file type check when the function executes, I think that doesn't matter. The code will look like this::
public function profile()
{
$rules = $this->_rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==TRUE){
$config['upload_path'] = 'uploads/files/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024;
$this->load->library('upload', $config);
//upload file to directory
if($this->upload->do_upload('file')){
$uploadData = $this->upload->data();
$uploadedFile = $uploadData['file_name'];
/*
*insert file information into the database
*.......
*/
}else{
$data['error_msg'] = $this->upload->display_errors();
}
}else {
$this->data['content'] = 'frontend/pages/place_order';
$this->load->view('frontend/_layout_main', $this->data);
}
}

Update picture/image in Codeigniter

I'm trying to create update image for user who want to change their photo.The when i click submit on photo upload, there is no photo uploaded and photo's column still no update.
Here is my Contorller:
function foto($id='')
{
$data['data'] = $this->user_model->get_foto($id);
$data['form_action'] = site_url("user/update_foto/$id");
$this->load->view('user/foto_form', $data);
}
function update_foto($id=''){
$this->user_model->update_foto($id);
}
Here is My model:
function get_foto($id=0){
$id = $this->session->userdata('id');
$sql = "SELECT id,foto FROM user WHERE id= '$id'";
$query = $this->db->query($sql);
$data = $query->row_array();
return $data;
}
function update_foto(){
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|png|jpeg';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('foto'))
{
$id_user=$this->session->userdata('id');
redirect ("user/foto/$id_user");
} else {
$id_user=$this->session->userdata('id');
$data=array(
'foto'=>$this->input->post('foto')
);
$this->db->where('id',$id_user);
$this->db->update('user',$data);
redirect("user");
}
}
And this is my upload form on view:
<form role="form" action="<?php echo $form_action ?>" class="form-horizontal style-form" method="POST" enctype="multipart/form-data">
<label >Upload Foto</label>
<input type="file" name="foto"/>
<button type="submit">Save</button>
</form>
Any Answer? Many thanks for the answer...
On your controller try replacing this
from
site_url("user/update_foto/$id");
to
site_url("user/update_foto") ./. $id;
Or you could use uri segment refer user guide.
site_url("user/update_foto") ./. $this->uri->segment(4); // unsure id check uri segment in url.
Your route may need to be changed
$route['user/update_foto/(:any)'] = "controllername/foto/$1";
All ways make sure the controller has index()
At your model this is wrong.
$data=array(
'foto'=>$this->input->post('foto')
);
$this->input->post('foto') does not get your file name.
You can try that with this
else {
$id_user=$this->session->userdata('id');
$info=$this->upload->data();
$data=array(
'foto'=>$info['file_name']
);
$this->db->where('id',$id_user);
$this->db->update('user',$data);
redirect("user");
}
better use this line for your upload path
$config['upload_path'] = FCPATH.'upload/';
$file_name = "";
if ($_FILES['foto']['error']!= 4) {
$fileParts = pathinfo($_FILES['foto']['name']);
$file_name = time() . '.' . $fileParts['extension'];
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $file_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$this->upload->do_upload('foto');
}

how to submit file using jquery to codeigniter controller

May I ask for your help guys!
I am trying to upload a file and passing all the data to codeigniter controller using jquery.
my view file:
<div class="form-group">
<label class="col-md-4 control-label">Item Image</label>
<div class="col-md-8">
<input class="form-control" type="file" placeholder="" id="itemImage" name="itemImage" data-parsley-required="true" />
</div>
</div>
<button type="button" onclick="add_item();">Sumit</button>
<script>
function add_item(){
$.post('<?php echo site_url('admin_newitem/add_item'); ?>',
{
itemId : $('#itemId').val(),
itemImage : $('#itemImage').val()
},
function(data){
if(data.result=='SUCCESS'){
$('#itemId').val('');
$('#itemImage').val('');
//show success
}else{
//show error
}
},'json'
);
}
</script>
My controller:
function add_item(){
$this->output->set_status_header(200);
$this->output->set_header('Content-Type: application/json');
$itemId = $this->input->post('itemId');
$itemImage = $this->input->post('itemImage');;
$config['upload_path'] = realpath(APPPATH.'../assets_main/img/item/');
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '200';
$config['max_height'] = '200';
$file_name = $config['file_name'] = md5(uniqid(mt_rand()));
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if(!$itemImage){
$jdata['result'] = "FAILED";
$jdata['message'] = "upload error.";
$jdata['field'] = "itemImage";
echo json_encode($jdata);
exit();
}
$data = array('upload_data' => $this->upload->data());
$jdata['message'] = "Thank you for purchasing our item!";
$jdata['result'] = "SUCCESS";
echo json_encode($jdata);
exit();
}
I was able to get the ItemId, and ItemImage but when I check the folder where the image is suppose to be located, it's not there. I think I fail to capture the real file, so, is there a way for me to get this done?
As you suggest, I believe that you are forgetting to actually do the upload, the code igniter documentation might help:
http://www.codeigniter.com/user_guide/libraries/file_uploading.html
With this correctly implemented, I think your code should look something similar to:
function add_item(){
$this->output->set_status_header(200);
$this->output->set_header('Content-Type: application/json');
$itemId = $this->input->post('itemId');
$itemImage = $this->input->post('itemImage');;
$config['upload_path'] = realpath(APPPATH.'../assets_main/img/item/');
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '200';
$config['max_height'] = '200';
$file_name = $config['file_name'] = md5(uniqid(mt_rand()));
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
//THE MISSING LINE
if($this->upload->do_upload()){
//THE FILE HAS NOW BEEN UPLOADED
$data = array('upload_data' => $this->upload->data());
$jdata['message'] = "Thank you for purchasing our item!";
$jdata['result'] = "SUCCESS";
echo json_encode($jdata);
exit();
}else{
//NO FILE UPLOADED
$jdata['result'] = "FAILED";
$jdata['message'] = "upload error.";
$jdata['field'] = "itemImage";
echo json_encode($jdata);
exit();
}
}
My initial thinking, having used CI and tried to do this same thing, is that you can't do file uploads via AJAX without a special plugin such as this:
http://malsup.com/jquery/form/
Specifically, this file upload portion:
http://malsup.com/jquery/form/#file-upload
Simply trying to send a post with the val of a file input will not work, I don't believe - though maybe more modern browsers are able to handle that now.

want to store multiple file path in database

Hi i want to store multiple file path in database, but the following code is storing just one file path
Kindly some one help.
My Controller
<?php
class upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view("header.php");
$this->load->view('main_views', array('error' => ' ' ));
$this->load->view("footer.php");
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2000';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
// no file uploaded or failed upload
$error = array('error' => $this->upload->display_errors());
$this->load->view("header.php");
$this->load->view('main_views', $error);
$this->load->view("footer.php");
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->model('post_model');
$this->post_model->main_model();
$this->load->view("header.php");
$this->load->view('main_views');
$this->load->view("footer.php");
}
}
?>
My Model
<?php
class post_model extends CI_Model
{
function main_model()
{
$filepath = $this->upload->data()['file_name'];
$this->db->trans_begin();
$this->db->query("insert into post (post_pic)
values ('$filepath')");
$ad_id = $this->db->insert_id();
}
}
?>
Views
<span id="filediv"><input name="userfile" type="file" id="file"/>
</span>
<span id="filediv"><input name="userfile2" type="file" id="file"/>
</span>
<span id="filediv"><input name="userfile3" type="file" id="file"/>
</span>
<span id="filediv"><input name="userfile2" type="file" id="file"/></span><br/>
extra text due to parsing rule kindly ignore it extra text due to parsing rule kindly ignore it extra text due to parsing rule kindly ignore it extra text due to parsing rule kindly ignore it extra text due to parsing rule kindly ignore it
Views
- input name change to name="userfile[]"
You can use multiple upload of codeignter
https://github.com/stvnthomas/CodeIgniter-Multi-Upload
Thanks
You have to upload each $_FILES
foreach ( $_FILES as $key => $value ) {
if (! empty ( $value ['name'] )) {
//change the file name
$config ['file_name'] = date('Y_m_d') . '_' . $value ['name'];
$this->upload->initialize($config);
if (! $this->upload->do_upload ( $key )) {
// handle error function
$this->handle_error ( $this->upload->display_errors () );
} else {
$files [$i] = $this->upload->data ();
++ $i;
}
}
}
Here in $files array you will get the details of the uploaded files which can be used further for model to insert into database the path of the files.

Categories