File upload already exist function in codingniter - php

Actually, i'm trying to upload file in codigniter it's done but i want if file is already exist in uploads folder will show error message please help me.
Here my code controller:
if($this->input->post('userSubmit'))
{
//echo "comm";
if(!empty($_FILES['file_upload']['name']))
{
// echo "coming";
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'doc|docx|pdf';
$config['file_name'] = $_FILES['file_upload']['name'];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('file_upload'))
{
//echo "cominggggggg";die;
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
//print_r($picture);die;
}
else
{
$picture = '';
}
}
else
{
$picture = '';
}
}

You don't need to initialize the CI upload settings twice and you should use ./uploads/ rather than uploads/. Otherwise it is just a matter of checking like so:
if ($this->input->post('userSubmit')) {
if (!empty($_FILES['file_upload']['name'])) {
if (is_file('./uploads/' . $_FILES['file_upload']['name'])) {
show_error('File already exists!'); // function exits
}
$config['upload_path'] = './uploads/'; // correct way
$config['allowed_types'] = 'doc|docx|pdf';
$config['file_name'] = $_FILES['file_upload']['name'];
$this->load->library('upload', $config);
//$this->upload->initialize($config); you already did this ^
if ($this->upload->do_upload('file_upload')) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
}
} else {
$picture = '';
}
}

Related

Trying to upload multiple files in codeigniter. Getting do_upload expects a sting array given error

I am trying to upload multiple files in CodeIgniter. But I am getting below warning and error
A PHP Error was encountered
Severity: Warning
Message: is_uploaded_file() expects parameter 1 to be string, array given
Filename: libraries/Upload.php
Error: You did not select a file to upload.
Here is my file upload form control:
<input type="file" accept="image/png, image/jpeg, image/gif, application/pdf, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, text/plain, application/pdf" name="file[]" multiple/>
My Controller function
Here $file is the name of the file being uploaded which I pass to this file_upload() from other function.
public function file_upload($file){
$new_file = "";
$original_file_name = '';
if($file!=""){
$file_name = $file;
$original_file_name = $file_name;
$random = rand(1, 10000000000000000);
$makeRandom = hash('sha512', $random.$this->input->post('title') . config_item("encryption_key"));
$file_name_rename = $makeRandom;
$explode = explode('.', $file_name);
if(count($explode) >= 2) {
$new_file = $file_name_rename.'.'.$explode[1];
$config['upload_path'] = "./uploads/images";
$config['allowed_types'] = "gif|jpg|png|jpeg|pdf|doc|xml|docx|GIF|JPG|PNG|JPEG|PDF|DOC|XML|DOCX|xls|xlsx|txt|ppt|csv";
$config['file_name'] = $new_file;
$config['max_size'] = '3072';
$config['max_width'] = '3000';
$config['max_height'] = '3000';
$this->load->library('upload',$config);
$this->upload->initialize($config);
if(!$this->upload->do_upload("file")) {
print_r($this->upload->display_errors());
} else {
echo "success";
}
} else {
//error
}
}else{
//some code here
}
}
imho your code doesn't make any sense - but the main problem here is - you've to change the _FILES array
Something like that should work
public function file_upload()
{
$strInputFileName = "file";
$arrFiles = $_FILES;
$config['upload_path'] = "./uploads/images";
$config['allowed_types'] = "gif|jpg|png|jpeg|pdf|doc|xml|docx|GIF|JPG|PNG|JPEG|PDF|DOC|XML|DOCX|xls|xlsx|txt|ppt|csv";
$config['file_name'] = $new_file;
$config['max_size'] = '3072';
$config['max_width'] = '3000';
$config['max_height'] = '3000';
$config['file_name'] = $this->getRandomFileName();
if (is_array($_FILES[$strInputFileName]['name']))
{
$countFiles = count($_FILES[$strInputFileName]['name']);
for($i=0;$i<$countFiles; $i++)
{
//overwrite _FILES array
$_FILES[$strInputFileName]['name'] = $arrFiles[$strInputFileName]['name'][$i];
$_FILES[$strInputFileName]['type'] = $arrFiles[$strInputFileName]['type'][$i];
$_FILES[$strInputFileName]['tmp_name'] = $arrFiles$strInputFileName]['tmp_name'][$i];
$_FILES[$strInputFileName]['error'] = $arrFiles[$strInputFileName]['error'][$i];
$_FILES[$strInputFileName]['size'] = $arrFiles[$strInputFileName]['size'][$i];
$this->upload->initialize($config);
if(!$this->upload->do_upload($strInputFileName))
{
print_r($this->upload->display_errors());
}
else
{
echo "success";
}
}
}
else
{
$this->upload->initialize($config);
if(!$this->upload->do_upload($strInputFileName))
{
print_r($this->upload->display_errors());
}
else
{
echo "success";
}
}
}
private function getRandomFileName()
{
$random = rand(1, 10000000000000000);
return hash('sha512', $random.$this->input->post('title') . config_item("encryption_key"));
}

File Upload in Codeigniter

I am trying to upload image using code-igniter, but it's not possible, why I don't know. Can anyone help me?
Here is code I have tried
public function upload(){
$config['upload_path'] = "./assets/uploads/";
$config['allowed_types'] = "jpg|png|jpeg|gif";
$this->load->library("upload" , $config);
$rs = $this->upload->do_upload("userfile");
print_r($rs);
print_r($_FILES);
if(!$rs){
$error = array('error'=>$this->upload->display_errors());
$this->load->view("main_view", $error);
}
else{
$file_data = $this->upload->data(); $data['img'] = "localhost/FileUpload/assets/uploads/";
$file_data['file_name']; $this->load->view("success_msg" , $data);
}
}
I'm not able to actually test this of course, but I believe this will get you started.
public function upload() {
$name = 'something'; // set this based on your requirements, I often use random strings or user names according to the situation.
$config['upload_path'] = "assets/uploads/";
$config['allowed_types'] = "jpg|png|jpeg|gif";
$config['file_name'] = $name;
$this->load->library("upload" , $config);
$rs = $this->upload->do_upload("userfile");
print_r($rs);
print_r($_FILES);
if(!$rs) {
$error = array( 'error'=>$this->upload->display_errors() );
$this->load->view("main_view", $error);
}
else {
$file_data = $this->upload->data();
$file_name = $file_data['file_name'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION); //Useful to store your name in database if/when you need to
$data = array('upload_data' => $upload_data);
$this->load->view("success_msg" , $data);
}
}

How to update pdf file and image file in codeigniter

I want to upload PDF file as well as image file with on one do_upload
I want to upload two different files in two different directory by using codeigniter. I wrote the following code in my model. but it will upload only the first image.
if($_POST){
if($_FILES['productimage']['name']){
$img = $_FILES['productimage']['name'];
$config['upload_path'] = './uploads/products/';
$config['allowed_types'] = 'png|jpg|gif|bmp';
$config['overwrite'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('productimage'))
{
$errors = array('error' => $this->upload->display_errors());
$img="";
}
else
{
$data =$this->upload->data();
$img=$data['file_name'];
//print_r($img);die;
}
}else{
$img=$this->input->post('image_old');
}
if($_FILES['productpdf']['name']){
$img = $_FILES['productpdf']['name'];
$config['upload_path'] = './uploads/products/';
$config['allowed_types'] = 'png|jpg|gif|bmp|pdf';
$config['overwrite'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('productpdf'))
{
$errors = array('error' => $this->upload->display_errors());
$pdf="";
}
else
{
$data =$this->upload->data();
$pdf=$data['file_name'];
}
}else{
$pdf=$this->input->post('pdf_old');
}
// print_r($img);print_r($pdf);die;
$title = $this->input->post('productname');
$content = $this->input->post('description');
$status = $this->input->post('status');
$this->db->where('product_id', $id);
$this->db->update('products',array('product_name'=>$title,'product_content'=>$content,'product_image'=>$img,'product_file'=>$pdf,'product_status'=>$status));
$this->db->where('product_id',$id);
$this->db->delete('products_filter');
$filters= $_POST['filter'];
foreach ($filters as $value)
{
$this->db->insert('products_filter',array('product_id' => $id,'products_search_id'=>$value));
}
return ($this->db->affected_rows() != 1)? false:true;
}else{
redirect(base_url('admin/products/product-list/'.$redirectid));
}
}
Please check my code
this code to handle pdf or images file upload in different directory
<?php
if($_POST){
if($_FILES['productimage']['name'])
{
$custom_file_name = $_FILES['productimage']['name'];
$file_ext = end(explode('.', $custom_file_name));
if($file_ext=='pdf')
{
$upload_path_directory='./uploads/products/pdf/';
$file_field_name="productimage";
}
else{
$upload_path_directory='./uploads/products/images/';
$file_field_name="productpdf";
}
$config['upload_path'] = $upload_path_directory;
$config['allowed_types'] = 'png|jpg|gif|bmp|pdf';
$config['overwrite'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload("$file_field_name"))
{
$errors = array('error' => $this->upload->display_errors());
$custom_file_name="";
}
else
{
$data =$this->upload->data();
$custom_file_name=$data['file_name'];
}
?>
First to make sure to upload library libraries and form validation if don't know where to set libaray will mention below*
$this->load->libaray("upload");
$this->load->libaray("form_validation");
to add this code in if condition

my image is not get inserted while uploading using codeigniter

My image is not get inserted while uploading using codeigniter:
function add_newblog()
{
$sess_id = $this->session->userdata('id');
$result['query'] = $this->login_model->profile($sess_id);
foreach($result['query'] as $row)
{
$email = $row->blogger_email;
$url = $row->blogger_url;
$author = $row->blogger_name;
if ($this->input->post('submit')) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$media = 'No Image Uploaded';
$title = $this->input->post("title");
$category = $this->input->post('category');
$content = $this->input->post('content');
$this->blog_model->add_newblog($sess_id,$title,$category,$content,$media,$email,$url,$author);
$this->session->set_flashdata('valid', 'Blog Created without Image');
redirect('content_writer/add_blog');
}
else {
$data = array('upload_data' => $this->upload->data());
$data = $this->upload->data();
$media = $data['file_name'];
$title = $this->input->post("title");
$category = $this->input->post('category');
$content = $this->input->post('content');
$this->blog_model->add_newblog($sess_id,$title,$category,$content,$media,$email,$url,$author);
$this->session->set_flashdata('valid', 'Blog Created');
redirect('content_writer/add_blog');
}
}
else{
$this->session->set_flashdata('invalid', 'Invalid');
redirect('content_writer/add_blog');
}
}
}
The else condition always works. The image name does not get saved in the image path.
the problem is here in this line
$config['upload_path'] = './uploads/';
instead use
$config['upload_path'] = 'uploads/<folder name>';
OR incase you want to save the image directly in uploads folder just use
$config['upload_path'] = 'uploads/';
as well as make your that you form in the veiw section is open with form_open_multipart()
hope this will solve your problem
Set your max_size, max_width and max_height. This would be an example below.
$config['max_size'] = '3000';
$config['max_width'] = '1500';
$config['max_height'] = '1500';
You havent passed the image name in $this->upload->do_upload() method.
use your
input type='file' name=myDoc
$this->upload->do_upload("myDoc")

Codeigniter upload optional

I looked for this in Google and different answers on stackoverflow. And probaly there is an good answer in them but still i don't get how i can implent it in my own code.
I got my own public function to upload an image, but now i want it to be optional. At this moment someone needs to upload an file to pass the validation, how can i make this optional?
my function:
public function _do_upload_image()
{
$config['upload_path'] = './company_images/';
$config['allowed_types'] = 'jpg|jpeg|png';
$this->load->library('upload', $config);
if (!$this->upload->do_upload())
{
$this->form_validation->set_message('_do_upload_image', $this->upload->display_errors());
}
else
{
$this->_upload_data = $this->upload->data();
}
}
Thanks in advance
--edit--
For other people, the answer worked and i gave my file_name an other name when there was no image uploaded. It looks like this:
public function _do_upload_image()
{
$config['upload_path'] = './company_images/';
$config['allowed_types'] = 'jpg|jpeg|png';
$returnArr = array();
$this->load->library('upload', $config);
if (!$this->upload->do_upload())
{
$returnArr = array('file_name' => 'leeg.jpg');
}
else
{
$returnArr = $this->upload->data();
}
$this->_upload_data = $returnArr;
}
If you mean you need to make your upload function optional then you can just do:
public function _do_upload_image()
{
$config['upload_path'] = './company_images/';
$config['allowed_types'] = 'jpg|jpeg|png';
$returnArr = array();
$this->load->library('upload', $config);
if ($this->upload->do_upload())
{
$returnArr = $this->upload->data();
}
return $returnArr; //just return the array, empty if no upload, file data if uploaded
}
Hope that makes sense
codeigniter file upload optionally ...works perfect..... :)
---------- controller ---------
function file()
{
$this->load->view('includes/template', $data);
}
function valid_file()
{
$this->form_validation->set_rules('userfile', 'File', 'trim|xss_clean');
if ($this->form_validation->run()==FALSE)
{
$this->file();
}
else
{
$config['upload_path'] = './documents/';
$config['allowed_types'] = 'gif|jpg|png|docx|doc|txt|rtf';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile',FALSE))
{
$this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());
if($_FILES['userfile']['error'] != 4)
{
return false;
}
}
else
{
return true;
}
}
i just use this lines which makes it optionally,
if($_FILES['userfile']['error'] != 4)
{
return false;
}
$_FILES['userfile']['error'] != 4 is for file required to upload.
you can u make it unneccessory by using $_FILES['userfile']['error'] != 4 , then it will pass this error for file required and
works great with other types of errors if any by using return false ,
hope it works for u ....

Categories