Codeigniter validating file upload and text input in one form - php

I have a form with text inputs and a file input. What is a proper way validate both input types using Codeigniter's validation library? I found some solutions but they don't work properly or seem like an overkill (creating new libraries or modifying CI system files).
In my view I'm using 1 multipart form and displaying both text validation error and upload errors.
Here is what I have so far in my Controller...
function create() //create new post
{
$this->form_validation->set_rules('content', 'Entry', 'trim|required|xss_clean');
$this->form_validation->set_rules('category_id', 'Category', 'trim|required|xss_clean|integer');
//Text input fields
if ($this->form_validation->run() == FALSE)
{
$this->load->view('new_post');
}
else
{
$config['upload_path'] = './uploads/posts/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '800'; //in KB
$this->load->library('upload', $config);
//File Upload
if (! $this->upload->do_upload())
{
$upload_error['upload_error'] = array('error' => $this->upload->display_errors());
$this->load->view('my_view', $upload_error);
return FALSE;
}
//Add to database
$data = array (
'user_id' => $this->tank_auth->get_user_id(),
'category_id' => $this->input->post('category_id'),
'content' => $this->input->post('content')
);
$this->Posts_model->create_post($data);
$this->session->set_flashdata('success', 'Post_added!');
redirect('posts');
}
}
I keep getting You did not select a file to upload. in my view.

What is the name of your file input? do_upload() is expecting it by default to be 'userfile', however if you have something like <input type="file" name="image"... you will need to call $this->upload->do_upload('image')
You also need to make sure the form is set to multipart - http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

You're using CodeIgniter's helpers correctly, this could be running more into a PHP problem then a CodeIgniter problem.
It looks like your file may be too big for your PHP configuration? PHP doesn't seem to be passing the file along to you. Create a php_info() file and see what UPLOAD_MAX_FILESIZE is set to?
Also, make sure you have the extension and mime type pair set in application/config/mimes.php.

default codeigneter upload class is $this->upload->do_upload('field_name = userfile') , so you can set the name of field file you make or you use default codeigneter name field of file , if you want to change the name field for file type in your form , please check how codeigneter made setting for that class, actually is simple class and easy to use.., because that class need parameter name of file

Form field validation with file upload using codeigniter
Controller: Upload.php
Note: create folder uploads at base level
Upload folder store file..
<?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' => ' ' ));
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'trim|required|xss_clean');
//Text input fields
if ($this->form_validation->run() == FALSE)
{
$this->load->view('upload_form');
}
else
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$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);
}
}
}
}
?>
Form:(upload.form.php)
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open_multipart();?>
Title: <input type="text" name="title" size="30" /><br/>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
**upload_success.php**
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open_multipart();?>
Title: <input type="text" name="title" size="30" /><br/>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>

Related

Codeigniter library file upload image file upload form does not work, url becomes duplicate

I have a detailed codeigniter project code is below:
config.php file:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['base_url'] = 'http://localhost/cicrud/codepolitan/Blog';
With the folder path controllers/codepolitan/Blog.php
<?php
class Blog extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('codepolitan/Blog_model');
$this->load->database();
$this->load->helper(array('form','url'));
}
//Tambah
public function add()
{
if ($this->input->post()) {
$data['title'] = $this->input->post('judul');
$data['content'] = $this->input->post('konten');
$data['url'] = $this->input->post('link');
$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('cover'))
{
echo $this->upload->display_errors();
}
else
{
print_r($this->upload->data());
exit;
}
print_r($data);
// var_dump($data);
$this->Blog_model->adddata($data);
}
$this->load->view('/codepolitan/form_add');
}
}
Display files from the form.
With the folder path view/codepolitan/form_add.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php echo form_open_multipart();?>
<div>
<label>Judul</label>
<input type="text" name="judul">
</div>
<div>
<label>URL</label>
<input type="text" name="link">
</div>
<div>
<label>Konten</label>
<textarea name="konten" cols="30" rows="10"></textarea>
</div>
<div>
<label>Upload Cover</label>
<?php echo form_upload('content', null, 'class="form-control"')?>;
</div>
<button type="submit">Simpan Artikel</button>
</form>
</body>
</html>
When running, choose a jpg or png file format and add the code in url to be duplicated like this http://localhost/cicrud/codepolitan/Blog/codpolitan/Blog/add
If, add function code "add()" from controller "Blog.php" at There is an error message "You did not select a file to upload." Whereas previously I had chosen a jpg or png file format.
Please provide an explanation why it is like that? How is the solution from the code above done?

Codeigniter: unable to upload image (You did not select a file to upload)

When I try to upload a image to my uploads folder i get the following error:
Array ( [error] =>
You did not select a file to upload.)
My View:
<form action="<?=base_url('create_public_profile_job') ?>" class="create-profile-form" method="POST">
<input type="file" name="userfile" size="20000" />
<button type="submit" class="create-profile-button">Submit</button>
</form>
My Controller
public function create_public_profile_job()
{
if(isset($_POST['userfile']))
{
$this->User_model->do_upload($_POST['userfile']);
}
}
My Model
public function do_upload($userfile)
{
$this->load->helper('form');
$this->load->helper('url');
$config['upload_path'] = 'assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1000000;
$config['max_width'] = 10240000;
$config['max_height'] = 7680000;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($userfile))
{
$error = array('error' => $this->upload->display_errors());
print_r($userfile);
print_r($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
print_r($data);
}
}
The Model part is from the Codeigniter userguide https://codeigniter.com/userguide3/libraries/file_uploading.html
Don't really know where the issue is, because I pass the image through all functions
change view to
<form action="<?=base_url('create_public_profile_job') ?>" class="create-
profile-form" method="POST" enctype="multipart/form-data">
<input type="file" name="userfile" size="20000" />
<button type="submit" class="create-profile-button">Submit</button>
</form>
You have to add the enctype="multipart/form-data" in the form tag to upload the data through the forms.
So I figured out what my problem was. Or better problems.
My first Problem was that I had to add to my form tag: enctype="multipart/form-data" as others already pointed out in the comments
My second problem was that I had to add in my autoload.php file $autoload['libraries'] = array('database',.., 'upload');
Last but not least I changed $this->load->library('upload', $config); to $this->upload->initialize($config);
Somehow the configuration was not able to initialize correctly, so this fixed my last problem.

Image Not Uploading - Codeigniter

I have a problem uploading image in a Codeigniter app I'm working on. The code was working when on my pc (ubuntu) just fine, as it's given in tutorials. But when I'm trying this in my (centos) server, it's giving an error
"You did not select a file to upload.".
Just for your reference, I'll paste the code here.
Controller- Upload1.php
<?php
class Upload1 extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form1', 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_form1', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success1', $data);
}
}
}
?>
Form - upload_form1.php
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload1/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
Success Page- upload_success1.php
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('upload1', 'Upload Another File!'); ?></p>
</body>
</html>
What could be the problem?
I have "uploads" directory set to 777. So that's not likely to be the reason. I also tried couple of solutions to similar problems, but isn't working. Have missed something obvious?
Versions:
For Server- PHP 5.3.13 (cli)
My PC- PHP 5.3.3 .
Codeigniter is same on local and remote machines- that is 2.1.3
I will be grateful for your suggestions!!
Thank you so much
based on your code, i don't see if there is any form validation to validate the submitted input whether it's valid with your upload config or not. What you should do first : Check the file that you're trying to upload is appropriate with the upload config or not. I think CI's upload class doesn't cover errors from a non valid input form. CMIIW.
normally this is the error when you are not taking the name as "userfile" so check the output by 'view source' in any browser

store the $_POST form data if page fail to submit

I am using codeigniter. I am currently having a very simple form (nothing but input fields) that submits to the controller for processing.
That all doesn't matter, but what I am asking about is that I have an upload file in the form also. so the upload function will check for file size and type and so on and gives error if not complying. when that happens and I choose another file that matches the requirement, I submit but nothing goes to next page but the uploaded file and its details while the other fields are not posted or are blank.
It is as if the post is not cached and when I select new file to upload and its okay, it checks $_POST of those fields and they are empty. How can I check for that so that to make sure all fields contain values?
Thank you and more than happy to help elaborating.
To repopulate the fields you can use the set_value function.
set_value()
Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The second (optional) parameter allows you to set a default value for the form.
First you check if the form validation and upload was successful.
If both are successful we redirect the user to a new page.
If one of these is unsuccessful we add the error message to your data array which we can access in our view and display our form.
Controller
public function signup()
{
// Data array
$data = array();
// Load form validation libary
$this->load->library('form_validation');
// Load upload library and set configuration
$config['upload_path'] = './uploads/';
$this->load->library('upload', $config);
// Set the required fields
$this->form_validation->set_rules('first_name', 'First name', 'required');
if ($this->form_validation->run() == TRUE)
{
// If upload was succesfull
if ($this->upload->do_upload())
{
$upload_data = $this->upload->data();
// Build array to store in database
$save_data = array(
'first_name' => $this->input->post('first_name'),
'image' => $upload_data['file_name']
);
// Send data to your model to process
$this->your_model->save($save_data);
// Redirect to success page
redirect('registration_succes');
}
else
{
// Upload failed, set error
$data['error'] = $this->upload->display_errors();
}
}
else
{
// Form validation failed, set error
$data['error'] = validation_errors();
}
// Display the form by default or on error
$this->load->view('myform', $data);
}
In our view we repopulate the fields with the submitted values using the set_value function.
View ( myform )
<?php echo form_open_multipart('signup');?>
<fieldset>
<?php if( isset($error) && ! empty($error) ): ?>
<div class="error"><?php echo $error; ?></div>
<?php endif; ?>
<p>
<label>First name</label>
<input type="text" name="first_name" value="<?php echo set_value('first_name'); ?>" />
</p>
<p>
<label>File</label>
<input type="file" name="userfile" size="20" />
</p>
<p>
<input type="submit" />
</p>
</fieldset>
</form>

Code Igniter -> attach email

How do you use the email->attach function?
I can't figure what is happen, cos when i put the code for email->attach the mesage came in blank(the mail body) and there is no attach.
If i remove that code line, everything come back to normal..
thank you
my controller (sendmail.php)
<?php
class Sendmail extends Controller {
function __construct() {
parent::Controller();
$this->load->library('email');
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('validation');
}
function index() {
$info = array (
'nome' => $this->input->post('nome'),
'mail' => $this->input->post('email'),
'motivo' => $this->input->post('motivo'),
'mensagem' => $this->input->post('mensagem'),
'anexo' => $this->input->post('upload'),
);
$this->load->library('email');
$this->email->set_newline('\r\n');
$this->email->clear();
$this->email->from($info['mail'], $info['nome']);
$this->email->to('example#mai.com');
/* $this->email->cc(''); # não é preciso */
$this->email->subject($info['motivo']);
$this->email->message($info['mensagem']);
$this->email->attach($info['anexo']);
if ($this->email->send() ) {
echo 'sent';
}
else {
$this->load->view('formulario');
# show_error( $this->email->print_debugger() );
}
}
}
?>
my view (formulario.php)
<?php
echo form_open_multipart('davidslv/index.php/sendmail');
?>
<label for="nome">nome</label>
<input type="text" name="nome" id="nome" required />
<label for="email">email</label>
<input type="text" name="email" id="email" required />
<label for="assunto">assunto</label>
<select name="motivo">
<option value="motivo1">motivo1</option>
<option value="motivo2">motivo2</option>
<option value="motivo3">motivo3</option>
</select>
<p> <label for="mensagem">mensagem</label>
<textarea name="mensagem" id="mensagem" rows="8" cols="30" required></textarea>
</p>
<label for="upload">documento</label>
<input type="file" id="upload" name="upload" size="18"/>
<input type="submit" id="enviar" name="enviar" value="Enviar!" />
</form>
You can not directly attach a file from the upload field of your form to an email. You can only attach files to your email from your server, so you need to upload the file from the form with CIs upload library: $this->upload->do_upload() to your server into some directory. the upload library needs to be configured, which file types are allowed etc. if the upload was successful, the do_upload function returns extensive data about where the file is stored. you can use the 'full_path' index from the array to attach this file to the email. then send the mail. after that you may delete the file from your server. Here are some code fragments that might help.
$this->load->library('upload');
if($_FILES['upload']['size'] > 0) { // upload is the name of the file field in the form
$aConfig['upload_path'] = '/someUploadDir/';
$aConfig['allowed_types'] = 'doc|docx|pdf|jpg|png';
$aConfig['max_size'] = '3000';
$aConfig['max_width'] = '1280';
$aConfig['max_height'] = '1024';
$this->upload->initialize($aConfig);
if($this->upload->do_upload('upload'))
{
$ret = $this->upload->data();
} else {
...
}
$pathToUploadedFile = $ret['full_path'];
$this->email->attach($pathToUploadedFile);
...
$this->email->send();
...
}
...
Hope this helped...
$this->email->attach()
Enables you to send an attachment. Put
the file path/name in the first
parameter. Note: Use a file path, not
a URL. For multiple attachments use
the function multiple times. For
example:
$this->email->attach('/path/to/photo1.jpg');
$this->email->attach('/path/to/photo2.jpg');
$this->email->attach('/path/to/photo3.jpg');
$this->email->send();
Codeigniter Email Class
This is Absolutely right code Please Try
$config['upload_path'] = './uploads';
$config['allowed_types'] = 'gif|jpg|jpeg|png|txt|php|pdf';
$config['max_size'] = '9000';
$config['encrypt_name'] = true;
$image_data = $this->upload->data();
$fname=$image_data[file_name];
$fpath=$image_data[file_path].$fname;
$this->email->attach($fpath);
step 1:You can not directly attach a file from the upload field of your form to an email. You can only attach files to your email from your server, so you need to upload the file from the form with CIs upload library:
$this->upload->do_upload() to your server into some directory.
step 2:
$file=upload file;
$file_path='uploaded directory on your server(eg:uploads/career)'.$file;
step 3:just include
$this->email->attach($file_path);
$this->email->send();
This is a late update, but it might be useful.
It was said twice
"You can not directly attach a file from the upload field of your form
to an email"
. However, this works fine in Codeigniter 3.0
foreach ($_FILES as $key => $file)
{
if ($file['error'] == 0)
{
$this->email->attach($file['tmp_name'], '', $file['name']);
}
}
(Though, the email is not sent and no errors are shown, if there are two files with the same name)

Categories