文件快傳網站及源碼

@zgcwkj  2019年09月09日

分類:

代碼 網站 

代碼有點粗糙,簡單實現了下!(PHP)

主要是文件上傳和下載的功能實現!

使用到的開源項目:http://github.com/fising/big-file-uploader

源碼鑒賞:

<?php

header('Content-type:text/json'); // 規定返回的內容是Json數據
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $jaonDataName = 'files/data.json';
    // 文件存儲位置
    $filePath = getPath();
    // 從文件中讀取數據到PHP變量
    $json_string = file_get_contents($jaonDataName);
    // 把JSON字符串轉成PHP數組
    $datas = json_decode($json_string, true);
    // 顯示出來看看
    // echo var_dump($datas);
    if (isset($_REQUEST['key'])) {
        foreach ($datas as $key => $value) {
            if (in_array($_REQUEST['key'], $value)) {
                echo json_encode([
                    'status'  => 0,
                    'message' => $value
                ]);
                exit();
            }
        }
        echo json_encode([
            'status'  => 1,
            'message' => '文件不存在'
        ]);
    } else {
        //保存上傳的文件
        $return = saveFile($filePath);
        //文件保存成功
        if ($return['status'] == 0) {
            $name = isset($_POST['name']) ? trim($_POST['name']) : '';
            // 添加新的數據
            array_push($datas, array('key' => $return['key'], 'value' => $filePath . DIRECTORY_SEPARATOR . $return['name']));
            // 把PHP數組轉成JSON字符串
            $json_string = json_encode($datas);
            // 寫入文件
            file_put_contents($jaonDataName, $json_string);
        }
        // 輸出到界面
        echo json_encode($return);
    }
}

/**
 * 獲取存儲的文件目錄
 * @return string
 */
function getPath()
{
    ini_set('date.timezone', 'Asia/Shanghai'); // 設置時區
    $path = 'files' . DIRECTORY_SEPARATOR . date('Ymd', time());
    if (!is_dir($path)) mkdir($path);
    return $path;
}

/**
 * 保存上傳的文件到一個目錄
 *
 * @param string $dir
 * @param string $dest
 * @return array
 */
function saveFile($dir, $dest = '')
{
    $sum = isset($_POST['sum']) ? trim($_POST['sum']) : '';
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $index = isset($_POST['index']) ? intval($_POST['index']) : 0;
    $count = isset($_POST['count']) ? intval($_POST['count']) : 0;

    //禁止上傳文件類型
    if ((strpos($name, '.php') || strpos($name, '.html')) !== false) {
        return array(
            'status' => 1,
            'message'   => '該類型文件禁止上傳'
        );
    }

    if (empty($sum) || empty($name) || $index < 0 || $index >= $count) {
        return array(
            'status' => 1,
            'message'   => false
        );
    }

    if ($_FILES['data']['error'] > 0) {
        return array(
            'status'  => $_FILES['data']['error'],
            'message' => getErrorMessage($_FILES['data']['error'])
        );
    }

    $dest = empty($dest) ? $name : $dest;
    $dest = $dir . DIRECTORY_SEPARATOR . $dest;
    if (file_exists($dest)) {
        return array(
            'status'  => 2,
            'message' => '同名文件已經存在'
        );
    }

    copy($_FILES['data']['tmp_name'], sys_get_temp_dir() . DIRECTORY_SEPARATOR . $sum . '-' . $index);

    if ($index + 1 == $count) {
        $fd = fopen($dest, 'x');
        if (false === $fd && !flock($fd, LOCK_EX)) {
            return array(
                'status'  => 1,
                'message' => '打開文件失敗'
            );
        }

        for ($i = 0; $i < $count; $i++) {
            $tmp = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $sum . '-' . $i;
            fwrite($fd, file_get_contents($tmp));
            unlink($tmp);
        }

        flock($fd, LOCK_UN);
        fclose($fd);
    }

    return array(
        'name'   => $name,
        'key'   => md5_file($dest),
        'status' => 0,
        'message'   => $index + 1 == $count
    );
}

/**
 * 根據錯誤代碼獲取錯誤信息
 *
 * @param int $code
 * @return string
 */
function getErrorMessage($code)
{
    switch ($code) {
        case UPLOAD_ERR_OK:
        case UPLOAD_ERR_FORM_SIZE:
            return '文件塊太大';
            break;
        case UPLOAD_ERR_PARTIAL:
            return '文件沒有完整上傳';
            break;
        case UPLOAD_ERR_NO_FILE:
            return '文件沒有上傳';
            break;
        case UPLOAD_ERR_NO_TMP_DIR:
            return '找不到臨時文件夾';
            break;
        case UPLOAD_ERR_CANT_WRITE:
            return '文件寫入失敗';
            break;
        default:
            return '未知錯誤';
            break;
    }
}

源碼下載:

內容已隱藏,需要評論並且審核通過後,才能閱讀隱藏內容
  • Github:PHP_FileUpload
  • 使用說明:

    這個源碼,沒有使用數據庫。使用的是 json 文件實現,注意改文件名稱防止被直接下載!


    評論已關閉

    1. 阿文

      可以下載試一下嘛

    2. 最近也是看到這個項目,好不容易找到一個模板,來瞅瞅看一下你寫的例子。感謝

    3. 判斷文件名後綴貌似不靠譜

      1. @蘇生

        等我有空再優化優化吧,PHP的源碼好像有問題~

    4. 從v2過來的,不錯,試下

    5. 感謝分享,很牛逼的源碼。這種網站還是有用處的,不過我一般用的話就用火狐那個。

    6. 不錯

    Top