PHP: How to get File Name & Extension of uploaded file in Codeigniter? - php

i need to store only filename + extension of file when upload and rename done to my databse.my problem is can't get extension.
$new_file_name=date("mdY")."_".time();
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$config['file_name'] = $new_file_name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('uploadFile'))
{
$error = array('error' => $this->upload->display_errors());
var_dump($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
var_dump($data);
echo $config['file_name'] . $config['file_ext'];
}
my next question load helper form for ? or need load form to use library form_validation ?
$this->load->helper(array('form')); for ?
$this->load->library('form_validation'); this for validation rule

custom upload filename codeigniter
first you can to explode with (.) in filename, then you get array, then catch the end array with function end().
and last i can to join filename with this date.
$dname = explode(".", $_FILES['gambar']['name']);
$ext = end($dname);
$_FILES['gambar']['name'] = strtolower('fitur_h_'.date('YmdHis').'.'.$ext);
//fitur_h_20200120143157.png //output filename
i hope my answer can help you

After you uploaded the file, you can get its property by:
$saved_file_name = $this->upload->data('file_name');
// will give you the filename along with the extension
If you want to get the file extension before uploading it, use core php:
$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
or to make it clean
$filename= $_FILES["file"]["name"];
$file_ext = pathinfo($filename,PATHINFO_EXTENSION);

Simply use the below code for image name with extension on post to solve issue,
$config['file_name'].$this->upload->data('file_ext')

I was having the same problem and i just figured it out.
I was trying to get the name with this: $this->upload->data('file_name');
but it was always empty, and i just finded out that you need to set something before you can access the data() array.
When your code successfully uploads the file, type this: $data = array('upload_data' => $this->upload->data());
after that, all the data() indexes will be accessible, 'file_name' included. The list with all indexes is in the documentation: https://codeigniter.com/user_guide/libraries/file_uploading.html#preferences
ps: I know it's been 2 years since this post but maybe someone can find it helpful if they stuck with this too.

I know this is too late, still I'm giving the answer.
If you want to get the image extension, then use pathinfo function with PATHINFO_EXTENSION parameter.
eg.
$imageExtention = pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION);
echo imageExtention;

you can get file name using this code
$file_name = $data['file_name'];
echo $file_name;
and extension for file
$ext = implode('.',$file_name);
echo $ext[1];

Related

adding timestamp while uploading image file is not working

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
}

Rename and replace an image in my images folder php

I'm a newbie working on an app in which i allow users to upload their pics and when they need to change the pic I can't delete the old pic and hence cant rename too. Here's my code to upload an img as per tutorial in codeigniter.
$config['upload_path'] = './img/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['file_name'] = $id.'_img';
$this->load->library('upload', $config);
if ( $this->upload->do_upload())
{
$this->view_data['message'] = "File Uploaded";
}
Here I pass the user id and hence need to rename and replace the old image with the name like 44_img..... Any help would be appreciated , Thanks in advance....
Try this for deletion of the old file:
$oldfile = $config['upload_path'].$config['file_name'];
if( file_exists( $oldfile ) ){
unlink( $oldfile );
}
You can use $this->upload->data() to retrieve data related to upload, and inside do something like that:
if ( $this->upload->do_upload())
{
$this->view_data['message'] = "File Uploaded";
$data = $this->upload->data();
$path = $data['full_path'];
$dir = dirname($path);
$ext = pathinfo($path, PATHINFO_EXTENSION);
if(rename($path, $dir.'/'.$your_file_new_name.'.'.$ext)) {
$this->view_data['message'] .= '<br/> And renamed';
}
}
Note that you must have enough rights to upload your files, especially write righths on a directory you want to upload to. Also, good practice is to give files unique names and separate them into user related directories. For example, you can combine mysql users id with image id.
if you want to over write the existing one, i.e., delete the older one and save new one with same name then
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if you want to keep both, better save the new one with old one, the code will automatically rename the new one and you can save the name of new uploaded image to access it
$config['overwrite'] = FALSE;
$this->load->library('upload', $config);
if ($this->upload->do_upload())
{
$uploaded_filename = $this->CI->upload->file_name; //name of the save image
$this->view_data['message'] = "File Uploaded";
}

Codeigniter - loading images from browser

I've made an upload form using CI.
Now my photos are uploaded in C:\xampp\htdocs\ci_new\uploads*.jpg
I want these images to be accessible from the web, so i can add their path to my database, but when i try to load them via localhost/ci_new/uploads/*.jpg it gives me error - the image files arent there (so im wrong with the folder stuff i guess).
Could you please tell me where do i need to put the images, so the folder could be public for the visitors and so i can fill the path as an url in my database.
This is my upload code if needed:
function do_upload(){
$config['upload_path'] = './uploads';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size']='5000';
$config['max_width'] = '1024';
$config['max_height']= '768';
$this->load->library('upload',$config);
if(!$this->upload->do_upload()) {
$error = array('error'=>$this->upload->display_erros());
$this->load->view('upload_form', $error);
} else {
$data=array('upload_data'=>$this->upload->data());
//$this->db->insert('images', $data);
$this->load->view('upload_success', $data);
print_r($data);
}
}
Thank you.
Make sure you have converted your image file name in order to convert the special characters which is not allowed in URL.
Try:
$filename = explode('.', $filename);
$tmp_filename = str_replace(" ", "_", $filename[0]);
/* replaces space with '-' */
$tmp_filename = preg_replace('/[^A-Za-z0-9\-]/', '_', $tmp_filename);
/* removes special chars */
$tmp_filename = preg_replace('/_+/', '_', $tmp_filename);
/* replaces multiple '_' with single */
$filename = $tmp_filename.
'.'
.$filename[sizeof($filename)-1];
/*Concatenating extension again.*/

Can't upload Image CodeIgniter, filetype error

I have write below code :
function upld_logo()
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$data['msg']='Sorry! Cant Upload' . $error['error'];
$data['main_content']='message';
$this->load->view('template',$data);
}
else
{
//$data = array('upload_data' => $this->upload->data());
$names = $this->upload->data();
$k=$names['file_name'];
$data['msg']='Your Logo Successfully Uploaded. ';
$data['main_content']='message';
$this->load->view('template',$data);
}
}
When I upload Image file with name logo.gif it show error message :
The filetype you are attempting to upload is not allowed.
Find this code in your system->libraries->Upload.php line 200
$this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $this->file_type);
and replace with this:
$this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type']);
Yes I also got the same error.
And if u change the $[allowed_types] = "*" (allowed all files)
you will find that upload is success but your image file don't have a type!
I think there's something wrong with the CI library maybe?
I have spent some time with the same issue. You might find codeigniters default upload library is using a couple of deprecated PHP functions to find the files mime type.... Good luck, I'm still trying to patch it myself .

Upload problem with PHP: Thumbnail picking up the image name

I have the following model(codeigniter) code to upload image and thumbnail.
However the result of image path becomes, images/comfort_big.jpg and images/comfort_big.jpg.jpg.
The thumbnail image picks up the name of image and add .jpg.
I am uploading images/confort_thumb.jpg for thumb.
Can anyone tell me what's wrong please?
if ($_FILES){
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '200';
$config['remove_spaces'] = true;
$config['overwrite'] = false;
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
if (strlen($_FILES['image']['name'])){
if(!$this->upload->do_upload('image')){
$this->upload->display_errors();
exit();
}
$image = $this->upload->data();
if ($image['file_name']){
$data['image'] = "images/".$image['file_name'];
}
}
if (strlen($_FILES['thumbnail']['name'])){
if(!$this->upload->do_upload('thumbnail')){
$this->upload->display_errors();
exit();
}
$thumb = $this->upload->data();
if ($thumb['file_name']){
$data['thumbnail'] = "images/".$thumb['file_name'];
}
}
}
I had a quick look at File Uploading Class in the user guide
In the preferences tables it states:
Note:The filename should not include a file extension.
So my guess is that you get the user to name the file
$config['file_name'] = "User defined";
or remove the extension programmatically. Since you know and list the extensions already you could do
$types = array(".gif",".jpg",".png");
$image['file_name'] = str_replace($types , "", $image['file_name'] );
Your problem is that when you create a thumb you are passing the full image.
So it will add another extension to it.
Use Below code to remove extension from file name.
<?php
$filename=$image['file_name'];
$file_name_with_dot = substr($filename,0, strrpos($filename, '.') + 1);
$only_file_name = substr($file_name_with_dot,0,strlen($file_name_with_dot)-1);
?>
Now pass this $only_file_name variable to your thumb function..
It will be better to use automatic thumb creation from main image.
Hope this will help for you.

Categories