The form I'm working with contains info for five people. Optionally, the user can upload a photo for each of the five people. I'm attempting to insert a default image into the resulting array $files where an image is not uploaded. Help would be greatly appreciated.
function multiple_upload($upload_dir = APPPATH, $config = array())
{
$CI =& get_instance();
$files = array();
if(empty($config))
{
$config['upload_path'] = realpath($upload_dir . '/uploads');
$config['allowed_types'] = 'gif|jpg|jpeg|jpe|png';
$config['max_size'] = '2048';
}
$CI->load->library('upload', $config);
$errors = FALSE;
$this->load->library('image_lib'); // moved outside loop so it'll work
foreach($_FILES as $key => $value)
{
if( ! empty($value['name']))
{
if( ! $CI->upload->do_upload($key))
{
$data['upload_message'] = $CI->upload->display_errors(ERR_OPEN, ERR_CLOSE); // ERR_OPEN and ERR_CLOSE are error delimiters defined in a config file
$CI->load->vars($data);
$errors = TRUE;
}
else
{
// resize the saved image
$path = $CI->upload->data('full_path');
//echo $path['full_path'] . "<Br/>";
$config = array(
'source_image' => $path['full_path'],
'new_image' => $upload_dir . 'uploads/thumbs',
'maintain_ration' => true,
'width' => 150,
'height' => 150
);
$this->image_lib->initialize($config);
$this->image_lib->resize();
// Build a file array from all uploaded files
$files[] = $CI->upload->data();
}
}
}
// There was errors, we have to delete the uploaded files
if($errors)
{
foreach($files as $key => $file)
{
#unlink($file['full_path']);
}
}
elseif(empty($files) AND empty($data['upload_message']))
{
$CI->lang->load('upload');
$data['upload_message'] = ERR_OPEN.$CI->lang->line('upload_no_file_selected').ERR_CLOSE;
$CI->load->vars($data);
}
else
{
return $files;
}
}
It might be easier to do your check after you validate the uploaded files.
For example: Initialize an array with five empty elements, one for each picture, then for each file that's uploaded, set its filename to the appropriate array element. When you're done, just run through and for any empty elements, just tack in the file (or file path) to your default image.
This way, you keep your file uploading and validation as vanilla as possible, and deal with the business logic of your page separately.
Related
I am developing a ad site that anyone able to upload 3 images.
So I am coding to upload that 3 images by adding timestamp in front of their file name to make them unique. I use codeigniter framework and attaching the code below.
when I submitting form data, localhost server shows that images have been saved correctly with some code infornt of image filename. But problem is there are no images saved in relevant image folder in that name and I cannot retrieve that images in next preview advertisement page.
I don't know much about php or codeignitor. Your help is highly appreciated.
$config['upload_path'] = './assets/images/adsimages';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5120;
$this->load->library('upload',$config);
$this->upload->initialize($config);
if (!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'no_image.jpg';
}
else {
$data = array('upload_data' => $this->upload->data());
$post_image1 = time().$_FILES['userfile1']['name'];
$post_image2 = time().$_FILES['userfile2']['name'];
$post_image3 = time().$_FILES['userfile3']['name'];
}
$result = $this->post_model->adregister($post_image1,$post_image2,$post_image3);
You can append time to 'filename' in config of upload library
$config['file_name'] = time().$_FILES['userfile1']['name'];
Or if you want unique name for all files the simply add
$config['encrypt_name'] = TRUE;
then
$this->load->library('upload', $config);
Try this one:-
$path = pathinfo($_FILES["userfile1"]["name"]);
$image_path = $path['filename'].'_'.time().'.'.$path['extension'];
I've written a possible solution for your code. You haven't shared your full code so you'll have to fill in the gaps yourself and maybe make some changes here and there; Comments are mentioned wherever necessary. See if it helps you.
public function your_function_name(){
// your-code
// your-code
// check if file is uploaded in field1
if(!empty($_FILES['userfile1']['name'])){
// call function to upload file
$userfile1 = $this->upload_file('userfile1');
}
// check if file is uploaded in field2
if(!empty($_FILES['userfile2']['name'])){
$userfile2 = $this->upload_file('userfile2');
}
// check if file is uploaded in field3
if(!empty($_FILES['userfile3']['name'])){
$userfile3 = $this->upload_file('userfile3');
}
$result = $this->post_model->adregister($userfile1, $userfile2, $userfile3);
}
// function to upload file
function upload_file($filename){
$config['file_name'] = time().$_FILES[$filename]['name']; // append time to filename
$config['upload_path'] = './assets/images/adsimages';
$config['allowed_types'] = 'gif|jpg|jpeg|png|GIF|JPG|PNG|JPEG';
$config['max_size'] = 5120;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$uploaded = $this->upload->do_upload($filename);
if ( ! $uploaded ){
$error = array('error' => $this->upload->display_errors());
$file = 'no_image.jpg'; // default file
}else{
$upload_data = $this->upload->data();
$file = $upload_data['file_name']; // uploaded file name
}
return $file; // return filename
}
i know it might be wrong to ask but when i am inserting multiple image using ajax and inserting it to the database files are getting inserted but the url is wrong let me show you
""http://localhost/P_Display/uploads/bike-926023_192048.jpg""
this is the url that i got from the console the file is saving but it might be because of the for loop that i am using to upload multiple files
let me show you the controller code
public function post_data_multimage()
{
$data = array();
$data['title'] = 'Multiple file upload';
if($this->input->post())
{
// retrieve the number of images uploaded;
$number_of_files = sizeof($_FILES['multimage']['tmp_name']);
$files = $_FILES['multimage'];
$errors = array();
for($i=0;$i<$number_of_files;$i++)
{
if($_FILES['multimage']['error'][$i] != 0) $errors[$i][] = 'Couldnt upload file '.$_FILES['multimage']['name'][$i];
}
if(sizeof($errors)==0)
{
// now, taking into account that there can be more than one file, for each file we will have to do the upload
// we first load the upload library
$this->load->library('upload');
// next we pass the upload path for the images
$config['upload_path'] = FCPATH . './uploads/';
// also, we make sure we allow only certain type of images
$config['allowed_types'] = 'gif|jpg|png|jpeg';
for ($i = 0; $i < $number_of_files; $i++) {
$_FILES['multimage']['name'] = $files['name'][$i];
$_FILES['multimage']['type'] = $files['type'][$i];
$_FILES['multimage']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['multimage']['error'] = $files['error'][$i];
$_FILES['multimage']['size'] = $files['size'][$i];
//now we initialize the upload library
$this->upload->initialize($config);
$image= $_FILES['multimage']['name'];
$post = $this->input->post();
unset($post['submit']);
$this->load->model('Pmodel');
$multi_data= $this->Pmodel->post_data_multimage($post,$image);
// we retrieve the number of files that were uploaded
if ($this->upload->do_upload('multimage'))
{
$data['uploads'][$i] = $this->upload->data();
$upload_data=$data['uploads'][$i];
$image_path= base_url("uploads/".$upload_data['raw_name'].$upload_data['file_ext']);
echo json_encode($image_path);
}
else
{
$data['upload_errors'][$i] = $this->upload->display_errors();
}
}
}
else
{
print_r($errors);
}
echo '<pre>';
print_r($data);
echo '</pre>';
}
else
{
echo "string";
}
}
how can i remove those slashes from my url?
i think this might work all we need is to add a html element to the controller that will echo the image from the controller and we don't need to pass the value to the view thus ending the conflict of wrong url
here is my code
$data = array();
$data['title'] = 'Multiple file upload';
if($this->input->post())
{
// retrieve the number of images uploaded;
$number_of_files = sizeof($_FILES['multimage']['tmp_name']);
$files = $_FILES['multimage'];
$errors = array();
for($i=0;$i<$number_of_files;$i++)
{
if($_FILES['multimage']['error'][$i] != 0) $errors[$i][] = 'Couldnt upload file '.$_FILES['multimage']['name'][$i];
}
if(sizeof($errors)==0)
{
// now, taking into account that there can be more than one file, for each file we will have to do the upload
// we first load the upload library
$this->load->library('upload');
// next we pass the upload path for the images
$config['upload_path'] = FCPATH . './uploads/';
// also, we make sure we allow only certain type of images
$config['allowed_types'] = 'gif|jpg|png|jpeg';
for ($i = 0; $i < $number_of_files; $i++) {
$_FILES['multimage']['name'] = $files['name'][$i];
$_FILES['multimage']['type'] = $files['type'][$i];
$_FILES['multimage']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['multimage']['error'] = $files['error'][$i];
$_FILES['multimage']['size'] = $files['size'][$i];
//now we initialize the upload library
$this->upload->initialize($config);
$image= $_FILES['multimage']['name'];
$post = $this->input->post();
unset($post['submit']);
$this->load->model('Pmodel');
$multi_data= $this->Pmodel->post_data_multimage($post,$image);
// we retrieve the number of files that were uploaded
if ($this->upload->do_upload('multimage'))
{
$data['uploads'][$i] = $this->upload->data();
$upload_data=$data['uploads'][$i];
$user_image = array( 'src' => base_url("uploads/" .$image),
'width' => '100px',
'height'=> '100px',
);
echo "<a href='#'>" . img($user_image)."</a>";
}
else
{
$data['upload_errors'][$i] = $this->upload->display_errors();
}
}
}
else
{
print_r($errors);
}
}
else
{
echo "string";
}
}
see i just echo the image with its path thus removing the problem.
save the address same
'Assets/image_upload/'.$image= $_FILES['multimage']['name']
to field image table of database if exist.
When you show it.
echo(base_url($item->image))//image field showed in database.
I have this controller which inserts the images to upload folder without resizing them.
public Function Upload() {
$this->load->library('upload');
$config['upload_path'] = FCPATH . 'uploads/property-images';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = 'property_image_1';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
for ($i = 0; $i < $number_of_files; $i++) {
$_FILES['uploadedimage']['name'] = $files['name'][$i];
$_FILES['uploadedimage']['type'] = $files['type'][$i];
$_FILES['uploadedimage']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['uploadedimage']['error'] = $files['error'][$i];
$_FILES['uploadedimage']['size'] = $files['size'][$i];
$this->upload->initialize($config);
if ($this->upload->do_upload('uploadedimage', $i)) {
$data['uploadedimage'] = $this->upload->data();
$image_name[$i] = $data['uploadedimage']['file_name'];
//$this->_property_images_resize($data); // Private Function For Resize
$data['images'] = implode(',',$image_name);
$this->model_users->insert_property_details($data))
redirect('view');
} else {
$this->form_validation->set_message('fileupload_check', $this->upload->display_errors());
return FALSE;
}
}
}
I further needed to resize the images with the help of a private function in controller:
private function _property_images_resize($data) {
$this->load->library('image_lib');
$config = array(
'image_library' => 'gd2',
'source_image' => 'uploads/property-images/'.$data['uploadedimage']['file_name'],
'new_image' => 'uploads/profile/test1/',
'create_thumb' => TRUE,
'maintain_ratio' => TRUE,
'width' => 10,
'height' => 10
);
$this->image_lib->initialize($config);
if(!$this->image_lib->resize()) echo $this->image_lib->display_errors();
}
After adding this second function, it changes nothing. Images uploads the way they were before without resizing.
Looking for someone's help as can't figure it out.
For validation Callback
function if_image_was_selected(){
$this->form_validation->set_message('if_image_was_selected', 'Please select at least 1 image in jpg/jpeg/png/gif format.');
$number_of_files = count($_FILES['uploadedimages']['tmp_name']);
$files = $_FILES['uploadedimages'];
for($i=0;$i<$number_of_files;$i++) {
if($_FILES['uploadedimages']['error'][$i] != 0) {
return false;
}else{
return true;
}
}
}
Are you sure your not suppose to call:
$this->load->library('image_lib', $config);
instead of
$this->image_lib->initialize($config);
Does your webserver user have write permissions to the uploads/profile/test1/ directory?
Do you get any error message? Have you checked the PHP log or Apache log?
Try adding this code below, above your code to see the error echo'd out to the screen if you can.
error_reporting(E_ALL);
ini_set("display_errors", 1);
I have an issue with codeigniter file upload library. I am trying to upload multiple files (7 images), i renamed them and after which uploaded to my server file system. But i cannot get the new name to save in my database.
Here is my Controller
if (isset($_POST['carform']))
{
$dir = './uploads/cars';
$config['upload_path'] = $dir;
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '2048';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['remove_spaces'] = 'TRUE';
$uid = $this->tank_auth->get_user_id();
$config['file_name'] = time().$uid;
$this->load->library('upload', $config);
foreach($_FILES as $field => $file)
{
if($file['error'] == 0)
{
// So lets upload
if ($this->upload->do_upload($field))
{
$data = array('upload' => $this->upload->data());
$this->cars_model->set_car($data);//end foreach loop.....
$id = $this->db->insert_id();
redirect('/cars/details/'.$id.'');
}else
{
$errors = $this->upload->display_errors();
echo($errors);
}
}
}
}//end if statement ...
You do have a helper function within Codeigniter File Uploading Class: $this->upload->data(). In order to get the filename do this:
$my_data=$this->upload->data();
$file_name=$my_data['filename'];
check the manual here
edit:
to insert data into database assuming $filename is a string you need first explode it into an array
$filename="14010989464.jpg 140109894641.jpg 140109894642.jpg 140109894643.jpg 140109894644.jpg 140109894645.jpg 140109894646.jpg";
$fn=explode(' ',$filename);
then you can insert the data (imagename) into the column img of your table test like this:
foreach ($fn as $key=>$val){
$data['img']=$fn[$key];
$this->db->insert('test', $data);
}
can use for
ex :
$this->load->library('upload', $config);
for($i=1;$i<=5;$i++) //5 = total image
{
if (!$this->upload->do_upload('userfile'.$i))
{
$data['error'] = array('error' => $this->upload->display_errors());
}
else
{
$upload_data = $this->upload->data();
$data[$i] = $upload_data['file_name'];
}
}
$data_x = array(
'image1' => $data['1'],
'image2' => $data['2'],
'image3' => $data['3'],
'image4' => $data['4'],
'image5' => $data['5'],
);
This is my upload model
function upload_avatar()
{
$id = $this->tank_auth->get_user_id();
//config upload parameters and upload image
$config = array(
'allowed_types' => 'jpeg|jpg|png',
'upload_path' => $this->upload_path,
'max_size' => 2048,
'encrypt_name' => TRUE,
'overwrite' => FALSE,
);
$this->load->library('upload', $config);
$this->upload->do_upload();
//get upload data, config, resize uploaded image, save in avatars subfolder
$image_data = $this->upload->data();
if ($image_data['file_size'] < 2048) {
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->upload_path . '/avatars',
'maintain_ratio' => TRUE,
'width' => 125,
'height' => 125
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
//only burn avatar path to user_profiles table if no upload errors
if (!$this->upload->display_errors()) {
$data = array('avatar' => base_url() . 'images/avatars/' . $image_data['file_name']);
$this->db->where('id', $id);
$this->db->update('user_profiles', $data);
}
//delete the original file from server
$this->load->helper('file');
unlink($image_data['full_path']);
} else {
echo $this->upload->display_errors();
}
}
I can't get the error message to echo straight to the browser when I try uploading a file > 2MB.
To be fair, CI ignores this large file, and uploads correctly when a file is < 2MB.
The only thing is that I can't get the error message to show on the front-end to give the suer some feedback.
Any ideas what's wrong here?
$config['upload_path'] = 'uploads/category/'.$id.'/';
//echo $file_name;die;
//echo $config['upload_path'];
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '2048';
$config['max_width'] = '1920';
$config['max_height'] = '1280';
$this->load->library('upload');
foreach ($_FILES as $key => $value) {
//print_r($key);
if (!empty($key['name'])) {
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)) {
// echo 'test';die;
// rmdir('uploads/category/'.$id);
$errors = $this->upload->display_errors();
flashMsg($errors);
}
}
}
try this!!
Is your post_max_size limit less than 2MB? (http://ca3.php.net/manual/en/ini.core.php#ini.post-max-size) If so the file may have been discarded before your code is invoked.
Update:
If you take out your function call in the else block, and just drop in an exit('too big'); are you able to see errors then? If so there may be an issue with how you're pasing the call off.