PHP文件上傳
1、upload.php
2、uploadProcess.php
3、封裝:
<?php
class Upload{
public $upload_name; //上傳文件名
public $upload_tmp_path; //上傳文件保存到服務器的temp路徑
public $file_size;
public $file_type;
public $file_save_path;
function __construct(){
$this->upload_name=$_FILES['myfile']['name'];
$this->upload_tmp_path=$_FILES['myfile']['tmp_name'];
$this->file_size=$_FILES['myfile']['size'];
$this->file_type=$_FILES['myfile']['type'];
$this->allow_file_type = array('jpeg','jpg','png','gif','bmp','doc','zip','rar','txt','wps','xlsx','ppt');
$this->file_save_path=$_SERVER['DOCUMENT_ROOT']."/file/up/";
}
public function upload_file($username){
//判斷文件大小
if($this->file_size>2*1024*1024){
echo "<script type='text/javascript'>window.alert('文件不能大於2M')</script>";
exit();
}
//獲取文件類型
/* if($this->file_type!="image/jpeg" && $this->file_type!="image/pjpeg"){
echo "文件類型只能是 jpg 格式";
exit();
}
*/ //獲取文件的擴展名
$file_type=$this->getFileExt($this->upload_name);
if(!in_array($file_type,$this->allow_file_type)){
echo "上傳文件類型格式錯誤";
exit();
}
//判斷上傳是否OK
if(is_uploaded_file($this->upload_tmp_path)){
//防止圖片覆蓋問題,為每個用戶建立一個文件夾
$user_path=$this->file_save_path.$username;
if(!file_exists($user_path)){
mkdir ($user_path);
}
//$move_to_file=$user_path."/".$_FILES['myfile']['name'];
//防止用戶上傳用戶名相同的問題
//$file_true_name=$_FILES['myfile']['name'];
$move_to_file=$user_path."/".time().rand(1,1000).substr($this->upload_name,strripos($this->upload_name,"."));
//echo $upload_file.$move_to_file;
//中文要轉碼
if(move_uploaded_file($this->upload_tmp_path,iconv("utf-8","gb2312","$move_to_file"))){
echo $this->upload_name."上傳成功";
}else{
echo "上傳失敗";
}
}else{
echo "上傳失敗";
}
}
//獲取文件的擴展名
public function getFileExt($filename){
$fileExt=pathinfo($filename);
return $fileExt["extension"];
}
}
?>