<?php
session_start();
$upload_file=$_FILES['file'];
$username=$_POST['username'];
//print_r($upload_file);
$cls_uploadFile=new cls_upload_file($username);
$cls_uploadFile->upload_file($upload_file);
class cls_upload_file{
private $upload_dir;
private $accept_fileType;
private $max_fileSize;
private $root_Dir;
const default_root_path = "../upload/tmp/";
//設定提示消息
static function feed_Msg($msg_code){
$msgs=array(
'F000'=>'Success',
'F100'=>'File Exist',
'F200'=>'Patch Create Failed',
'F300'=>'File Upload Wrong'
);
return $msgs[$msg_code];
}
//初始化構造函數,如果沒有值則給預設路徑
public function __construct($folder = "tmp1") {
//defalut file in tmp folder
if (trim($folder) == ""){
$folder = self::default_root_path."tmp1";
}else{
$folder=self::default_root_path.$folder;
}
$this->upload_dir = $folder;
//上傳檔案入口
public function upload_file($file){
$f_Name = $file['name'];
$f_tmpName = $file['tmp_name'];
$f_Size = $file['size'];
$f_Error = $file['error'];
$f_Type = $this->get_fileType($f_Name);
if($f_Error!=0){
echo self::feed_Msg('F300');
return false;
$dir = $this->upload_dir; //取得上傳檔案夾路徑
//檢測是否存在路徑傳回路徑,不存在建立 傳回路徑
$target_dir = $this->checkDir_exist($dir);
if($target_dir<0){
echo self::feed_Msg('F200');
//拼接目标檔案
$target_file=$target_dir."/".$f_Name;
//檢查檔案是否存在,不存在則傳回檔案名,反之傳回-1
$target_file=$this->check_file_exist($target_file);
//檔案存在 退出傳回
if ($target_file<0){
echo self::feed_Msg('F100');
//移動臨時檔案到指定檔案
move_uploaded_file($f_tmpName, $target_file);
echo self::feed_Msg('F000');
//$_SESSION['fname']="prefix-".md5($file['name']);
//echo "<br />";
//echo "FileName :".$_SESSION['fname'];
// echo json_encode("uploaded");
// header("Location: ../upload.php?name=fasdf");
//檢查檔案是否存在
private function check_file_exist($file){
if(!file_exists($file)){
return $file;
return -1;
private function check_file_size($file){
private function move_file($file,$new_location){
//擷取檔案類型
private function get_fileType($fileName){
$ftype= pathinfo($fileName, PATHINFO_EXTENSION);
return $ftype;
//檢測檔案夾是否存在,不存在建立,存在傳回路徑,建立失敗傳回-1
private function checkDir_exist($dir){
if(is_dir($dir)){
return $dir;
if(!mkdir($dir)){
return -1;
}
private function addFile_to_db(){
public function set_max_FileSize($size = -1){
$this->max_fileSize = $size;
public function set_accept_FileType($type = -1){
$this->accept_fileType = $type;
public function set_root_FolderDir($rootDir = -1){
$this->root_Dir = $rootDir;
}