實(shí)例:文件上傳2

2018.09.03
只有一個(gè)文件,代碼如下:

目錄結(jié)構(gòu):

upfile(文件夾)
├─upfile.html ????前端頁(yè)面
├─upfile.php ????后臺(tái)上傳文件

upfile.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <title>文件上傳</title>
    <meta name="description" content=""/>
    <meta name="keywords" content=""/>
</head>

<body>
    <form action="upfile.php" method="post" enctype="multipart/form-data">
        <label>上傳文件:</label>
        <input type="file" name="myfile">
        <br/>
        <input type="submit" value="提交">
    </form>
</body>
</html>

upfile.php:

<?php
//判斷文件上傳錯(cuò)誤
switch($_FILES['myfile']['error']){
    case 1:
        exit('文件超過(guò)php.ini限制');
        break;
    case 2:
        exit('文件超過(guò)html限制');
        break;
    case 3:
        exit('文件只有部分被上傳');
        break;
    case 4:
        exit('沒(méi)有文件被上傳');
        break;
    case 6:
        exit('找不到臨時(shí)文件夾');
        break;
    case 7:
        exit('文件寫入失敗');
        break;
}

//定義允許上傳的文件大小
$maxsize = 1024*1024*2;
if($_FILES['myfile']['size'] > $maxsize){
    exit('文件過(guò)大,不允許上傳!');
}

//定義允許用戶上傳的文件類型
$mine = ['image/jpeg', 'image/jpg', 'image/pjpeg', 'image/png', 'image/gif'];
//判斷用戶上傳的文件類型是否合法
if(!in_array($_FILES['myfile']['type'],$mine)){
    exit('文件類型不合法!');
}

$tmp = $_FILES['myfile']['tmp_name'];

$path = 'e:/wamp64/www/2018/201807/upfiles';
$fileName = getRandName();
//獲取文件的擴(kuò)展名
$ext = pathinfo($_FILES['myfile']['name'], PATHINFO_EXTENSION);
//拼接文件名
$basename = $fileName.'.'.$ext;
//拼接路徑
$dest = $path.'/'.$basename;

//將臨時(shí)文件夾中的文件,移動(dòng)到指定位置
move_uploaded_file($tmp, $dest);

echo '上傳成功,<a href="./upfile.html">返回</a>';

//生成隨機(jī)文件名
function getRandName(){
    $string = date('YmdHis');
    for($i=0; $i<6; $i++){
        switch(mt_rand(0,2)){
            case 0:
                $string .= chr(mt_rand(97,122));
                break;
            case 1:
                $string .= chr(mt_rand(65,90));
                break;
            case 2:
                $string .= mt_rand(0,9);
                break;
        }
    }
    return $string;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容