Skip to content

Instantly share code, notes, and snippets.

@goFrendiAsgard
Created October 2, 2012 04:02
Show Gist options
  • Save goFrendiAsgard/3816091 to your computer and use it in GitHub Desktop.
Save goFrendiAsgard/3816091 to your computer and use it in GitHub Desktop.
No-CMS upload file technique to avoid duplicate file name
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// you can also extends CI_Controller for normal CodeIgniter code
class Register extends CMS_Controller{
// this is the upload path
$upload_path = BASEPATH.'../modules/ssc/assets/upload/';
// this is how to use it
public function upload(){
$file = $_FILES['user_file'];
$tmp_name = $file['tmp_name'];
$original_name = $file['name'];
$prefix = 'document';
$new_name = $this->upload_file($tmp_name, $original_name, $prefix);
// $new_name will be something like 'document_20120809201007_Ac8u_something.jpg
}
private function rand_string( $length ){
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen( $chars );
$str = '';
for( $i = 0; $i < $length; $i++ ){
$str .= $chars[ rand( 0, $size - 1 ) ];
}
return $str;
}
private function upload_file($tmp_file_name, $original_file_name, $prefix){
// check upload path
$upload_path = $this->upload_path;
if(!file_exists($upload_path)){
mkdir($team_directory);
}
if(!is_writable($upload_path)){
chmod($upload_path, 0777);
}
$time_stamp = date('YmdHis');
$new_file_name = $prefix.'_'.$time_stamp.'_'.$this->rand_string(4).
'_'.$original_file_name;
move_uploaded_file($tmp_file_name, $upload_path.$new_file_name);
return $new_file_name;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment