How to concatenate image name with date in codeigniter - codeigniter

I want to store image name with date in folder and database.
For example image name is Desert.png
I want to store in database and folder like this: 2016-08-29Desert.png
$this->upload->do_upload(date('Y-d-m).'photo');
This code does not save image in folder and database.
How to solve this in CodeIgniter

I would advise you to generate a random string along with the name of the file. But from what you asked, the code below should be enough.
$this->load->library('upload');
$imagePath = './images/';
if(!file_exists($imagePath))
mkdir($imagePath, 0777, true);
$name_parts = pathinfo($_FILES['photo']['name']);
$name_full = preg_replace('/\s+/', '', $name_parts['filename']);
$file_name = date('Y-m-d') . '-' . $name_full;
$config['upload_path'] = $imagePath;
$config['file_name'] = $file_name;
$config['allowed_types'] = 'png|bmp|jpg';
$config['max_size'] = '1024'; // 1MB~
$config['overwrite'] = FALSE;
$this->upload->initialize($config);
if($this->upload->do_upload('photo') == FALSE)
return;

Related

Is it possible to move the files in folder to different subfolders according to database school_id

I have done an image upload function for large registration functionality. My uploaded files are stored in a single folder.. but I want to move those files into a separate folder with id stored in the database. is it possible to move those files into separate folders now??
I want to move the uploaded files into a folder with the name of id in the database. I cant do it manually since the uploads folder has many thousands of images. is it possible to do it in code?
public function add_applicants()
{
if (isset($_FILES['photo']) == 1) {
$config['upload_path'] = FCPATH . 'uploads/';
$this->upload_path = $config['upload_path'];
if ($this->validate_upload_path() == TRUE)
{
$config['upload_path'] = $this->upload_path;
}
$config['allowed_types'] = 'jpg';
$config['max_size'] = 2000;
$config['remove_spaces'] = TRUE;
$config['overwrite'] = true;
$config['file_name'] = date('Ymdhis') . '.jpg';
$file_name = $config['file_name'];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('photo')) {
$this->upload->display_errors();
}
}
$data = $this->input->post();
$data['photo'] = $file_name;
$insetapplicants = $this->Welcome_Model->insertApplicants($data);
if ($insetapplicants == 'Success') {
echo "<script>
alert('New Applicants Added Successfully');
window.location.href='dashboard';
</script>";
}
}
public function index() {
$data['mediumwise_details'] = $this->Welcome_Model->mediumwise_home();
$this->load->view('home',$data);
}
I expect that the files are moved to different folders
For example, my uploads folder has 10 photos of different school_Id stored in the same folder. but I want if 2 photos are from one school_id means, a folder name with that school_id is created and that 2 photos are placed inside that folder. likewise different folder for different school_id 's
I hope the following code will help you. let me know if it does not work.
create on function or method in controller place following code and run that function make necessary changes I have created below code based on the information you have given us.
$result = $this->db->get('mts_applicants')->result_array();
if($result){
foreach($result as $row){
$old_path = FCPATH . 'uploads/';
$new_path = FCPATH . 'uploads/'.$row['school_code'].'/';
$old_name = $old_path.$row['photo'];
$new_name = $new_path.$row['photo'];
if(!is_dir($new_path)){
mkdir($new_path, 0777, true);
}
rename($new_name, $old_name) ;
}
}

How to remove existing file when uploading new one in codeigniter file uploading?

I am using codeigniter file uploading class to upload files and images in my local folder.I am using the code below, it's working fine.
public function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|txt|sql';
$config['max_size'] = 8048000;
$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('Emp_details_view', $error);
}
else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
Now, my question is how to remove previously added file when uploading new one.
You can use unlink() function to delete your previous image
unlink('image-path/image-name');
first save your filename in a database table then when unlinking take that value from database and unlink. here uploads is the foldername .
unlink("uploads/".$val['image']);
$val['image'] contains imagename from db.

how to get upload file name in codeigniter

Hi i'm trying to upload image to a folder and image name in database
in view
echo form_open_multipart('subscribers_c/actioncreate',array('class'=>'form'));`enter code here`
<input type='file' name='img'>
in controller
$config['upload_path'] ='./assets/uploads/subscribers_photos'; //The path where the image will be save
$config['allowed_types'] = 'gif|jpg|png'; //Images extensions accepted
$config['max_size'] = '2048';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config); //Load the upload CI library
if (!$this->upload->do_upload('img'))
{
$uploadError = array('upload_error' => $this->upload->display_errors());
//$this->set_flashdata('msg_error', $uploadError, site_url().'/subscribers_c/actioncreate');
}
$file_info = $this->upload->data('img');
$img_name = $file_info['file_name'];
$data=array(
'chit_fund_id'=>$this->input->post('cid'),
'first_name'=>$this->input->post('fname'),
'last_name'=>$this->input->post('lname'),
'dob'=>$this->input->post('bd'),
'gender'=>$this->input->post('g'),
'contact_number'=>$this->input->post('mob'),
'address'=>$this->input->post('add'),
'email_id'=>$this->input->post('eml'),
'bid_status'=>$this->input->post('b_status'),
'user_status'=>$this->input->post('u_status'),
'image_name'=>$img_name,
);
//print_r($data);
image_name is not having any value
how to get image name .
Instead of img in upload data
$file_info = $this->upload->data('img');
Try
$file_info = $this->upload->data();
$img = $file_info['file_name'];
And on here $config['upload_path'] = './assets/uploads/subscribers_photos'; end with /
Like $config['upload_path'] = './assets/uploads/subscribers_photos/';
Inside the view call the form_upload function(if needed, your one is also correct):
<?php echo form_upload('pic'); ?>
Inside controller function for upload:
$img_name = $_FILES["pic"]["name"];
By using this code you will get the file name.
$img_name = $this->upload->data('file_name');

CodeIgniter renaming image to be the next id in db table

I'm brand new to codeigniter and am trying to rename my image to be the next auto incremented number in the table.
I was looking into using
$id = $this->db->insert_id();
But am still unsure how to add 1 to that value and use it for my file name. I've got image resizing all set just need to rename and I'm set.
Any help would be much appreciated!!! Thanks so much!
Controller:
$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());
redirect('index.php/success');
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->resize($data['upload_data']['full_path'], $data['upload_data']['file_name']);
redirect('index.php/success');
echo $img;
}
// Update Record to save filename
}
function resize($path, $file){
$config['image_library']= 'gd2';
$config['source_image']= $path;
$config['create_thumb']= TRUE;
$config['maintain_ration']= TRUE;
$config['width']= 320;
$config['height']= 196;
$config['new_image']='./uploads/'.$file;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
Get the last number of the id column which you have set to auto increment.You can use sql Max() function to that.Then simply add a 1 to that and use it for the image renaming.That's it!!!

How to upload image in CodeIgniter?

In view
<?php echo form_open_multipart('welcome/do_upload');?>
<input type="file" name="userfile" size="20" />
In controler
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';
$config['overwrite'] = TRUE;
$config['encrypt_name'] = FALSE;
$config['remove_spaces'] = TRUE;
if ( ! is_dir($config['upload_path']) ) die("THE UPLOAD DIRECTORY DOES NOT EXIST");
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')) {
echo 'error';
} else {
return array('upload_data' => $this->upload->data());
}
}
And I call this function like this
$this->data['data'] = $this->do_upload();
and view this image:
<ul>
<?php foreach ($data['upload_data'] as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
I don't know what's the error.
It seems the problem is you send the form request to welcome/do_upload, and call the Welcome::do_upload() method in another one by $this->do_upload().
Hence when you call the $this->do_upload(); within your second method, the $_FILES array would be empty.
And that's why var_dump($data['upload_data']); returns NULL.
If you want to upload the file from welcome/second_method, send the form request to the welcome/second_method where you call $this->do_upload();.
Then change the form helper function (within the View) as follows1:
// Change the 'second_method' to your method name
echo form_open_multipart('welcome/second_method');
File Uploading with CodeIgniter
CodeIgniter has documented the Uploading process very well, by using the File Uploading library.
You could take a look at the sample code in the user guide; And also, in order to get a better understanding of the uploading configs, Check the Config items Explanation section at the end of the manual page.
Also there are couple of articles/samples about the file uploading in CodeIgniter, you might want to consider:
http://code.tutsplus.com/tutorials/how-to-upload-files-with-codeigniter-and-ajax--net-21684
http://runnable.com/UhIc93EfFJEMAADX/how-to-upload-file-in-codeigniter
http://jamshidhashimi.com/image-upload-with-codeigniter-2/
http://code.tutsplus.com/tutorials/how-to-upload-files-with-codeigniter-and-ajax--net-21684
http://hashem.ir/CodeIgniter/libraries/file_uploading.html (CodeIgniter 3.0-dev User Guide)
Just as a side-note: Make sure that you've loaded the url and form helper functions before using the CodeIgniter sample code:
// Load the helper files within the Controller
$this->load->helper('form');
$this->load->helper('url');
// Load the helper files within the application/config/autoload
$autoload['helper'] = array('form', 'url');
1. The form must be "multipart" type for file uploading. Hence you should use `form_open_multipart()` helper function which returns:
``
Simple Image upload in codeigniter
Find below code for easy image upload:
public function doupload()
{
$upload_path="https://localhost/project/profile"
$uid='10'; //creare seperate folder for each user
$upPath=upload_path."/".$uid;
if(!file_exists($upPath))
{
mkdir($upPath, 0777, true);
}
$config = array(
'upload_path' => $upPath,
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('userpic'))
{
$data['imageError'] = $this->upload->display_errors();
}
else
{
$imageDetailArray = $this->upload->data();
$image = $imageDetailArray['file_name'];
}
}
//this is the code you have to use in you controller
$config['upload_path'] = './uploads/';
// directory (http://localhost/codeigniter/index.php/your directory)
$config['allowed_types'] = 'gif|jpg|png|jpeg';
//Image type
$config['max_size'] = 0;
// I have chosen max size no limit
$new_name = time() . '-' . $_FILES["txt_file"]['name'];
//Added time function in image name for no duplicate image
$config['file_name'] = $new_name;
//Stored the new name into $config['file_name']
$this->load->library('upload', $config);
if (!$this->upload->do_upload() && !empty($_FILES['txt_file']['name'])) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('production/create_images', $error);
} else {
$upload_data = $this->upload->data();
}
Change the code like this. It works perfectly:
public function uploadImageFile() //gallery insert
{
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$new_image_name = time() . str_replace(str_split(' ()\\/,:*?"<>|'), '',
$_FILES['image_file']['name']);
$config['upload_path'] = 'uploads/gallery/';
$config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
$config['file_name'] = $new_image_name;
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['$min_width'] = '0';
$config['min_height'] = '0';
$this->load->library('upload', $config);
$upload = $this->upload->do_upload('image_file');
$title=$this->input->post('title');
$value=array('title'=>$title,'image_name'=>
$new_image_name,'crop_name'=>$crop_image_name);}
$image_folder = APPPATH . "../images/owner_profile/" . $_POST ['mob_no'] [0] . $na;
if (isset ( $_FILES ['image'] ) && $_FILES ['image'] ['error'] == 0) {
list ( $a, $b ) = explode ( '.', $_FILES ['image'] ['name'] );
$b = end ( explode ( '.', $_FILES ['image'] ['name'] ) );
$up = move_uploaded_file ( $_FILES ['image'] ['tmp_name'], $image_folder . "." . $b );
$path = ($_POST ['mob_no'] [0] . $na . "." . $b);
Below code for an uploading a single file at a time.
This is correct and perfect to upload a single file.
Read all commented instructions and follow the code.
Definitely, it is worked.
public function upload_file() {
***// Upload folder location***
$config['upload_path'] = './public/upload/';
***// Allowed file type***
$config['allowed_types'] = 'jpg|jpeg|png|pdf';
***// Max size, i will set 2MB***
$config['max_size'] = '2024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
***// load upload library***
$this->load->library('upload', $config);
***// do_upload is the method, to send the particular image and file on that
// particular
// location that is detail in $config['upload_path'].
// In bracks will set name upload, here you need to set input name attribute
// value.***
if($this->upload->do_upload('upload')) {
$data = $this->upload->data();
$post['upload'] = $data['file_name'];
} else {
$error = array('error' => $this->upload->display_errors());
}
}
check $this->upload->initialize($config); this works fine for me
$new_image_name = "imgName".time() . str_replace(str_split(' ()\\/,:*?"<>|'), '',
$_FILES['userfile']['name']);
$config = array();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
$config['file_name'] = $new_image_name;
$config['max_size'] = '0';
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|mp4|jpeg';
$config['file_name'] = url_title("imgsclogo");
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$this->upload->initialize($config);
$this->upload->do_upload();
$data = $this->upload->data();
}

Resources