Error submitting a form with upload pic option. PHP Codeigniter - php

I've been trying to upload a pic to a folder and store its path in the database, my code seems to work correctly, but no it's not, After i click submit button, it goes to a blank page.
Using Inspect element, Network option in my browser, when seeing the parameters sent
I see correct input from the text fields but for the image,
Content-Disposition: form-data; name="myimage"; filename="IMG_8971.JPG"
Content-Type: image/jpeg
Plus some other weirly looking characters and symbols like :
ÿØÿà
CONTROLLER:
private function setup_upload_option()
{
$config = array();
$config['upload_path'] = 'blog/uploads/';
$config['allowed_type']='jpg|jpeg|png|gif';
$config['encrypt_name']= TRUE;
$config['overwrite']=FALSE;
return $config;
}
public function post_new_blog()
{
$this->form_validation->set_rules('title', 'Title of the Blog', 'trim|required');
$this->form_validation->set_rules('desc', 'Content of the Blog', 'trim|required');
$this->form_validation->set_rules('tags', 'Tags fo the blog', 'trim|required');
if($this->form_validation->run()==FALSE) {
$this->session->set_flashdata('fail', validation_errors());
$this->load->view('blogsection/addblog', array('logged_in' => $this->logged_in));
}
else {
$this->load->library('upload');
$files = $_FILES;
$count = count($_FILES['myimage']['name']);
for($i=0; $i<$count ;$i++)
{
$_FILES['myimage']['name'] = $files['myimage']['name'][$i];
$_FILES['myimage']['type'] = $files['myimage']['type'][$i];
$_FILES['myimage']['size'] = $files['myimage']['size'][$i];
$_FILES['myimage']['tmp_name'] = $files['myimage']['tmp_name'][$i];
$this->upload->initialize($this->setup_upload_option());
if($this->upload->do_upload()==TRUE)
{
$data = $this->upload->data();
$config1['image_library'] = 'gd2';
$config1['source_image'] = $data['full_path'];
$config1['new_image'] = 'blog/uploads/thumbs/';
$config1['create_thumb'] = false;
$config1['height'] = 200;
$config['width'] = 200;
$this->load->library('image_lib', $config1);
$this->image_lib->initialize($config1);
$this->image_lib->resize();
$mydata = $this->session->all_userdata();
$dataarray = array(
'blog_title' => $this->input->post('title', true),
'blog_content' => $this->input->post('desc', true),
'blog_tags' => $this->input->post('tags', true),
'blog_image_name' => $data['orig_name'],
'blog_image' => $data['full_path'],
'date_posted' => date(" jS \of F Y "),
'posted_by' => $mydata['username']
);
$this->main_model->save_new_posts($dataarray);
$this->load->view('blogsection/addblog', array('logged_in' => $this->logged_in, 'success' => 'Blog was posted successfully',$dataarray));
}
}
}
}
MODEL:
public function save_new_posts($dataarray)
{
$this->db->insert('blogs', $dataarray);
if($this->db->affected_rows()>0)
{
return true;
}
}

i have code that always works, it is some what different from you method i hope it will help you.
$imgpath='uploads/profile_pic/';
$all_img="";
if($_FILES["profile_pic"]['name'])//form input type file
{
$path_parts = pathinfo($_FILES["profile_pic"]["name"]);
$image_path = $path_parts['filename'].'_'.time().'.'.$path_parts['extension'];
$all_img.=$image_path;
move_uploaded_file($file_tmp=$_FILES["profile_pic"]["tmp_name"],$imgpath."/".$image_path);
$data['cm_user_profile_pic']=$all_img;//store image name in array
}

Related

How to remove this error: The filetype you are attempting to upload is not allowed

public function addAppdetails()
{ $dev_id = $this->sessionStart();
$this->load->library('form_validation');
$this->form_validation->set_rules('appname', 'App Name', 'required');
$this->form_validation->set_rules('platform', 'Platform', 'required');
//$this->form_validation->set_rules('category','App Category','required');
$this->form_validation->set_rules('description', 'App Description', 'required');
//$this->form_validation->set_rules('app_pic','App Pic','required');
//$this->form_validation->set_rules('file','App File','required');
if ($this->form_validation->run())
{
$appname = $this->input->post('appname');
$platform = $this->input->post('platform');
$category1 = $this->input->post('category');
$descripton = $this->input->post('description');
$category = implode(",", $category1);
echo "l";
$data1=$this->appFileupload();
echo "Break";
$data2=$this->appImageupload();
die;
foreach ($data1 as $dataArray)
{
$fileName=$dataArray['file_name'];
}
foreach ($data2 as $dataArray)
{
$imageName=$dataArray['file_name'];
}
$data = array('name' => $appname, 'platform' => $platform, 'description' => $descripton, 'category' => $category,'file_name'=>$fileName,'image_name'=>$imageName,'dev_id'=>$dev_id);
$this->Dev_model->addApp($data);
//$this->appImageupload();
echo "yolo";
}
else
{
$data['dataArray'] = $this->sessionStart();
$category = $this->input->post('category');
print_r($category);
$this->load->view('dev/addApp', $data);
}
}
public function appFileupload()
{
$config1['upload_path'] = './uploads/files';
$config1['allowed_types'] = 'apk|exe';
$this->load->library('upload', $config1);
if ( ! $this->upload->appFileUpload('file'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
public function appImageupload()
{
$config2['upload_path'] = './uploads/appImages';
$config2['allowed_types'] = 'gif|jpg|png';
$config2['max_size'] = 1000000000;
$config2['max_width'] = 10240000;
$config2['max_height'] = 76800000;
$this->load->library('upload', $config2);
if ( ! $this->upload->appImageUpload('app_pic'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
The output is as follows:
lBreak
Array ( [error] =>
The filetype you are attempting to upload is not allowed.
)
So, if I exchange the positions of appFileupload() and appImageupload() then it will give the same error for 'apk|exe' file and right now it is giving the error for appImageupload(). If you will ask how do I know about this? Then the answer is, I have checked their folder one gets uploaded but not the other.
CodeIgniter version is: 3.x
Add * in place of another type.
$config['allowed_types'] = '*';
I am just suggesting this for test purpose
Edit:
I am not sure but this will be helpful.
You could try looking at system/libraries/Upload.php line 199:
$this->_file_mime_type($_FILES[$field]);
Change that line to:
$this->_file_mime_type($_FILES[$field]); var_dump($this->file_type); die();
Well Lol, I'm answering my own question.
First, loading the library again with $config2 won't work because the library is already loaded once and $config1 will stay loaded. To load a new config use:
$this->upload->initialize($config2);

Why I'm getting this error: The filetype you are attempting to upload is not allowed

public function addAppdetails()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('appname', 'App Name', 'required');
$this->form_validation->set_rules('platform', 'Platform', 'required');
//$this->form_validation->set_rules('category','App Category','required');
$this->form_validation->set_rules('description', 'App Description', 'required');
//$this->form_validation->set_rules('app_pic','App Pic','required');
//$this->form_validation->set_rules('file','App File','required');
if ($this->form_validation->run()) {
$appname = $this->input->post('appname');
$platform = $this->input->post('platform');
$category1 = $this->input->post('category');
$descripton = $this->input->post('description');
$category = implode(",", $category1);
$data = array('name' => $appname, 'platform' => $platform, 'description' => $descripton, 'category' => $category);
$this->appImageupload();
die;
$this->Dev_model->addApp($data);
} else {
$data['dataArray'] = $this->sessionStart();
$category = $this->input->post('category');
print_r($category);
$this->load->view('dev/addApp', $data);
}
}
public function appImageupload()
{
$config['upload_path'] = './uploads/appImages';
$config['allowed_types'] = 'exe';
$config['file_type'] = 'exe';
$config['max_size'] = 1000000000;
$this->load->library('upload', $config);
if ( ! $this->upload->appImageUpload('app_pic'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
}
The function appImageupoad is for uploading '.exe' files. So whenever I try to upload an executable file it gives the error. But if I change the $config['allowed-type] to .jpg or any image file extension then gets uploaded.
P.S.I have also tried the same thing in do_upload() it gives the same error.
You can also remove these lines of code
$config['file_type'] = 'exe';
$config['max_size'] = 1000000000;
You already specified allowed types allowed_types
Give it a try and if works then you can apply another validations as well

how can i upload a video and it saved to a folder in codeigniter?

i'm new to codeigniter. i need help to upload a picture and video and save it to folder and database.
here is my controller
public function upload()
{
$this->m_upload->upload();
$this->upload_gambar();
}
public function upload_gambar()
{
//load the helper
$this->load->helper('form');
$config['upload_path'] = 'assets/gallery/images';
$config['allowed_types'] = 'gif|jpg|png|mp4';
$config['max_size'] = '';
$this->load->library('upload', $config);
$this->upload->initialize($config);
$this->upload->set_allowed_types('*');
$data['upload_data'] = '';
$this->upload->do_upload('uploadan');
redirect(c_upload);
}
and this is my models
public function upload()
{
$title = $this->input->post('title');
$details = $this->input->post('details');
$type = $this->input->post('gallery');
$picture = $_FILES['uploadan']['name'];
$data = array(
'url' => $picture,
'title' => $title,
'details' => $details,
'category' => $type
);
$this->db->insert('gallery', $data);
}
i've already set upload_max_filesize and post_max_size in the php.ini but it still not working. please help me fix this problem. thankyou
Try this
In Controller
$configVideo['upload_path'] = 'assets/gallery/images'; # check path is correct
$configVideo['max_size'] = '102400';
$configVideo['allowed_types'] = 'mp4'; # add video extenstion on here
$configVideo['overwrite'] = FALSE;
$configVideo['remove_spaces'] = TRUE;
$video_name = random_string('numeric', 5);
$configVideo['file_name'] = $video_name;
$this->load->library('upload', $configVideo);
$this->upload->initialize($configVideo);
if (!$this->upload->do_upload('uploadan')) # form input field attribute
{
# Upload Failed
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('controllerName/method');
}
else
{
# Upload Successfull
$url = 'assets/gallery/images'.$video_name;
$set1 = $this->Model_name->uploadData($url);
$this->session->set_flashdata('success', 'Video Has been Uploaded');
redirect('controllerName/method');
}
In Model
public function uploadData($url)
{
$title = $this->input->post('title');
$details = $this->input->post('details');
$type = $this->input->post('gallery');
$data = array(
'url' => $url,
'title' => $title,
'details' => $details,
'category' => $type
);
$this->db->insert('gallery', $data);
}
Add mimes code for media file in:
application/config/mimes.php
especially for mp4

in codeigniter2.1.4,is it mandatory pass the file's field name in do_upload function or not

I'm curious to know in $this->upload->do_upload('img') field name is passing mandotory not.I have seen several example in stackoverflow where do_upload() not taking any argument as file field name.But in case of mine without field name file not uploaded.I want to know which is correct syntax?
2)How do i bypass the file upload validation when there is no file being uploaded.If there is no file(image) in the form then $this->upload->display_errors() will not be called.my code is below
function add()
{
if ($this->input->server('REQUEST_METHOD') === 'POST')
{
$this->form_validation->set_rules('category', 'Category Name', 'required');
if ($this->form_validation->run())
{
$data_to_store = array(
'category' => $this->input->post('category'),
'description' => $this->input->post('description'),
'parent'=>'0'
);
$last_id=$this->admin_category_model->add_category($data_to_store);
$config['upload_path'] ='./uploads/';
$config['allowed_types'] = 'gif|jpg|png|GIF|JPG|PNG';
$config['remove_spaces'] = TRUE;
$config['max_size'] = '0';
$config['file_name'] =$last_id.'_'.$_FILES['img']['name'];
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if($this->upload->do_upload('img'))
{
$data = array('upload_data' => $this->upload->data());
$config2['image_library'] = 'gd2';
$config2['source_image'] = $data['upload_data']['full_path'];
$config2['new_image'] ='./uploads/thumb/'.$data['upload_data']['file_name'];
$config2['create_thumb'] = FALSE;
$config2['maintain_ratio'] = TRUE;
$config2['width'] = 35;
$config2['height'] = 35;
$this->load->library('image_lib',$config2);
$this->image_lib->resize();
$data_to_store = array(
'img' => $config['file_name'],
);
$this->admin_category_model->update_category($last_id,$data_to_store);
$this->session->set_flashdata('flash_message', 'Record Added');
redirect('admin_category/index');
}
else
{
$data['error']=$this->upload->display_errors();
}
}
}
$data['title']='Add Category';
$data['main_content'] = 'admin/add_category';
$this->load->view('admin/includes/template', $data);
}
1st) No, not necessary, by default it will take the name userfile.
2nd) Say for example your fieldname is img check like this:
if( $_FILES['img']['name'] != "" ){
//your upload code here
}

Modifying My Image Uploader

At this present point in time I have some code that does the following:
I can edit and I can add a house sale that uploads/edits one image for this particular house and then during the process a thumbnail is created and then the original file name and the thumbnail name is saved to database fields called imagename and imagethumb.
(Note: Add and Edit a seprate pages)
What my idea is:
I will create another page that has the name of the houses fed into a dropdown menu so when one is selected and images are selected they will upload.
What my issue is:
I am getting myself confused as to what would be the best way to modify my database to enable this change.
How would I modify my php code to handle more then one file (How do I handle multiple images and then pass the image for uploading resizing etc ) What is the best option? - within my given idea?
Could I have an example of what I should do so I can work off this.
I have included the model view and controller (As an Example) of my Add Sale but I will also need to edit a image for the respective sale.
Model:
class Sales_model extends CI_Model
{
function __construct() {
parent::__construct();
}
function getSalesPage($id = NULL) {
$query = $this->db->get_where('sales', array('id' => $id), 1);
if($query->num_rows() == 1) return $query->row();
} # End getSalesPage
function getSalesPages($id = NULL) { // $id does nothing
$query = $this->db->get('sales');
if($query->num_rows() > 0) return $query->result();
} # End getSalesPages
function getSalesContent($id = NULL) {
$this->db->where('id', $id);
$query = $this->db->get('sales', 1);
if($query->num_rows() > 0) {
$row = $query->result_array();
return $row;
}else{
return FALSE;
} # End IF
} # End getSalesContent
function addSale($data = NULL) {
$this->db->insert('sales', $data);
return TRUE;
} # End Add Sale
function updateSale($id, $content) { //Content id from being passed
$this->db->where('id', $id); // selecting the $id to update
$update = $this->db->get('sales'); // What does $update = well it = get the db sales
$row = $update->row_array(); // what does $row mean = well it gets the row as an array
if($update->num_rows() > 0) {
if(isset($content['imagename']) && isset($content['thumbname'])) {
#lets delete the image
unlink("/includes/uploads/gallery/".$row['imagename']);
#lets delete the thumb.
unlink("/includes/uploads/gallery/thumbs/".$row['thumbname']);
}
$this->db->where('id', $id);
if($this->db->update('sales', $content))
{
return TRUE;
}
else
{
return FALSE;
}
} # End IF
} # End Update
function deleteSale($id){
$this->db->where('id', $id);
$q = $this->db->get('sales');
$row = $q->row_array();
if ($q->num_rows() > 0){
//delete from the database
$this->db->where('id', $id);
$this->db->delete('sales');
//lets delete the image
unlink("includes/uploads/sales/".$row['imagename']);
//lets delete the thumb.
unlink("includes/uploads/sales/thumbs/".$row['thumbname']);
}//END if num_rows
}//END function deleteSale($id)
} # End Model
View:
<?php
//Setting form attributes
$formAddSale = array('id' => 'addSale', 'name' => 'addSale');
$saleName = array('id' => 'name', 'name' => 'name','class' => 'validate[required[custom[onlyLetterSp]]]', 'value' => set_value('name'));
$saleLocation = array('id' => 'location', 'name' => 'location','class' => 'validate[required[custom[onlyLetterSp]]]', 'value' => set_value('location'));
$saleBedrooms = array('id' => 'bedrooms','name' => 'bedrooms','class' => 'validate[required[custom[number]]]', 'value' => set_value('bedrooms'));
$saleBathrooms = array('id' => 'bathrooms','name' => 'bathrooms','class' => 'validate[required[custom[number]]]', 'value' => set_value('bathrooms'));
$saleCondition = array('id' => 'condition','name' => 'condition','class' => 'validate[required[custom[onlyLetterSp]]]', 'value' => set_value('condition'));
$saleImage = array('id' => 'userfile', 'name'=> 'userfile');
$salePrice = array('id' => 'price','name' => 'price','class' => 'validate[required[custom[number]]]','value' => set_value('price'));
$saleDescription = array('id' => 'description','name' => 'description','class' => '', 'value' => set_value('description'));
$saleSubmit = array('id' => 'submit', 'name'=> 'submit', 'value' => 'Add Sale');
?>
<div id ="formLayout">
<?php
if($success == TRUE) {
echo '<section id = "validation">Sale Added</section>';
}
echo '<section id = "validation">'.$message['imageError'].'</section>';
?>
<?php echo form_open_multipart('admin/addsale/', $formAddSale); ?>
<?php echo form_fieldset(); ?>
<?php echo form_label('Name:','name'); ?>
<?php echo form_input($saleName); ?>
<div id="errorName"><?php echo form_error('name'); ?></div>
<span class="small">Required Field - Text</span>
<?php echo form_label('Location:','location');?>
<?php echo form_input($saleLocation);?>
<div id="errorLocation"><?php echo form_error('location'); ?></div>
<span class="small">Required Field - Text</span>
<?php echo form_label('Bedrooms: ','bedrooms');?>
<?php echo form_input($saleBedrooms);?>
<div id="errorBedrooms"><?php echo form_error('bedrooms'); ?></div>
<span class="small">Required Field - Number</span>
<?php echo form_label('Bathrooms: ','bathrooms');?>
<?php echo form_input($saleBathrooms);?>
<div id="errorBathrooms"><?php echo form_error('bathrooms'); ?></div>
<span class="small">Required Field - Number</span>
<?php echo form_label('Condition: ','condition');?>
<?php echo form_input($saleCondition);?>
<div id="errorCondition"><?php echo form_error('condition'); ?></div>
<span class="small">Required Field - Text</span>
<?php echo form_label('Price: ','price');?>
<?php echo form_input($salePrice);?>
<div id="errorPrice"><?php echo form_error('price'); ?></div>
<span class="small">Required Field - Number</span>
<?php echo form_label('Image: ','userfile');?>
<?php echo form_upload($saleImage);?>
<div id="errorUserfile"><?php echo form_error('userfile'); ?></div>
<span class="small">Required Field - 1MB Max Size</span>
<?php echo form_label('Description: ','description');?>
<div id="errorDescription"><?php echo form_error('description'); ?></div>
<span class="small">Required Field - Text</span>
<?php echo form_textarea($saleDescription);?>
<script type="text/javascript">CKEDITOR.replace('description');</script>
<?php echo form_submit($saleSubmit);?>
<?php echo form_fieldset_close(); ?>
<?php echo form_close(); ?>
</div>
Controller:
class Addsale extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
if(!$this->session->userdata('logged_in'))redirect('admin/home');
# Main Data
$data['title'] = 'Add Sale: ';
//Set Validation
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('location', 'Location', 'trim|required|xss_clean');
$this->form_validation->set_rules('bedrooms', 'Bedrooms', 'trim|numeric|required|xss_clean');
$this->form_validation->set_rules('bathrooms', 'Bathrooms', 'trim|numeric|required|xss_clean');
$this->form_validation->set_rules('condition', 'Condition', 'trim|required|xss_clean');
$this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean');
$this->form_validation->set_rules('price', 'Price', 'trim|required|xss_clean');
if($this->form_validation->run()) {
//Set File Settings
$config['upload_path'] = 'includes/uploads/sales/';
$config['allowed_types'] = 'jpg|png';
$config['remove_spaces'] = TRUE;
$config['overwrite'] = TRUE;
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()) {
$data['message'] = array('imageError' => $this->upload->display_errors());
} // Upload error end
else{
$data = array('upload_data' => $this->upload->data());
$data['success'] = TRUE;
$config['image_library'] = 'GD2';
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['new_image'] = 'includes/uploads/sales/thumbs/';
$config['create_thumb'] = 'TRUE';
$config['thumb_marker'] ='_thumb';
$config['maintain_ratio'] = 'FALSE';
$config['width'] = '150';
$config['height'] = '150';
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$file_info = $this->upload->data();
$this->db->escape($content);
$content = array(
'name' => $this->input->post('name', TRUE),
'location' => $this->input->post('location', TRUE),
'bedrooms' => $this->input->post('bedrooms', TRUE),
'bathrooms' => $this->input->post('bathrooms', TRUE),
'condition' => $this->input->post('condition', TRUE),
'description' => $this->input->post('description', TRUE),
'price' => $this->input->post('price', TRUE),
'imagename' =>$file_info['file_name'],
'thumbname' =>$file_info['raw_name'].'_thumb'.$file_info['file_ext']
);
$this->sales_model->addSale($content);
}#end else
} # End Form Validation
$data['content'] = $this->load->view('admin/addsale', $data, TRUE);
$data['sales_pages'] = $this->sales_model->getSalesPages();
$data['cms_pages'] = $this->navigation_model->getCMSPages();
$this->load->view('admintemplate', $data);
} # End Index Function
} # End Controller
For handling dropdown, i think its easy one. But related multi upload stuff, you can use something like...
in your view
<?php echo form_label('Image: ','userfile1');?>
<?php echo form_upload('userfile1');?>
<?php echo form_label('Image: ','userfile2');?>
<?php echo form_upload('userfile2');?>
<!-- and so on -->
<span class="small">Required Field - 1MB Max Size</span>
Then in your controller, you can do this way
//Set File Settings
$config['upload_path'] = 'includes/uploads/sales/';
$config['allowed_types'] = 'jpg|png';
$config['remove_spaces'] = TRUE;
$config['overwrite'] = TRUE;
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
// Validate files for upload section...
$success = array();
$errors = array();
$updload_files = array(
'userfile1' => $_FILES['userfile1'],
'userfile2' => $_FILES['userfile2'],
// You can add more
);
foreach($updload_files as $field => $updload_file)
{
// Only process submitted file
if($updload_file['error'] == 0)
{
// If there is an error, save it to error var
if( ! $this->upload->do_upload($field) )
{
$errors[] = 'Failed to upload '.$field;
}
// Use this to get the new file info if you need to insert it in a database
$success[] = array( 'Success to upload '.$field => $this->upload->data());
}
else
{
$errors[] = $field . ' contain no data';
}
}
// Heres you could gettin know whats happen
var_dump($errors);
var_dump($success);

Categories