PHP Uploader不会重命名上传

时间:2012-08-22 18:54:00

标签: php apache

我的Dedi服务器上有一个PHP上传器,上传器可以正常工作,只有在上传文件之后才会从临时名称重命名它们。

出现类似

的内容
2b4134a1f559b6da866c9febbc92d709.mp3

上传者file.php

    <?php

class file {

    public $id;
    public $fileName;
    public $systemFilename;
    public $fileType;
    public $fileExtension;
    public $systemUrl;
    public $originalUrl;
    public $thumbPath;
    public $thumbUrl;
    public $canHaveThumb;
    public $ts;
    public $size;
    public $authorized;
    public $knownExtensions;
    public $mimeType;
    public $filePath;

    public function __construct() {
        $this->setKnownExtensions();
    }

    // Check and save a new file on the disk and the database
    public function uploadNewFile($files) {

        $result = array(); // The variable we will send back when we have finished to check and save the file
        $this->setFileName($files['Filedata']['name']);
        if ($this->authorized) {

            // Build the target path
            $siteUrl = F3::get('siteUrl'); // Set in config.php
            $uploadFolder = F3::get('uploadFolder'); // Set in config.php
            $uploadUrl = $_SERVER['DOCUMENT_ROOT'] . '/' . $uploadFolder . '/';

            // Get the temporary file
            $tempFile = $_FILES['Filedata']['tmp_name'];

            // Get a unique system name
            $rand = rand(1, 414342);
            $ts = time();
            $systemName = md5($rand . $ts);

            $this->systemFilename = $systemName . '.' . $this->fileExtension;
            $this->ts = $ts;

            // Clean the path
            $targetFile = str_replace('//', '/', $uploadUrl) . $this->systemFilename;
            // Save the file on the disk
            move_uploaded_file($tempFile, $targetFile);

            // Save the file in the database
            DB::sql('INSERT INTO hm_files (fileName, systemFilename, fileType, time) VALUES ("' . $this->fileName . '", "' . $this->systemFilename . '", "' . $this->fileType . '", ' . $this->ts . ')');
            $this->id = F3::get('DB->pdo')->lastInsertId();

            // Retrieve the template for the file list
            $result['tableRow'] = $this->getTableRow();

            // We create a thumbnail if it is a simple image
            $this->createThumb();
        }

        $result['file'] = $this;
        return $result;
    }

    public function canHaveThumb() {
        if ($this->fileType == 'image') {

            $this->canHaveThumb = true;
        } else {
            $this->canHaveThumb = false;
        }
        return $this->canHaveThumb;
    }

    public function createThumb() {
        if ($this->canHaveThumb()) {
            $filePath = $this->getFilePath();
            if (file_exists($filePath)) {
                $thumbPath = site::getThumbsPath();
                $thumb = new image($filePath);
                $thumb->dir($thumbPath);
                $thumb->width(250);
                $thumb->save();
            }
        }
    }

    public function getThumbPath() {
        $thumbFolderPath = site::getThumbsPath();
        $this->thumbPath = $thumbFolderPath . $this->systemFilename;

        if (!file_exists($this->thumbPath)) {
            $this->createThumb();
        }

        return $this->thumbPath;
    }

    public function getThumbUrl() {

        $base = F3::get('BASE');
        $thumbsFolder = F3::get('thumbsFolder');
        $this->thumbUrl = $base . '/' . $thumbsFolder . '/' . $this->systemFilename;

        return $this->thumbUrl;
    }

    // Delete a file
    public function delete() {
        $filePath = $this->getFilePath();
        if (file_exists($filePath)) {
            unlink($filePath); // Remove the file from the hard drive
        }
        if ($this->canHaveThumb()) {
            $thumbPath = $this->getThumbPath();
            if (file_exists($thumbPath)) {

                unlink($thumbPath); // Remove the thumb from the hard drive
            }
        }
        DB::sql('DELETE FROM hm_files WHERE id = ' . $this->id); // Remove from database
    }

    // Set the filename and the file extension
    public function setFileName($fileName) {
        $this->fileName = $fileName;
        $this->fileExtension = strtolower(substr(strrchr($this->fileName, '.'), 1));
        $this->checkExtension();
        $this->getFileType();
    }

    // Check if a file has an authorized extension
    public function checkExtension() {
        $okExtensions = F3::get('okExtensions'); // defined in config.php
        if (in_array($this->fileExtension, $okExtensions)) {
            $this->authorized = true;
        } else {
            $this->authorized = false;
        }
        return $this->authorized;
    }

    // Define the file type (eg: image, video, ...)
    // Not used in this version
    public function getFileType() {
        $ext = $this->fileExtension;
        if (isset($this->knownExtensions[$ext])) {
            $this->fileType = $this->knownExtensions[$ext];
        } else {
            $this->fileType = 'file';
        }
        return $this->fileType;
    }

    public function getFileSize() {
        $this->size = filesize($this->getFilePath());
        return $this->size;
    }

    // Transform the filesize in kilobytes, megabytes, ... and append the unit.
    public function getReadableSize() {
        $bytes = $this->getFileSize();
        $decimals = 2;
        $sz = 'BKMGTP';
        $factor = floor((strlen($bytes) - 1) / 3);
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
    }

    // Get the HTML for the file list
    public function getTableRow() {

        F3::set('file', $this);
        // We check if the file exist before displaying the table row
        if (file_exists($this->getFilePath())) {
            $tableRow = F3::render('views/table_row.php');
            return $tableRow;
        } else {
            return '';
        }
    }

    // Get a file path on the server harddrive
    public function getFilePath() {
        $path = F3::get('rootPath');
        $uploadsFolder = F3::get('uploadFolder');
        $this->filePath = $path . '/' . $uploadsFolder . '/' . $this->systemFilename;
        return $this->filePath;
    }

    public function getSystemUrl() {
        $base = F3::get('BASE');
        $this->systemUrl = $base . '/file/' . $this->systemFilename;
        return $this->systemUrl;
    }

    public function getOriginalUrl() {
        $siteUrl = F3::get('siteUrl');
        $uploadsFolder = F3::get('uploadFolder');

        $this->originalUrl = $siteUrl . '/' . $uploadsFolder . '/' . $this->systemFilename;
        return $this->originalUrl;
    }

    public function getMime() {
        $filePath = $this->getFilePath();
        $finfo = new finfo(FILEINFO_MIME);
        $info = $finfo->file($filePath);
        return $info;
    }

    public function gearUp($queryResult) {
        $this->id = $queryResult['id'];
        $this->fileName = $queryResult['fileName'];
        $this->systemFilename = $queryResult['systemFilename'];
        $this->fileType = $queryResult['fileType'];
        $this->ts = $queryResult['time'];
        $this->getSystemUrl();
        $this->getOriginalUrl();
        return $this;
    }

    // Display a single file
    public static function display($systemFilename) {
        $fileQuery = DB::sql('SELECT * FROM hm_files WHERE systemFilename LIKE "' . $systemFilename . '"');
        if (count($fileQuery) > 0) {
            $file = new file();
            $file->gearUp($fileQuery[0]);
            $mime = $file->getMime();
            header('Content-Disposition: inline; filename="' . $file->fileName . '"');
            header('Content-type: ' . $mime);
            readfile($file->getOriginalUrl());
        } else {
            return false;
        }
    }

    // Build a zip of files
    // You can create direct download by setting $directDownload on true.
    // Important : we don't use the classic ZipArchive class of PHP. When we zip large files it produces errors.
    // We use the pclzip class. Doc: http://www.phpconcept.net/pclzip/
    public static function serveZip($idsArray, $token, $directDownload = true) {
        if (count($idsArray) > 0) {
            $rootPath = F3::get('rootPath');
            $zipPath = $rootPath . '/zips/archive-' . $token . '.zip';
            $zipper = new pclzip($zipPath);

            foreach ($idsArray as $id) {
                $file = file::fetch($id);
                $filePath = $file->getFilePath();
                $filesArray = array(
                    array(PCLZIP_ATT_FILE_NAME => $filePath,
                        PCLZIP_ATT_FILE_NEW_FULL_NAME => $file->fileName)
                );
                $zipper->add($filesArray, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_ALL_PATH);
            }


            // We set the cookie to track the end of zipping
            setcookie('multiUp', $token);

            // If this is a direct download we serve the zip in the browser and then destroy the zipfile on the server
            if ($directDownload) {
                $zipContent = file_get_contents($zipPath);
                header('Content-Disposition: attachment; filename="archive.zip"');
                header('Content-type: application/zip');
                echo $zipContent;
                unlink($zipPath);
            }
        }
    }

    // Get info for a single file
    public static function fetch($id) {
        $fileQuery = DB::sql('SELECT * FROM hm_files WHERE id = ' . $id);
        if (count($fileQuery) > 0) {
            $file = new file();
            $file->gearUp($fileQuery[0]);

            return $file;
        } else {
            return false;
        }
    }

    // Fetch all files in the database
    public static function fetchAll() {
        $files = array();
        $filesId = DB::sql('SELECT id FROM hm_files ORDER BY time DESC');
        foreach ($filesId as $fileId) {
            $file = file::fetch($fileId['id']);
            if ($file) {
                $files[] = $file;
            }
        }
        return $files;
    }

    // Creates families for file extensions
    // Not used in this version. Might be usefull to create icons
    private function setKnownExtensions() {
        $fileTypes = array();

        // DOCUMENTS
        $fileTypes['pdf'] = 'pdf';

        // PLAIN TEXT
        $fileTypes['txt'] = 'text';
        $fileTypes['rtf'] = 'text';
        $fileTypes['as'] = 'text';
        $fileTypes['xml'] = 'text';
        $fileTypes['html'] = 'text';
        $fileTypes['htm'] = 'text';
        $fileTypes['js'] = 'text';
        $fileTypes['php'] = 'text';
        $fileTypes['asp'] = 'text';
        $fileTypes['py'] = 'text';
        $fileTypes['sql'] = 'text';
        $fileTypes['css'] = 'text';

        // ARCHIVES
        $fileTypes['zip'] = 'archive';
        $fileTypes['rar'] = 'archive';
        $fileTypes['7zip'] = 'archive';
        $fileTypes['gzip'] = 'archive';
        $fileTypes['gz'] = 'archive';
        $fileTypes['tgz'] = 'archive';
        $fileTypes['ace'] = 'archive';
        $fileTypes['arc'] = 'archive';

        // EXCEL
        $fileTypes['xls'] = 'excel';
        $fileTypes['xlsx'] = 'excel';
        $fileTypes['xlsm'] = 'excel';
        $fileTypes['ods'] = 'excel';
        $fileTypes['ots'] = 'excel';
        $fileTypes['csv'] = 'excel';
        $fileTypes['numbers'] = 'excel';

        // WORD
        $fileTypes['doc'] = 'word';
        $fileTypes['docx'] = 'word';
        $fileTypes['odt'] = 'word';
        $fileTypes['ott'] = 'word';
        $fileTypes['pages'] = 'word';

        // POWERPOINT
        $fileTypes['ppt'] = 'powerpoint';
        $fileTypes['pptx'] = 'powerpoint';
        $fileTypes['odp'] = 'powerpoint';
        $fileTypes['otp'] = 'powerpoint';
        $fileTypes['key'] = 'powerpoint';

        // IMAGES
        $fileTypes['png'] = 'image';

        $fileTypes['gif'] = 'image';
        $fileTypes['jpg'] = 'image';
        $fileTypes['jpeg'] = 'image';


        // UNCOMMON IMAGEs
        $fileTypes['svg'] = 'rareimage';
        $fileTypes['svgz'] = 'rareimage';
        $fileTypes['jpf'] = 'rareimage';
        $fileTypes['bmp'] = 'rareimage';
        $fileTypes['eps'] = 'rareimage';
        $fileTypes['tif'] = 'rareimage';
        $fileTypes['tiff'] = 'rareimage';
        $fileTypes['raw'] = 'rareimage';
        $fileTypes['pbm'] = 'rareimage';
        $fileTypes['tga'] = 'rareimage';
        $fileTypes['cdr'] = 'rareimage';



        // "WORKING" IMAGES
        $fileTypes['psd'] = 'photoshop';
        $fileTypes['psb'] = 'photoshop';

        $fileTypes['ai'] = 'illustrator';
        $fileTypes['ait'] = 'illustrator';
        $fileTypes['fxg'] = 'illustrator';
        $fileTypes['cgm'] = 'illustrator';

        $fileTypes['indd'] = 'indesign';
        $fileTypes['idml'] = 'indesign';

        $fileTypes['fla'] = 'flash';
        $fileTypes['swf'] = 'flash';
        $fileTypes['xfl'] = 'flash';

        $fileTypes['prproj'] = 'premiere';

        $fileTypes['aep'] = 'aftereffect';

        // 3D
        $fileTypes['3ds'] = '3d';
        $fileTypes['dwg'] = '3d';
        $fileTypes['dxf'] = '3d';
        $fileTypes['max'] = '3d';

        // SOUND / MUSIC
        $fileTypes['mp3'] = 'music';
        $fileTypes['wav'] = 'music';
        $fileTypes['flac'] = 'music';
        $fileTypes['aac'] = 'music';
        $fileTypes['aiff'] = 'music';
        $fileTypes['aif'] = 'music';
        $fileTypes['aifc'] = 'music';
        $fileTypes['wma'] = 'music';
        $fileTypes['au'] = 'music';
        $fileTypes['snd'] = 'music';
        $fileTypes['aa3'] = 'music';
        $fileTypes['oma'] = 'music';
        $fileTypes['at3'] = 'music';
        $fileTypes['m3u'] = 'music';
        $fileTypes['amr'] = 'music';
        $fileTypes['cda'] = 'music';

        //VIDEO
        $fileTypes['avi'] = 'video';
        $fileTypes['flv'] = 'video';
        $fileTypes['m4v'] = 'video';
        $fileTypes['mkv'] = 'video';
        $fileTypes['mov'] = 'video';
        $fileTypes['mpeg'] = 'video';
        $fileTypes['mpg'] = 'video';
        $fileTypes['mpe'] = 'video';
        $fileTypes['mp4'] = 'video';
        $fileTypes['3gp'] = 'video';
        $fileTypes['aep'] = 'video';

        $this->knownExtensions = $fileTypes;
    }

}

?>

它在具有CPanel的托管服务器上运行良好,这就是为什么我怀疑我的PHP.ini文件? (我自己安装了服务器)

如果是.ini文件,我应该寻找什么?

1 个答案:

答案 0 :(得分:1)

脚本会故意更改文件名,以确保它们始终是唯一的。如果有人上传具有相同文件名的文件,这可以防止文件被覆盖。如果您确实要保留原始名称,可以更改此行:

  $targetFile = str_replace('//', '/', $uploadUrl) . $this->systemFilename;

到此:

$targetFile = str_replace('//', '/', $uploadUrl) . $this->fileName;

请注意,虽然脚本为每个上传的文件指定了唯一的名称,但它仍然在数据库表中保留原始名称,如下所示:

 DB::sql('INSERT INTO hm_files (fileName, systemFilename, fileType, time) VALUES ("' . $this->fileName . '", "' . $this->systemFilename . '", "' . $this->fileType . '", ' . $this->ts . ')');