Delete uploaded file with a wrong name as the defined - php

Below is my upload function in codeigniter. I can upload a file. I also check if the file name matches the url parameter. How do i delete the file if the name does not match the url. I have tried unlink function but it does not work
function do_upload() {
$this->makeDir();
$labref = $this->uri->segment(3);
$filename = 'xyz/'. date('Y').'/'.date('M').'/'. $labref .'/' . $labref . '.xlsx';
if (file_exists($filename)) {
$data['labref'] = $this->uri->segment(3);
$data['settings_view'] = 'analyst_file_present_v';
$this->base_params($data);
} else {
$config['upload_path'] = 'xyz/'. date('Y').'/'.date('M').'/'. $labref ;
$config['allowed_types'] = 'xls|xlsx';
$this->load->library('upload', $config);
$data= $this->upload->data();
if ($data['file_name']=="$labref.'.xlsx'") {
$this->SaveFileDetails();
$this->success();
}else{
$filename = 'xyz/'.date('Y').'/'.date('M').'/'. $labref.'/'.$labref.'xlsx' ;
unlink($filename);
echo 'You have uploaded a wrong file';
}
if (!$this->upload->do_upload('worksheet')) {
$data['labref'] = $this->uri->segment(3);
$data['error'] = $this->upload->display_errors();
$data['settings_view'] = 'upload_analyst_v';
$this->base_params($data);
}
}
}

You've got some pretty nasty quote mismatches:
if ($data['file_name']=="$labref.'.xlsx'") {
^-----^---
Since you're in a double-quoted string, those ' are going to become part of the filename. Perhaps you meant:
if ($data['file_name']== $labref .'.xlsx') {
instead? (note lack of ".

It seems to me you are trying to delete the wrong file.
You should replace:
$filename = 'xyz/'.date('Y').'/'.date('M').'/'. $labref.'/'.$labref.'xlsx' ;
with:
$filename = 'xyz/'.date('Y').'/'.date('M').'/'. $labref.'/' . $data['file_name'];
To delete the uploaded file.
Edit: You have to actually do the upload before you can access the errors and data so you should move your $this->upload->do_upload() block to before the if statement.

Related

file name changes when i upload i file using do_upload function

when i upload a file using do_upload() in code igniter, it uploads the file but it renames it with underscore(_) in the place of blank spaces.
file name to be uploaded: A B C.pdf
file that uploads: A_B_C.pdf
code in controller to upload file:
//$filefeild is the name of folder in which file is to be saved
public function upload_Files($filefeild)
{
//set preferences
$config['upload_path'] = 'assets/bcc/'.$filefeild."/";
$config['allowed_types'] = 'doc|docx|xml|pdf|image|excel|jpg|png|jpeg';
$config['max_size'] = 0;
$config['filname'] = $filenamee = $_FILES[$filefeild]['name'];
$this->upload->initialize($config);
if (!$this->upload->do_upload($filefeild))
{
// case - failure
$upload_error = array('error' => $this->upload->display_errors());
}
else
{
// case - success
$upload_data = $this->upload->data();
$data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . $upload_data['file_name'] . '</strong> was successfully uploaded!</div>';
$filname = $upload_data['file_name'];
return $filenamee;
}
}
IF you see codeigniter's function exist here, you will find following code,
// Remove white spaces in the name
if ($this->remove_spaces === TRUE)
{
$this->file_name = preg_replace('/\s+/', '_', $this->file_name);
}
Which means codeigniter removes spaced and adds _ by default which can be changed by setting config variable. like $config['remove_spaces'] = FALSE;
Secondly if you want your file should be saved with underscors and you get actual name by which file is being saved then in your code you have to make a slight change as described below.
your current code
$config['filname'] = $filenamee = $_FILES[$filefeild]['name'];
Change it to
$config['filname'] = $_FILES[$filefeild]['name'];
and in success scenario get file name from $this->upload->data()
Note: you can find answere here aswell.

Dynamically Codeigniter Image Upload Rename

I am uploading multiple dynamic images with codeigniter with the following code.
foreach ($_FILES as $key => $value) {
$imagePrefix = time();
if (!$this->upload->do_upload($key))
{
echo $errors = $this->upload->display_errors();
return '';
}
else
{
$imagename = $imagePrefix.$value['name'];
$insertImage = $this->db->query("Insert into `tbl_event_imges` (`iEventID`,`vImage`) values ('".$insertId."','".$imagename."')");
}
}
When I upload an image to the specific folder this works fine; the issue is if a user uploads an image having same name, then it will automatically rename the image and upload to the folder, but what I want is to rename it by adding $imagePrefix that I have added in else part of the code and then want to upload the image with this name. But this is not working with me..
Any suggestion please?
you need to provide configuration preferences to your upload function like so:
$imagePrefix = time();
$imagename = $imagePrefix.$value['name'];
$this->load->library('upload');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = $imagename; // set the name here
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)){
...
}else{
...
}
Source: http://www.codeigniter.com/user_guide/libraries/file_uploading.html?highlight=file%20upload#setting-preferences
Just alternative, you can use CI's rename function to rename after file uploaded.
$image = $this->upload->data();
$file_path = $image ['file_path'];
$file = $image ['full_path'];
$file_ext = $image['file_ext'];
$final_file_name = time() . $image['file_name'] . $file_ext;
only add below code and it run successfully and also set encrypt_name to false
$path = $_FILES['userfile']['name'];
$newName = "Add any name".".".pathinfo($path, PATHINFO_EXTENSION);
$config['file_name'] = $newName;
$config['encrypt_name'] = false;

Laravel 4 file not uploading

$destinationPath = public_path().'/uploads/';
if (Input::hasFile('photo'))
{
$res = Input::file('photo')->move($destinationPath);
echo $destinationPath;
if($res)
{
echo '<br />good';
}
else
{
echo 'bad'.$res;
}
exit;
}
my enctype form is enctype="multipart/form-data", the uploads folder exists and its access is 777, the above statement returns good, the path is correct, what I'am doing wrong?
$photo = Input::file('photo');
if (Input::hasFile('photo'))
{
$file = Input::file('photo');
$destinationPath = public_path().'/uploads/';
$filename = $file->getClientOriginalName();
$uploadSuccess = $file->move($destinationPath, $filename);
$user->logo_path = $filename;
}
$object->save();
// Don't forget to save it using a save function, otherwise your hard work will be for nothing
// $object : use your object like user, car, ...

How to delete uploaded files with Codeigniter?

I used the Codeigniter's Upload Class to upload images to a folder in the project. In the database I only store the the url generated after upload the image, so when I want to delete a row in the db I also need to delete the image. How can I do it in codeigniter?
I will be grateful for your answers.
You can delete all the files in a given path, for example in the uploads folder, using this deleteFiles() function which could be in one of your models:
$path = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
function deleteFiles($path){
$files = glob($path.'*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
//echo $file.'file deleted';
}
}
delete_row_from_db(); unlink('/path/to/file');
/path/to/file must be real path.
For eg :
if your folder is like this htp://example.com/uploads
$path = realpath(APPPATH . '../uploads');
APPPATH = path to the application folder.
Its working...
if(isset($_FILES['image']) && $_FILES['image']['name'] != '')
{
$config['upload_path'] = './upload/image';
$config['allowed_types'] = 'jpeg|jpg|png';
$config['file_name'] = base64_encode("" . mt_rand());
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg', 'We had an error trying. Unable upload image');
}
else
{
$image_data = $this->upload->data();
#unlink("./upload/image/".$_POST['prev_image']);
$testData['image'] = $image_data['file_name'];
}
}
$m_img_real= $_SERVER['DOCUMENT_ROOT'].'/images/shop/real_images/'.$data['settings']->shop_now;
$m_img_thumbs = $_SERVER['DOCUMENT_ROOT'].'/images/shop/thumbs/'.$data['settings']->shop_now;
if (file_exists($m_img_real) && file_exists($m_img_thumbs))
{
unlink($m_img_real);
unlink($m_img_thumbs);
}
View:
<input type="file" name="new_file" data-required="1" class="" />
<input type="hidden" name="old_file" value="echo your old file name"/>
<input type="submit" name="submit"/>
Controller:
function edit_image() {
if(isset($_FILES['new_file']['name']) && $_FILES['new_file']['name'] != '') {
move_uploaded_file($_FILES['new_file']['tmp_name'],'./public_html/banner/'.$_FILES['new_file']['name']);
$upload = $_FILES['new_file']['name'];
$name = $post['old_file'];
#unlink("./public_html/banner/".$name);
}
else {
$upload = $post['old_file'];
}
}
Try using delete_files('path') function offered by CI framework itself:
https://ellislab.com/codeigniter/user-guide/helpers/file_helper.html
$image_data = $this->upload->data();
unlink($image_data['full_path']);
This line $this->upload->data() will return many information about uploaded file. You can print information and work accordingly.

PHP fileupload: keep both files if same name

is there any pretty solution in PHP which allows me to expand filename with an auto-increment number if the filename already exists? I dont want to rename the uploaded files in some unreadable stuff. So i thought it would be nice like this: (all image files are allowed.)
Cover.png
Cover (1).png
Cover (2).png
…
First, let's separate extension and filename:
$file=pathinfo(<your file>);
For easier file check and appending, save filename into new variable:
$filename=$file['filename'];
Then, let's check if file already exists and save new filename until it doesn't:
$i=1;
while(file_exists($filename.".".$file['extension'])){
$filename=$file['filename']." ($i)";
$i++;
}
Here you go, you have a original file with your <append something> that doesn't exist yet.
EDIT:
Added auto increment number.
Got it:
if (preg_match('/(^.*?)+(?:\((\d+)\))?(\.(?:\w){0,3}$)/si', $FILE_NAME, $regs)) {
$filename = $regs[1];
$copies = (int)$regs[2];
$fileext = $regs[3];
$fullfile = $FILE_DIRECTORY.$FILE_NAME;
while(file_exists($fullfile) && !is_dir($fullfile))
{
$copies = $copies+1;
$FILE_NAME = $filename."(".$copies.")".$fileext;
$fullfile = $FILE_DIRECTORY.$FILE_NAME;
}
}
return $FILE_NAME;
You can use this function below to get unique name for uploading
function get_unique_file_name($path, $filename) {
$file_parts = explode(".", $filename);
$ext = array_pop($file_parts);
$name = implode(".", $file_parts);
$i = 1;
while (file_exists($path . $filename)) {
$filename = $name . '-' . ($i++) . '.' . $ext;
}
return $filename;
}
Use that function as
$path = __DIR__ . '/tmp/';
$fileInput = 'userfile';
$filename = $path .
get_unique_file_name($path, basename($_FILES[$fileInput]['name']));
if (move_uploaded_file($_FILES[$fileInput]['tmp_name'], $filename)) {
return $filename;
}
You can get working script here at github page
Use file_exists() function and rename() function to achieve what you're trying to do!

Categories