文件上傳

用戶(hù)頁(yè)面

<html>
<head>
<meta charset="utf-8">
<title>文件/圖片上傳</title>
</head>
<body>

<form action="upload_file.php" method="post" enctype="multipart/form-data">
    <label for="file">文&nbsp&nbsp&nbsp&nbsp件:</label>
    <input type="file" name="file" id="file"><br>
    <label for="new_name">命名為:</label>
    <input type="text" name="new_name" id="new_name"><br>
    注意:重命名不會(huì)修改文件后綴,如果不想重命名可以不填。<br>
    <input type="submit" name="submit" value="提交">
</form>

</body>
</html>

上傳文件的類(lèi)

<?php
/*
**這個(gè)類(lèi)是這次留的作業(yè)內(nèi)容,要求是最遲在周六培訓(xùn)過(guò)后,新人全部了解mysql的基本操作之后,依靠數(shù)據(jù)庫(kù)完成以下所有方法并實(shí)現(xiàn)一個(gè)上傳文件的功能
**所有對(duì)應(yīng)的數(shù)據(jù)庫(kù)操作務(wù)必使用PDO或mysqli來(lái)實(shí)現(xiàn)
**mysqli鼓勵(lì)使用面向?qū)ο蟮哪J?,而非面向過(guò)程
**成員變量和成員方法都可以在我提供的基礎(chǔ)上增加新的,可能只完善我寫(xiě)的這些未必能實(shí)現(xiàn)功能
**可以當(dāng)場(chǎng)質(zhì)疑我一些變量或函數(shù)的必要性和合理性
**上傳的表單已經(jīng)提供給你,你只需要完善這個(gè)類(lèi)即可
**測(cè)試過(guò)程詳見(jiàn)upload_file.php
**至于上傳文件的原生寫(xiě)法,推薦自學(xué)教程:http://www.runoob.com/php/php-file-upload.html
*/
class Upload{
    //以下函數(shù)可以增加,成員變量可以自由增刪,我只是給出了一個(gè)比較可行的例子,只要你寫(xiě)的類(lèi)能根據(jù)upload_file.php的邏輯實(shí)現(xiàn)文件的上傳就行了
    var $realFile;//這是保存文件的變量,提示,它可以直接由php提供的$_FILES變量賦值
    var $name;//上傳文件名
    var $size;//文件大小
    var $type; //文件類(lèi)型
    var $cookie;
    static $maxSize = 20480000;//最大尺寸10000kb
    //允許的上傳文件類(lèi)型,實(shí)際上應(yīng)該從數(shù)據(jù)庫(kù)中讀取,這里寫(xiě)死,請(qǐng)改用數(shù)據(jù)庫(kù)
    static $files_types = array();
    static $pictures_types = array();
    public function __construct($realFile, $name, $size, $type) {
        $this->realFile = $realFile;
        $this->name = $name;
        $this->size = $size;
        $this->type;
    }

    private static function get_permit_types()
    {
        $mysqli = new mysqli('localhost', 'root','', 'upload');
        if (!$mysqli)
        {
            die("Connection Failed " . $mysqli->connect_error);
        }
        $res1 = $mysqli->query('select allow_types from filetypes');
        $res2 = $mysqli->query('select pic_allow_types from pictypes');
        $i = 0;
        while($row = $res1->fetch_array(MYSQLI_ASSOC))
        {
            self::$files_types[$i++] = $row['allow_types'];
        }
        while($row = $res2->fetch_array(MYSQLI_ASSOC))
        {
            self::$pictures_types[$i++] = $row['pic_allow_types'];
        }
        if(isset(self::$files_types) and isset(self::$pictures_types))
        {
            $res1->free();
            $res2->free();
            $mysqli->close();
            return true;
        }
        else
        {
            $res1->free();
            $res2->free();
            $mysqli->close();
            return false;
        }
    }

    public function add_type(){
        $mysqli = new mysqli('localhost', 'root','', 'upload');
        if (!$mysqli)
        {
            die("Connection Failed " . $mysqli->connect_error);
        }

        $sql1 = "insert into filetypes(allow_types) VALUES ('')";
        $sql2 = "insert into pictypes(pic_allow_types) VALUES ('')";

        if($mysqli->query($sql1) or $mysqli->query($sql2))
        {
            $mysqli->close();
            return true;
        }
        else
        {
            $mysqli->close();
            return false;
        }
    }

    public function delete_type(){
        //刪除可上傳類(lèi)型的函數(shù),原則上從數(shù)據(jù)庫(kù)中刪除這一條
        //返回值,成功返回true,失敗返回false即可
        $mysqli = new mysqli('localhost', 'root','', 'upload');
        $sql1 = "delete from filetypes where allow_types =''";
        $sql2 = "delete from pictypes where pic_allow_types =''";
        if($mysqli->query($sql1) or $mysqli->query($sql2))
        {
            $mysqli->close();
            return true;
        }
        else
        {
            $mysqli->close();
            return false;
        }
    }

    public function upload(){
        //對(duì)當(dāng)前對(duì)象執(zhí)行上傳的操作,提示:上傳后文件的信息至少應(yīng)當(dāng)存在數(shù)據(jù)庫(kù)的某個(gè)表中,要求圖片和其他類(lèi)型的文件能被分類(lèi)到files和pictures兩個(gè)目錄中,命名格式自行發(fā)揮
        //返回值要求上傳失敗返回false即可,上傳成功可以返回一個(gè)文件存儲(chǔ)信息的json
        $mysqli = new mysqli('localhost', 'root','', 'upload');
        if (!$mysqli)
        {
            die("Connection Failed " . $mysqli->connect_error);
        }

        if ($this->realFile["error"] > 0)
        {
            echo "錯(cuò)誤: " . $this->realFile["error"] . "<br>";
            return false;
        }
        else {
            self::get_permit_types();
            $temp = explode('.', $this->name);
            $extension = end($temp);
            if(in_array($extension, self::$files_types))
            {
                move_uploaded_file($this->realFile["tmp_name"], "D:/Project/homework/files/" . $this->name);
                $name = $this->name;
                $type = $this->realFile['type'];
                $size = $this->size;
                $path = 'D:/Project/homework/files';
                $sql3 = "insert into files(filename, type, size, path) values('$name', '$type', '$size', '$path')";
                if(!$mysqli->query($sql3))
                {
                    return false;
                }
            }
            if(in_array($extension, self::$pictures_types))
            {
                move_uploaded_file($this->realFile["tmp_name"], "D:/Project/homework/pictures/" . $this->name);
                $name = $this->name;
                $type = $this->realFile['type'];
                $size = $this->size;
                $path = 'D:/Project/homework/pictures';
                $sql3 = "insert into pics(filename, type, size, path) values('$name', '$type', '$size', '$path')";
                if(!$mysqli->query($sql3))
                {
                    return false;
                }
            }
            echo "上傳文件名: " . $this->name . "<br>";
            echo "文件類(lèi)型: " . $this->realFile['type'] . "<br>";
            echo "文件大小: " . $this->size . "<br>";
            echo "文件臨時(shí)存儲(chǔ)目錄: " . $this->realFile['tmp_name'] . "<br>";
            echo "文件所在目錄" . 'D:/Project/homework/pictures/' . $this->name . "<br>";
            $result = array(
                'name' => $this->name,
                'type' => $this->realFile['type'],
                'size' => $this->realFile['size'],
                'temp' => $this->realFile['tmp_name']
            );
            setcookie('upload_file','upload_file', time()+300);
            return json_encode($result);
        }
    }

    public function limit(){
        //上傳限制的方法,主要用于檢測(cè)文件的各項(xiàng)合法(如大小),如果你能考慮到更多安全的因素(不僅是文件類(lèi)型),那么更能體現(xiàn)你的NB,至于
        //返回值默認(rèn)只要合法返回true,不合法返回false,如果想分類(lèi)錯(cuò)誤類(lèi)型,那么請(qǐng)優(yōu)秀的你自行修改我upload_file.php里的邏輯以便更好地報(bào)錯(cuò)
        self::get_permit_types(); // 從數(shù)據(jù)庫(kù)獲取允許的類(lèi)型

        $temp = explode('.', $this->name);
        $extension = end($temp);
        if($this->size > self::$maxSize)
        {
            return false;
        }
        elseif(!in_array($extension, self::$files_types)
                and !in_array($extension, self::$pictures_types))
        {
            return false;
        }
        else
        {
            return true;
        }

    }

    public function user_limit(){
        //對(duì)用戶(hù)上傳的權(quán)限進(jìn)行限制,根據(jù)要求應(yīng)當(dāng)每個(gè)用戶(hù)(你如果覺(jué)得麻煩可以把用戶(hù)的識(shí)別特征寫(xiě)成一個(gè)常量,只要這個(gè)函數(shù)可以正常執(zhí)行就行了)
        //返回值默認(rèn)只要合法返回true,不合法返回false,如果想分類(lèi)錯(cuò)誤類(lèi)型,那么請(qǐng)優(yōu)秀的你自行修改我upload_file.php里的邏輯以便更好地報(bào)錯(cuò)

        if(!isset($_COOKIE['upload_file']))
        {
            return true;
        }
        if(isset($_COOKIE['upload_file']))
        {
            return false;
        }
    }

    public function rename($new_name){
        //修改上傳文件名的方法,傳入name則改名,不傳則不改名
        //改名返回true,未修改返回false
        if($new_name != '')
        {
            $temp = explode('.', $this->realFile['name']);
            $extension = end($temp);
            $this->name = $new_name . '.' . $extension;
            return true;
        }
        if($new_name == '')
        {
            return false;
        }
    }

}

上傳文件的腳本。

<?php
require_once("upload.class.php");

$myFile = new Upload($_FILES['file'],
                     $_FILES['file']['name'],
                     $_FILES['file']['size'],
                     $_FILES['file']['type']);

$myFile->rename($_POST["new_name"]);//嘗試重命名
if($myFile->limit()){
    if($myFile->user_limit()){
        if($result = $myFile->upload()){
            echo "文件上傳成功!" . "<br>";
            echo $result;//由于規(guī)定上傳成功后返回一個(gè)json
        }else{
            echo "文件上傳失??!";
        }
    }else{
        echo "上傳頻率過(guò)快!請(qǐng)5分鐘后再試";
    }
}else{
    echo "文件不合法!";
}

實(shí)際效果

正常上傳
連續(xù)上傳
修改文件名
修改后頁(yè)面
實(shí)際修改效果
數(shù)據(jù)庫(kù)1
數(shù)據(jù)庫(kù)2
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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