Upload two files in codeIgniter showing error - php

my View form multipart
<h3>Upload Submission File(doc,docx,pdf,cda,rtf,txt)</h3>
<?php echo form_error('fileToUpload'); ?>
<p>
<input type="file" name="fileToUpload" id="fileToUpload" title="Upload Submission File"
accept="application/pdf, .doc, .docx, .txt, application/msword, .rtf, .cda"/>
</p>
<h3>Upload Additional File (gif,jpeg,png,tiff,pdf)</h3>
<?php echo form_error('additionalUpload'); ?>
<p>
<input type="file" name="additionalUpload" id="additionalUpload" title="Upload Additional File"
accept="image/gif, image/jpeg, image/png, image/x-tiff, application/pdf" />
</p>
My Contoller
function submit_article() {
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<p style="color:red">', '<br/></p>');
$my_rules = array(
array(
'field' => 'fileToUpload',
'label' => 'Submission File',
'rules' => 'callback_is_proper_file'
),
array(
'field' => 'additionalUpload',
'label' => 'Additional File',
'rules' => 'callback_is_image'
)
);
$this->form_validation->set_rules($my_rules);
if ($this->form_validation->run() == FALSE) {
//ERROR
$data['title'] = ucfirst('submit Article');
$this->load->view('templates/header', $data);
$this->load->view('submit_article', $data);
$this->load->view('templates/footer', $data);
} else {
//SUCCESS
$data['title'] = ucfirst('article Submitted');
$this->load->view('templates/header', $data);
$this->load->view('forms_view/submit_article_success', $data);
$this->load->view('templates/footer', $data);
}
}
function is_image() {
if ($_FILES['additionalUpload']['tmp_name'] != '') {
$config1['upload_path'] = './public/uploads/';
$config1['allowed_types'] = 'gif|jpg|jpeg|png|pdf|tiff';
$config1['max_size'] = '2048';
$config1['max_width'] = '0';
$config1['max_height'] = '0';
$config1['remove_spaces'] = true;
$config1['overwrite'] = true;
$this->load->library('upload', $config1);
if (!$this->upload->do_upload('additionalUpload')) {
$this->form_validation->set_message('is_image', $this->upload->display_errors('<p style="color:red">', '<br/></p>'));
return FALSE;
} else {
$this->upload->data();
return TRUE;
}
}
}
function is_proper_file() {
if ($_FILES['fileToUpload']['tmp_name'] != '') {
$config['upload_path'] = './public/uploads/';
$config['allowed_types'] = 'doc|docx|pdf|cda|rtf|txt';
$config['max_size'] = '1024*10';
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['remove_spaces'] = true;
$config['overwrite'] = true;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('fileToUpload')) {
$this->form_validation->set_message('is_proper_file', $this->upload->display_errors('<p style="color:red">', '<br/></p>'));
return FALSE;
} else {
$this->upload->data();
return TRUE;
}
} else {
$this->form_validation->set_message('is_proper_file', '<p style="color:red">Please select a file to upload.<br/></p>');
return FALSE;
}
}
The additionalUpload field is not required field and filetoupload is a required field.
when i submit the form by filling all the details except additionalUpload my code works well for me, but when i submit the form with additionalUpload along with aal other details it shows me error "The filetype you are attempting to upload is not allowed." for additionalUpload field..
in other words when i submit the form with one file that is filetoupload which is required its works for me.. and when i submit the form with both the files that is filetoUpload and additionalUpload then its shows me error for the additional upload fields "The filetype you are attempting to upload is not allowed.",, and when i simply submit the form with only addtionalupload file its do the upload in my upload folder but when i submit with all the fields it shows me error "The filetype you are attempting to upload is not allowed." for the additional Upload filed..
THANKS IN ADVANCE PLEASE HELP ANYONE

$this->load->library('upload');
$this->upload->initialize($config1);
I need to call it like above where as I have called it in this way:
$this->load->library('upload',$config);

Related

How can I store validation errors related to image upload as flash massages in this Codeigniter 3 application?

I am working on a basic blog application with Codeigniter 3.1.8 and Bootstrap 4.
The posts, of course, have main images. There is a default image if no image is uploaded by the user.
There are restrictions on image files a user can upload:
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '2048';
I have managed to display the upload error messages that correspond to the configuration above (for your curiosity and/or use, the code is here).
For the update() method however, since there are redirects involved, all form validation messages are stored as "flash messages".
public function update() {
// Form data validation rules
$this->form_validation->set_rules('title', 'Title', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('desc', 'Short description', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('body', 'Body', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
$id = $this->input->post('id');
// Update slug (from title)
if ($this->form_validation->run()) {
$slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug, $id);
if ($slugcount > 0) {
$slug = $slug."-".$slugcount;
}
} else {
$slug = $this->input->post('slug');
}
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if (isset($_FILES['userfile']['name']) && $_FILES['userfile']['name'] != null) {
// Use name field in do_upload method
if (!$this->upload->do_upload('userfile')) {
$errors = array('error' => $this->upload->display_errors());
// Dysplay upload validation errors
// only if a file is uploaded and there are errors
if (empty($_FILES['userfile']['name'])) {
$errors = [];
}
if (!empty($errors)) {
$data['upload_errors'] = $errors;
}
} else {
$data = $this->upload->data();
$post_image = $data[ 'raw_name'].$data[ 'file_ext'];
}
}
else {
$post_image = $this->input->post('postimage');
}
if ($this->form_validation->run() && empty($errors)) {
$this->Posts_model->update_post($id, $post_image, $slug);
$this->session->set_flashdata('post_updated', 'Your post has been updated');
redirect('/' . $slug);
} else {
$this->form_validation->run();
$this->session->set_flashdata('errors', validation_errors());
// this line was added later
// but the bug persists
$this->session->set_flashdata('upload_errors', $errors);
redirect('/dashboard/posts/edit/' . $slug);
}
}
In the edit-post.php view I have:
<input type="hidden" name="postimage" id="postimage" value="<?php echo $post->post_image; ?>">
<label for="postimage">Upload an image</label>
<div class="form-group">
<input type="file" name="userfile" id="postimage" size="20">
<?php if ($this->session->flashdata('upload_errors')) { ?>
<div class="error-messages">
<?php if(isset($upload_errors)){
foreach ($upload_errors as $upload_error) {
echo $upload_error;
}
}?>
</div>
<?php } ?>
</div>
I have not been able to add the image upload errors messages as "flash messages".
How can I do that?
In edit-post.php you have to change:
<?php if ($this->session->flashdata('upload_errors')) { ?>
With:
<?php if ($upload_errors = $this->session->flashdata('upload_errors')) { ?>
Try this:
$this->session->set_flashdata('errors', validation_errors());
$this->session->set_flashdata('upload_errors', $errors);
Or you can create an $errorArray from validation_errors() and $errors.
I do the exact same thing (upload errors go into a flashdata element). Here's how it works for me:
(I'll skip the upload config... but for this example, it's stored in an array conveniently named $config)
In my controller:
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
$this->session->set_flashdata('message', "An error ocurred: ".$this->upload->display_errors());
$this->session->set_flashdata('alert_class', "alert-danger");
}
else
{
$this->session->set_flashdata('message', "Upload successful");
$this->session->set_flashdata('alert_class', "alert-success");
}
In my view (all my views carry this code)
<?php
if (null !== $this->session->flashdata('message'))
{ ?>
<div class="alert <?php echo $this->session->flashdata('alert_class'); ?> text-center mb-2"><i class="fas fa-exclamation-triangle fa-fw"></i> <?php echo $this->session->flashdata('message'); ?></div>
<?php
}
?>
In this way, if I don't set a flashdata element called message the view won't even display the DIV where alert is displayed. If, on the other hand, I do set the message element, a col-12 alert is displayed with the message I defined and styled with the alert class I want (success, warning, danger, info, etc)
This will only work for upload validation errors. In your multipart form you may also have regular validation errors which you should check for separately. You can do the same with a flash element:
$this->session->set_flashdata('message', validation_errors());
I use the same element name (message) because I'd stop upon the first error, So there would be no upload error and form validation error in the same display.
This should work.
public function update()
{
// Form data validation rules
$this->form_validation->set_rules('title', 'Title', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('desc', 'Short description', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_rules('body', 'Body', 'required', array('required' => 'The %s field can not be empty'));
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
$id = $this->input->post('id');
$form_is_valid = $this->form_validation->run()
$errors = [];
// Update slug (from title)
if ($form_is_valid) {
$slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug, $id);
if ($slugcount > 0) {
$slug = $slug."-".$slugcount;
}
} else {
$slug = $this->input->post('slug');
$errors[] = validation_errors();
}
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if (isset($_FILES['userfile']['name']) && $_FILES['userfile']['name'] != null) {
// Use name field in do_upload method
if (!$this->upload->do_upload('userfile')) {
$upload_errors = array('error' => $this->upload->display_errors());
// Dysplay upload validation errors
// only if a file is uploaded and there are errors
if (empty($_FILES['userfile']['name'])) {
$upload_errors = [];
}
if (!empty($upload_errors)) {
$data['upload_errors'] = $upload_errors;
$errors[] = $upload_errors;
}
} else {
$data = $this->upload->data();
$post_image = $data[ 'raw_name'].$data[ 'file_ext'];
}
}
else {
$post_image = $this->input->post('postimage');
}
if (empty($errors)) {
$this->Posts_model->update_post($id, $post_image, $slug);
$this->session->set_flashdata('post_updated', 'Your post has been updated');
redirect('/' . $slug);
} else {
$this->session->set_flashdata('errors', $errors);
redirect('/dashboard/posts/edit/' . $slug);
}
}
$this->form_vlaidation->run() is called only once.
Errors are saved both (form validation & upload) in the same array.
Post is updated only if $errors is empty.
You should think how you can improve the code further.
Try this one .Add this in constructor
$this->session->keep_flashdata('errors');
and remove session data after use it in view
$this->session->unset_userdata('errors');

Image upload still submitting with callback validation in CI

I am trying to do a image upload validation on codeigniter 3. I have tried many tut's but still face this issue. I would like if the user was to leave the upload a photo area blank ( eventually if they upload a unsupported mime and size) for it to throw a error before it allows or tries to submit the data.
Right now it throws a error but showing the database query along with "Image in sql cannot be blank". I would like it to show like a regular form validation would without it showing the sql query and error.
It still seems to submit the form without it throwing the error first, because it says $post_image undefined.
I have already tried entering a callback with isset function to try to only allow the form to submit data if a image was uploaded, if not I was trying to display the errors by passing the error variable. None of this seems to work correctly as I explained above.
Controller:
public function create(){
//Check in login session
if(!$this->session->userdata('logged_in')){
$this->session->set_flashdata('log_post','Please login or create a free account to post a ad.');
redirect('users/register');
}
$data['title'] = 'Create a Post';
$data['categories'] = $this->post_model->get_categories();
$data['states'] = $this->post_model->get_city();
$this->form_validation->set_error_delimiters('<div class="error"> <h7> Error: </h7>', '</div>');
$this->form_validation->set_rules('title','Title',array('required', 'min_length[3]'));
//$this->form_validation->set_rules('file','Image Upload','required');
$this->form_validation->set_rules('Description','About You',array('required', 'min_length[5]'));
$this->form_validation->set_rules('Number','Phone Number',array('required', 'min_length[7]'));
$this->form_validation->set_rules('Area','Location/Area',array('required', 'min_length[2]'));
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
} else {
// $this->load->helper('file');
//$this->form_validation->set_rules('file','','callback_file_check');
if($this->form_validation->run()==TRUE){
$config['upload_path'] = 'assets/images/posts';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['encrypt_name'] = TRUE; //TURN ON
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$this->upload->initialize($config);
if(!$this->upload->do_upload('file')){
$errors = array('error'=>$this->upload->display_errors());
$this->load->view('templates/header');
$this->load->view('posts/create', $errors);
$this->load->view('templates/footer');
}else {
$data = $this->upload->data();
$post_image = $data['file_name'];
}
}
$this->post_model->create_post($post_image);
$this->session->set_flashdata('post_created','Your Post has been submitted');
redirect('posts');
}
}
}// end of class
Model:
public function create_post($post_image){
$slug = md5(uniqid().mt_rand());
//url_title($this->input->post('title'), 'dash', TRUE). // this is the orginal way for slug SEO friendly
$site = $this->input->post('site');
//adds HTTP too website links
if (!preg_match("~^(?:f|ht)tps?://~i", $site)) {
$site = "http://" . $site;
}
$data = array(
'title'=>$this->input->post('title'),
'body'=> $this->input->post('Description'),
'post_image' => $post_image
);
return $this->db->insert('posts',$data);
}
View:
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="textarea">Photo</label>
<div class="col-lg-8">
<div class="mb10">
<?php echo form_error('file') ?>
<input name="file" type="file" class="form-control-file" id="exampleInputFile" aria-describedby="fileHelp">
</div>
<?php if (isset($error)) { echo $error; } ?>
</div>

i am not understanding how to upload image in codeigniter

Below i have code of my form data with image but it was not working. i tried to insert data without image the data inserted into db. but when i tried to insert with image the form error raised and redirecting to targeted page. Below i have mvc code please while giving edited answer also explain me why my code didn't worked and how your code worked instead of copy paste i want to learn concept behind it.please.
//my form view code
<?php echo form_open_multipart('admin/uauthor');?>
<h5><label>Username Here:</label></h5>
<?php echo form_input(['name'=>'aname','class'=>'form-control','placeholder'=>'Enter your name here']);?>
<h5><label>Mail Here:</label></h5>
<?php echo form_input(['name'=>'amail','class'=>'form-control','placeholder'=>'Enter your Mail here']);?>
<h5><label>Password Here:</label></h5>
<?php echo form_input(['name'=>'apwd','type'=>'password','class'=>'form_control','placeholder'=>'Enter your password here']);?>
<h5><label>Phone Here:</label></h5>
<?php echo form_input(['name'=>'aphone','class'=>'form-control','placeholder'=>'Enter your phone here']);?>
<h5><label>Profile Pic Here:</label></h5>
<?php echo form_upload(['name'=>'apic','class'=>'form-control']);?>
<select name="alevel" class="form-control">
<option value="admin">Admin</option>
<option value="author">Author</option>
</select><br>
<button type="submit" class="btn btn-success">Add Author</button>
<?php form_close();?>
----------
//my Controller code
public function uauthor()
{
$this->form_validation->set_rules('aname','Author Name','required');
$this->form_validation->set_rules('amail','Author Mail','required|is_unique[admin.amail]',array(
'required' => 'You have not provided %s.',
'is_unique' => 'This %s already exists.'
));
$this->form_validation->set_rules('aphone','Author Phone','required|is_unique[admin.aphone]',array(
'required' => 'You have not provided %s.',
'is_unique' => 'This %s already exists.'
));
$this->form_validation->set_rules('apwd','Author Password','required');
if ($this->form_validation->run()){
$config = [
'upload_path' => './uploads/authors',
'allowed_types' => 'jpg|gif|png|jpeg',
];
$this->load->library('upload', $config);
$data= $this->input->post();
if(! $this->upload->do_upload()){
$this->session->set_flashdata('pmsg',"Author Upload Failed Please Try Again");
return redirect('admin/aauthor');
}else{
$info = $this->upload->data();
$image_path = $info['raw_name'] . $info['file_ext'];
$data['apic'] = $image_path;
}
$this->adata->uauthorQ($data);
$this->session->set_flashdata('amsg', 'Author Added Successfully');
return redirect('admin/authors');
}else{
$this->session->set_flashdata('pmsg', validation_errors());
return redirect('admin/aauthor');
}
}
----------
//My Model code
public function uauthorQ($data)
{
return $this->db->insert('admin',$data);
}
Change this :
$this->upload->do_upload()
to this :
$this->upload->do_upload('apic')
so it will using 'apic' instead of the default 'userfile' input field name
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|pdf';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('welcome_message', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
html
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
do some changes on your controller.
inserting data must be as array of fields. so i have changed some $data as array.
$data['aname'] = $this->input->post('aname');
$data['amail'] = $this->input->post('amail');
$data['apwd'] = md5($this->input->post('apwd'));
$data['aphone'] = $this->input->post('aphone');
//my Controller code
public function uauthor()
{
$this->form_validation->set_rules('aname','Author Name','required');
$this->form_validation->set_rules('amail','Author Mail','required|is_unique[admin.amail]',array(
'required' => 'You have not provided %s.',
'is_unique' => 'This %s already exists.'
));
$this->form_validation->set_rules('aphone','Author Phone','required|is_unique[admin.aphone]',array(
'required' => 'You have not provided %s.',
'is_unique' => 'This %s already exists.'
));
$this->form_validation->set_rules('apwd','Author Password','required');
if ($this->form_validation->run()){
$config = [
'upload_path' => './uploads/authors',
'allowed_types' => 'jpg|gif|png|jpeg',
];
$this->load->library('upload', $config);
if(! $this->upload->do_upload('apic')){
$this->session->set_flashdata('pmsg',"Author Upload Failed Please Try Again");
return redirect('admin/aauthor');
}else{
$info = $this->upload->data();
$image_path = $info['raw_name'] . $info['file_ext'];
$data['apic'] = $image_path;
$data['aname'] = $this->input->post('aname');
$data['amail'] = $this->input->post('amail');
$data['apwd'] = md5($this->input->post('apwd'));
$data['aphone'] = $this->input->post('aphone');
}
$this->adata->uauthorQ($data);
$this->session->set_flashdata('amsg', 'Author Added Successfully');
return redirect('admin/authors');
}else{
$this->session->set_flashdata('pmsg', validation_errors());
return redirect('admin/aauthor');
}
}

How to make codeigniter sticky form when error comes from upload file field

I have a form that allows user to upload multiple files. Additionaly user have to fill other input text fields like address, email etc.
I don't know how to make form sticky if error comes from file uploading and how to access error messages set by form_validation library. Because if for example one of the filetype is not allowed I use redirect to step out of the loop responsible for uploading every file.
To keep upload error message I use $this->session->set_flashdata('errors', $errors) but then I'm not able to use error messages from form_validation library ( echo form_error('field_name) ) and display user input in form fields ( echo set_value('field_name'))
Here is controller method responsible for file upload and data insert:
function do_upload()
{
// load form validation library
$this->load->library('form_validation');
// set validation rules
$this->form_validation->set_rules('email','Email','trim|required|valid_email|matches[confirm_email]');
$this->form_validation->set_rules('confirm_email','Email','trim|required|valid_email');
$this->form_validation->set_rules('delivery_name','Nazwa','trim|required');
$this->form_validation->set_rules('delivery_street','Ulica','trim|required');
$this->form_validation->set_rules('delivery_city','Miasto','trim|required');
$this->form_validation->set_rules('delivery_postcode','Kod pocztowy','trim|required');
$this->form_validation->set_rules('delivery_country','Kraj','trim|required');
$this->form_validation->set_rules('captcha','Captcha','callback_check_captcha');
if ( $this->form_validation->run() )
{
// if validation passes I insert form data into database and I start to upload
// all the files using foreach loop
$config['upload_path'] = './uploads/upload_directory';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$upload_data = array();
$task_address_id_array = $this->MTasks->insertNewTask($task_directory);
$task_id = $task_address_id_array['task_id'];
$address_id = $task_address_id_array['address_id'];
// iterate over files to be uploaded
foreach ($_FILES as $key => $value)
{
if (!empty($value['name']))
{
$this->upload->initialize($config);
$result = $this->upload->do_upload($key);
if (!$result)
{
// if upload error occurs I need to redirect to break the loop
$errors = $this->upload->display_errors();
$this->session->set_flashdata('errors', $errors);
redirect();
}
else
{
$current_upload_data = $this->upload->data();
// insert upload data to database
$this->MTasks->insertFileInfo($current_upload_data,$task_id);
}
}
}
redirect('upload/success_message');
}
else
{
$this->load->view('include/header');
$this->load->view('upload_form',$this->data);
$this->load->view('include/footer');
}
}
The main problem is you can not put as validation rule file uploads, because the library executes one by one.
A simple solution is to validate your fields and then validate the file upload. Example:
<?php
function save()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$this->form_validation->set_error_delimiters('', '<br />');
echo validation_errors();
exit();
}
else
{
if($_FILES['imagen']['error'] != 4)
{
$image $this->_manage_image($this->input->post('name'));
}
else
{
exit('No empty field!');
}
# save in your bd o success message...
}
}
function _manage_image($name)
{
# config
$config['upload_path'] = './images/products/';
$config['allowed_types'] = 'gif|jpg|png';
// ...
$config['file_name'] = $name;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image'))
{
# errors...
echo $this->upload->display_errors();
exit();
}
else
{
# upload
return $img_data['file_name'];
}
}

struggling with a ajax upload and PHP

I need some help please,
I am upload loading an image with the help of a jquery uploader so that the user can get a preview of the image and I can jCrop on it, my problem is that I then need to save the file name, but I cannot get to the variable I create in the upload function,
The process that users goes throug is as follows,
User fills in their details
User selects and image to up load and hits the upload button
Upload function is run, and the image is returned to the view
User selects an area of the image that will be cropped and saved
User carries on filling form out
Save the items including the filename
Below is my PHP code, which I believe is where the variable goes missing and cannot be used in the add function,
Add() - The function that the form submits too
public function add()
{
$this->form_validation->set_rules('title','title', 'required|trim|min_length[2]');
$this->form_validation->set_rules('firstname', 'firstname', 'required|trim|alpha');
$this->form_validation->set_rules('surname', 'surname', 'required|trim|alpha');
$this->form_validation->set_rules('email', 'email address', 'required|trim|valid_email');
$this->form_validation->set_rules('postcode', 'postcode', 'required|trim|min_length[6]|max_length[9]');
$this->form_validation->set_rules('company_name', 'company_name', 'required|trim');
$this->form_validation->set_rules('company_summary', 'company_summary', 'required|trim|max_length[3000]');
$this->form_validation->set_rules('alternative_ads', 'alternative ads', 'required|trim|prep_url');
$this->form_validation->set_rules('facebook_url', 'Facebook URL', 'required|trim|prep_url');
$this->form_validation->set_rules('twitter_url', 'Twitter URL', 'required|trim|prep_url');
if($this->form_validation->run() == FALSE)
{
$this->template->build('admin/users/add');
}
else
{
//group the post data together soe that we can save the data easily.
$user = array(
'firstname' => $this->input->post('firstname'),
'surname' => $this->input->post('surname'),
'email' => $this->input->post('email'),
'postcode' => $this->input->post('postcode'),
'date_registered' => date("d-m-y h:i:s", time())
);
if(!$this->users_model->insert($this->input->xss_clean($user)))
{
$data['error'] = "We could not save you details, please try again";
$this->template->build('/users/admin/add', $data);
}
$employer = array(
'company_name' => $this->input->post('company_name'),
'company_summary' => $this->input->post('company_summary'),
'logo' => $this->file['file_name'],
'alternative_ads' => $this->input->post('alternative_ads'),
'facebook_url' => $this->input->post('facebook_url'),
'twitter_url' => $this->input->post('twitter_url'),
'user_id' => $this->db->insert_id()
);
if(!$this->employer_model->insert($this->input->xss_clean($employer)))
{
$data['error'] = "We could not save you details, please try again";
$this->template->build('/users/admin/add', $data);
}
else
{
die(print_r($this->file));
$this->load->library('image_lib');
$config['image_library'] = 'gd2';
$config['source_image'] = '/media/uploads/users/' . $this->file['file_name'];
$config['thumb_marker'] = TRUE;
$config['x_axis'] = $this->input->post('x');
$config['y_axis'] = $this->input->post('y');
$this->image_lib->initialize($config);
if ( ! $this->image_lib->crop())
{
$data['error'] = "We could not crop you image, please try again. If the problem persists please contact us";
$this->template->build('/admin/users/add', $data);
}
$this->session->set_flashdata('success', 'You have successfully added an employer');
redirect('/admin/users/manage');
}
}
}
And the upload function that the jquery uploader calls
private function upload()
{
$config['upload_path'] = "./media/uploads/users";
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['encrypt_name'] = TRUE;
$this->load->library('upload');
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
die(print_r($error));
}
else
{
$this->file = $this->upload->data();
$msg = $this->file;
echo json_encode($msg);
}
}
To recap I am setting $this->file in upload() and trying to use it in the add() function.
You'll have to return something from the upload() function in order to use it in the add() function. Depending on your app and it's set up this may or may not break your ajax.
An alternative would be to set session, for the bits you need.
$this->file will only be in the scope of the upload. So like Ross mentioned have the upload echo the image in the json and then do something with it in the form. Like add it to a hidden input that is then sent with the post data.

Categories