php檔案上傳


使用php上傳檔案的簡單紀錄,順便留一下自己以前用的class。

首先是基本的html設定,使用上傳時html的form需要加上enctype的設定,file如果需要複選多個檔案的話需要加上multiple。

<form method="post" enctype="multipart/form-data" action="upload.php">
  <!--單檔案-->
  <input type="file" name="upfile">
  <!--可選擇多檔案-->
  <input type="file" name="multfile[]" multiple>
  <input type="submit" value="上傳">
</form>

php的部分則可以利用$_FILES取得上傳的資料,資料欄位如下。

//假設name為upfile
echo $_FILES['upfile']['name'];//印出上傳檔案名稱

//欄位
[name] => "上傳檔案原始名稱"
[type] => image/jpeg //檔案類型
[tmp_name] => /tmp/php/php6hst32 //暫存檔案位置
[error] => UPLOAD_ERR_OK //狀態 可用來檢查上傳是否成功(UPLOAD_ERR_OK) 
[size] => 12345 //大小

多檔案的話資料則會像這樣

echo $_FILES['upfile']['name'][0];
////////
[name] => Array
	(
		[file1] => File
		[file2] => File2
	)
	...

其他的上傳狀態[error]可以從這邊查
https://www.php.net/manual/en/features.file-upload.errors.php


下方簡單紀錄一下以前寫的class,把自己常用的功能組一組的東西。

class File_up
{
	private function randomstr($len=8){
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$charactersLength = strlen($characters);
		$randomString = '';
		for ($i = 0; $i <= $len; $i++) {
			$randomString .= $characters[rand(0, $charactersLength - 1)];
		}
		return $randomString;
	}
	private function RemoveSpecialChar($str){
		$res = str_ireplace(
				array( '\'', '"', ',', ';', '<', '>'
					  , ' ', ' ', '+', '\\', '\/', ':', '*'
					  , '?', '|')
				, '', $str);

		return $res;
	}
  //單檔案用 $_FILE 可通過副檔名 檔案最大限制 儲存位置 檔名加入額外字串
	public function d_file_up($fileData, $setPassExtArr, $fileLimit, $RootDir, $exfilefoot=""){
		
		if(!is_dir($RootDir)){
			mkdir($RootDir, 0755);
		}
		
		$f_name = $fileData["name"];
		$f_size = $fileData["size"];
		$f_tmp = $fileData["tmp_name"];
		$r_file_name = "";
		$passExt = array("pdf", "doc", "docx", "csv", "xls", "xlsx", "ppt", "pptx", "jpg", "jpeg", "png", "gif");
		if(count($setPassExtArr) > 0){
			$passExt = $setPassExtArr;
		}
		if($exfilefoot=='random'){
			$exfilefoot = $this->randomstr(8);
		}
		
		if(is_uploaded_file($f_tmp)){//判斷暫存檔是否存在
			if($f_size < $fileLimit){//檔案大小限制
				//附檔名
				$path_parts = pathinfo($f_name);
				$extension = strtolower($path_parts['extension']);
				$filename = $this->RemoveSpecialChar($path_parts['filename']);
				$ispass = false;
				foreach($passExt as $val){
					if($val == $extension){
						$ispass = true;
					}
				}
				
				if($ispass){
					$savename = $filename.$exfilefoot. "." . $extension;
					$tempi = 1;
					While(is_file($RootDir."/".$savename)){
						$savename = $filename.$exfilefoot . "(" . $tempi . ")" . "." . $extension;
						$tempi++;
					}
					$r_file_name = $savename;
					move_uploaded_file($f_tmp , $RootDir."/".$savename);
				}
			}
		}
		return $r_file_name;
	}
	//多檔案用 $_FILE 可通過副檔名 檔案最大限制 儲存位置 檔名加入額外字串 額外文字
	public function d_file_up_array($fileData, $setPassExtArr, $fileLimit, $RootDir, $exfilefoot="", &$remarkarr = array()){
		
		if(!is_dir($RootDir)){
			mkdir($RootDir, 0755);
		}
		
		$r_file_name = array();
		$tmp_remark = array();
		$file_count = count($fileData["name"]);
		if($exfilefoot=='random'){
			$exfilefoot = $this->randomstr(8);
		}
		echo $file_count;
		for($i=0; $i<$file_count; $i++){
			$f_name = $fileData["name"][$i];
			$f_size = $fileData["size"][$i];
			$f_tmp = $fileData["tmp_name"][$i];
			
			$passExt = array("pdf", "doc", "docx", "csv", "xls", "xlsx", "ppt", "pptx", "jpg", "jpeg", "png", "gif");
			if(count($setPassExtArr) > 0){
				$passExt = $setPassExtArr;
			}
			
			if(is_uploaded_file($f_tmp)){//判斷暫存檔是否存在
				if($f_size < $fileLimit){//檔案大小限制
					//附檔名
					$path_parts = pathinfo($f_name);
					$extension = strtolower($path_parts['extension']);
					$filename = $this->RemoveSpecialChar($path_parts['filename']);
					$ispass = false;
					foreach($passExt as $val){
						if($val == $extension){
							$ispass = true;
						}
					}
					
					if($ispass){
						$savename = $filename.$exfilefoot. "." . $extension;
						$tempi = 1;
						While(is_file($RootDir."/".$savename)){
							$savename = $filename.$exfilefoot . "(" . $tempi . ")" . "." . $extension;
							$tempi++;
						}
						array_push($r_file_name, $savename);
						move_uploaded_file($f_tmp , $RootDir."/".$savename);
						if(isset($remarkarr[$i])){
							array_push($tmp_remark, $remarkarr[$i]);
						}else{
							array_push($tmp_remark, null);
						}
					}
				}
			}
		}
		$remarkarr = $tmp_remark;
		return $r_file_name;
	}
}
Tags : php