I am trying to check if the upload file field (<input type="file" name="userfile">) is empty or other validation on image upload field. In the view I echo <?php echo $upload_error;?> but it says $upload_error is Undefined variable. what is the problem with my code and how can i fix that.
This is my controller function
function add_main_products(){
$this->form_validation->set_rules('product_name', 'Main Product Category', 'required');
if ($this->form_validation->run() == FALSE){
$this->load->view('admin/admin_add_mainproduct');
}
else{
$config['upload_path'] = 'application/views/uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
if (! $this->upload->do_upload('userfile')){
$error['upload_error'] = array('error' => $this->upload->display_errors());
$this->load->view('admin/admin_add_mainproduct', $error);
return FALSE;
}
$this->mod_products->add_main_product($this->upload->data());
$data = array('upload_data' => $this->upload->data());
$data['result']="Main Product Added Successfully";
$this->load->view('admin/admin_add_mainproduct', $data);
}
}
Not sure if I understand your question properly but you can set rules the same way for file input:
$this->form_validation->set_rules('userfile', 'Image', 'required');
Let me know if this helps
Related
I am a newbie programmer and I'm not really good in English. I will ask a question about my code. I'm getting confused when I input an image and save it to database in phpmyadmin. The noimage.jpg is displayed even when I input another file. Please help me solve the problem. Thankyou
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
}
else {
$config['upload_path'] = './assets/images/posts';
$config['allowed_types'] ='gif|jpg|png';
$config['max_size'] ='2048';
$config['max_width'] ='500';
$config['max_height'] ='500';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile')) {
$error = array(
'error' => $this->upload->display_errors()
);
$post_image ='noimage.jpg';
}
else {
//if uploaded
$data = array('upload_data' => $this->upload->data());
$post_image= $_FILES['userfile']['name'];
}
$this->post_model->create_post($post_image);
redirect('posts');
}
I am new to CI and I am learning it through tutorials on Youtube. I am trying to upload image with what I found on tutorial here but unfortunately its not working. Below are the codes please help me.
Controller
public function create() {
$data['title'] = 'Create Post';
$data['desc'] = 'Feel free to create a new post here.';
$data['categories'] = $this->post_model->get_categories();
$this->form_validation->set_rules('title', 'Post Title', 'required');
$this->form_validation->set_rules('desc', 'Post Description', 'required');
if($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
} else {
// Upload Image
$config['upload_path'] = './assets/images/posts';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 500;
$config['max_height'] = 500;
$this->upload->initialize($config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'noimage.jpg';
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->post_model->create_post($post_image);
return redirect('posts');
}
}
Model
public function create_post($post_image) {
$slug = url_title($this->input->post('title'));
$data = array(
'post_title' => $this->input->post('title'),
'post_slug' => $slug,
'post_desc' => $this->input->post('desc'),
'post_cat_id' => $this->input->post('catid'),
'post_image' => $post_image
);
return $this->db->insert('posts', $data);
}
View
<?php echo form_open_multipart('posts/create'); ?>
<div class="form-group">
<label>Post Title</label>
<?php echo form_input(['name'=>'title', 'placeholder'=>'Add Title', 'class'=>'form-control', 'value'=>set_value('title')]); ?>
</div>
<div class="form-group">
<label>Select Category</label>
<select name="catid" class="form-control">
<?php foreach($categories as $category): ?>
<option value="<?php echo $category['cat_id']; ?>"><?php echo $category['cat_name']; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Post Description</label>
<?php echo form_textarea(['name'=>'desc', 'placeholder'=>'Add Description', 'class'=>'form-control', 'value'=>set_value('desc')]); ?>
</div>
<div class="form-group">
<label>Upload Image</label>
<input type="file" name="userfile" size="20">
</div>
<input type="submit" class="btn btn-primary" value="Add Post">
Now whenever I try to create a post with an image it executes if(!$this->upload->do_upload()){ as TRUE and thus inserts noimage.jpg in database as well as image is not uploaded too. Any help would be appreciated. Thanks.
EDIT
On trying to DEBUG it using print_r($this->upload->data()); die(); I got an empty list of array which means the file is not getting submitted from the form itself on the first place. But why? I don't find any error in the form.
Array
(
[file_name] =>
[file_type] =>
[file_path] => ./assets/images/posts/
[full_path] => ./assets/images/posts/
[raw_name] =>
[orig_name] =>
[client_name] =>
[file_ext] =>
[file_size] =>
[is_image] =>
[image_width] =>
[image_height] =>
[image_type] =>
[image_size_str] =>
)
and print_r($errors) give this error. I am close to solve now I guess.
Array
(
[error] =>
The image you are attempting to upload doesn't fit into the allowed dimensions.
)
SOLUTION
I had to change the max_width and max_height to 0 for unlimited. The image was not being uploaded due to this error.
If you think your code is correct. Have you checked folder permissions?
You have to give permission to folders in order to store images
Forget to load upload library do like this :
$this->load->library('upload', $config);
The whole code (file uploading part) should be like this :
else {
// Upload Image
$config['upload_path'] = FCPATH.'assets/images/posts';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 500;
$config['max_height'] = 500;
$this->load->library('upload', $config);
if($this->upload->do_upload('userfile'))
{
print_r($this->upload->data());die;
$file_name = $this->upload->data('file_name');
$post_image = $file_name;
}
else
{
$errors = array('error' => $this->upload->display_errors());
print_r($errors);die;
$post_image = 'noimage.jpg';
}
$this->post_model->create_post($post_image);
return redirect('posts');
}
try following changes
$config['upload_path'] = './assets/images/posts'; **to** $config['upload_path'] = getcwd().'/assets/images/posts';
You must remove library upload from autoloading and edit code like this.
if($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
} else {
// Upload Image
$config['upload_path'] = './assets/images/posts';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 500;
$config['max_height'] = 500;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload('userfile')){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'noimage.jpg';
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->post_model->create_post($post_image);
return redirect('posts');
}
try this code!
public function create() {
$data['title'] = 'Create Post';
$data['desc'] = 'Feel free to create a new post here.';
$data['categories'] = $this->post_model->get_categories();
$this->form_validation->set_rules('title', 'Post Title', 'required');
$this->form_validation->set_rules('desc', 'Post Description', 'required');
if($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
} else {
// Upload Image
$config['upload_path'] = './assets/images/posts';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 500;
$config['max_height'] = 500;
$this->load->library('upload');
$this->upload->initialize($config);
if(!$this->upload->do_upload('userfile'))
{
$errors = array('error' => $this->upload->display_errors());
$post_image = 'noimage.jpg';
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->post_model->create_post($post_image);
return redirect('posts');
}
I have a form including different inputs and file upload input. I want the users if they want to upload images then upload, but if they don't want to upload. Don't give an error.
if($_POST){
$config['upload_path'] = 'images/tmp';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['min_width'] = 480;
$config['min_height'] = 360;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
//Sending this $error to view and if a user didnt upload image and just filled
//the other inputs it shows error. but i dont want that.
} else { }
} else {
redirect(site_url());
}
You are on right track. Just delete or comment this line
$error = array('error' => $this->upload->display_errors());
You might be send your $error to view file like below:
$this->load->view('upload_form', $error);
So Don't send your value to view file. Just call your view when image successfully uploaded below:
if ( ! $this->upload->do_upload('userfile') )
{
// $error = array('error' => $this->upload->display_errors());
/*Delete or comment this line. Do your other stuff here if image not uploaded.*/
}else{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
/* This is example. You can do anything on successfully image upload.*/
}
You can refer codeigniter manual https://www.codeigniter.com/userguide3/libraries/file_uploading.html
$config['upload_path'] = 'images/tmp';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['min_width'] = 480;
$config['min_height'] = 360;
$this->load->library('upload', $config);
//$rand_str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// $filename=md5(str_shuffle($rand_str.mt_rand()));
// $config['file_name']=$filename;
$this->upload->initialize($config);
if ( $this->upload->do_upload('userfile'))
{
//$data = array('upload_data' => $this->upload->data());
// $data["filename"]=$filename;
// $data["ad_id"]=$lid;
// $data["filename"]=$rand_name;
// $this->Ads_model->insert_image($data);
}
I solved my problem changing the Upload class to give no error. I commented the lines including "no selected files".
I am working on codeigniter project. All is working on my localhost. Now i have shifted all the things on server. I am also using cloudfare.
the problem is when i try to upload image it shows me blank screen. Following is my controller code.
// Add Data
function add(){
$data['pageTitle']=$this->lang->line('siteTitle');
// Breadcrumbs
$this->breadcrumbs->push('Dashboard','admin/dashboard');
$this->breadcrumbs->push('Category List','admin/category/index');
$this->breadcrumbs->push('Add Category','admin/category/add');
// Load View
// Form Submit
$this->form_validation->set_rules('_cat_title','Title','required|is_unique[pu_project_category.c_title]');
$this->form_validation->set_rules('_cat_slug','Slug','required');
$this->form_validation->set_rules('_cat_desc','Description','required');
if($this->form_validation->run()==TRUE){
if($this->upload->do_upload('_cat_image')){
$image=$this->upload->data();
$image=$image['file_name'];
}else{
$image='No Image';
}
$data['resUpload']=$this->upload->display_errors();
$data['res']=$this->Category_Model->add($image);
}
// Load View
$this->load->view('admin/common/header',$data);
$this->load->view('admin/common/left-sidebar',$data);
$this->load->view('admin/category/add',$data);
$this->load->view('admin/common/footer',$data);
}
Following is configuration code for uploading file,
// Upload Configuration
$config['upload_path'] = './project_images/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|zip';
$config['max_size'] = '2000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
Please help me to solve this problem and tell me where i doing wrong.
try this
public function add()
{
$this->form_validation->set_rules('_cat_slug','Slug','required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('welcome_model');//change this with your model
//image upload
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'png|gif|jpg|jpeg';
$config['max_size'] = '7000';
$this->load->library('upload',$config);
if ( ! $this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_view', $error); //loads the view display.php with error
}
$upload_data=$this->upload->data();
$image=$upload_data['file_name'];
$this->load->view('upload_view');
$data= array(
'_cat_slug' => $this->input->post('_cat_slug'),
'image' => $image
); //loads view display.php with data
$this->welcome_model->registre($data);//change this with your model function name
}
else
{
echo validation_errors();
}
}
I have the following code in my view:
if (isset($stockists)) {
$id = $stockists->ID;
echo form_open_multipart($system_settings['admin_folder'].'/stockists/form/'.$id);
}
else {
echo form_open_multipart($system_settings['admin_folder'].'/stockists/form/');
}
<?php echo "<input type='file' name='userfile' size='20' />"; ?>
There's lots of other text input fields in there that are sent to a database on submit. The file up loader is what I'm interested in though.
In my controller function, how can I check if a file exists in the up-loader after submit?
The following retruns false:
$image = ($_FILES['userfile']);
I need to check in a conditional statement if a file exists in the uploader. So for example:
if ($_FILES['userfile']) {
//do
}
But this method does not work.
The super global $_FILES
$_FILES['userfile'] isn't a boolean.
if (strlen($_FILES['userfile']['tmp_name']) > 0) {
// Yes, is uploaded
}
In the array, you've also error:
echo $_FILES['userfile']['error'];
CodeIgniter Approach
CodeIgniter has an upload class that can do the work for you.
CodeIgniter's File Uploading Class permits files to be uploaded. You can set various preferences, restricting the type and size of the files.
Below an example from the CodeIgniter documentation:
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$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('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
See for full examples the documentation: CI File Upload Class