摘要:<?php<form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="Myfile"> &nbs
<?php
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="Myfile">
<input type="submit" value="上傳">
</form>
/**
* 文件下載操作
* $filename 需要下載的文件名
*/
function dow_file($filename){
//告訴瀏覽器告訴返回文件的大小
header('Accept-Length:'.filesize($filename));
//告訴瀏覽器,文件作為附件處理,并告訴瀏覽器下載完的文件名
header('Countent-Disposition:attachment;filename=',basename($filename));
//輸出文件
readfile($filename);
}
/**
* $fileInfo 上傳的文件信息
* $uploadPath 上傳的指定目錄
* $allowExt 上傳的文件類型
* $maxSize 上傳文件的最大值(字節(jié))
*/
function upload_file($fileInfo, $uploadPath = './upload', $allowExt['png','jpg','jpeg','gif','txt','html'],$maxSize = 1000000){
//判斷上傳錯誤號
if($fileInfo['error'] === 0){
//獲取文件后綴
$ext = strtolower(pathinfo(fileInfo['name'],PATHINFO_EXTENESION));
//判斷文件類型
if(!in_array($ext, $allowExt)){
return '非法文件類型';
}
//判斷文件大小
if($fileInfo['size'] > $maxSize){
return '超出允許上傳的最大值!';
}
//判斷文件上傳方式
if(!is_uploaded_file($fileInfo['name'])){
return '非法上傳操作';
}
//判斷目錄是否存在,不存在則創(chuàng)建
if(!is_dir($uploadPath)){
mkdir($uploadPath,0777,true);
}
//生成唯一文件名,uniqid生成唯一id,microtime返回當前unix時間戳中的微秒
$uniName = md5(uniqid(microtime(true),true)).'.'.$allowExt;
//拼接路徑以及文件名
$dest = $uploadPath.''.$uniName;
//將文件移動到指定目錄
if(move_uploaded_file($fileInfo['tmp_name'], $dest)){
return '文件上傳失敗';
}
return '文件上傳成功'
}else{
switch ($fileInfo['error']) {
case 1:
$res = '上傳的文件超過了 php.ini 中 upload_max_filesize 選項限制的值!';
break;
case 2:
$res = '上傳文件的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項指定的值。';
break;
case 3:
$res = '文件只有部分被上傳。';
break;
case 4:
$res = '沒有文件被上傳。';
break;
case 6:
$res = '找不到臨時文件夾。';
break;
case 7:
$res = '文件寫入失敗。';
break;
}
return $res;
}
}
$fileinfo = $_FILES['Myfile'];
if($fileinfo){
upload_file($fileinfo);
}
?>
批改老師:韋小寶批改時間:2019-02-23 11:25:24
老師總結(jié):上傳以及下載文件 個人感覺是PHP文件中最作用的兩個 一定要多多練習 而上傳中的判斷只能多不能少 上傳和安全性是密切相關(guān)的