PHP library

File Upload Class in PHP

Author: Thorpe Lee(koangbok@gmail.com), Front&Back-end Developer, posted on 2015-12-10 03:18:03

Print - 프린트하기


This component simplifies file validation and uploading.

How to Install


using the Composer (http://getcomposer.org/), If you want to get more information about the Composer, visit here("https://xpressengine.github.io/Composer-korean-docs/"), This is Korean site

Create a composer.json file in your project root:

{
    require: {
        cafelatte/uploader: 1.0.0
    }
}

            
How to use

Html Sample


 

PHP Sample

require_once __DIR__ . /vendor/autoload.php;

try {
    $upload = new \Cafelatte\Libraries\Uploader();
    $upload->setUploadPath(./upload/);
    $upload->setPermitedExt(array(jpg,xlsx));
    $upload->setBannedExt();
    $upload->setLimitMaxSize(111121212);
    $upload->setPrefixFolder(m);
    $firstFileName01 = $upload->upload($_FILES[test01]);
    $firstFileName02 = $upload->upload($_FILES[test02]);

    echo $firstFileName01;
    echo --------;
    echo $firstFileName02;

} catch (Exception $ex) {
    echo $ex->getMessage();
}


            
Class Source Code

/**
 * This class allows a user to resize image and validate their files.
 *
 * @author Thorpe Lee 
 * @version 1.0
 * @copyright Copyright (c) 2014, Thorpe Lee
 * @license MIT License
 */
namespace Cafelatte\Libraries;
class Uploader
{
    /**
     * upload file 
     * @var type 
     */
    private $file;
    /**
     * file type infomation uploaded
     * @var type 
     */
    private $fileType;
    /**
     * file Temprary name(binary) infomation uploaded
     * @var type 
     */
    private $fileTmpName;
    /**
     * file size infomation uploaded
     * @var type 
     */
    private $fileSzie;
    /**
     * file error code infomation uploaded
     * @var type 
     */
    private $fileError;
    /**
     * upload folder
     * @var type 
     */
    private $uploadPath;
    /**
     * Dir to store the attached files
     * @param type $uploadPath
     */
    public function __construct()
    {
        
    }
    /**
     * upload validation
     */
    private function inputValidationFile()
    {
        $this->validationFileErrorCode();
        $this->validationExtendion();
        $this->validationPermitedExtendion();
        $this->validationSize();
        $this->validationError();
        $this->setMakeDir();
    }
    /**
     * get a file name
     * @return type
     */
    private function getFileName()
    {
        return $this->fileName = $this->file[name];
    }
    /**
     * get a file type
     * @return type
     */
    private function getFileType()
    {
        return $this->fileType = $this->file[type];
    }
    /**
     * get a binary file in tem dir
     * @return type
     */
    private function getFileTempName()
    {
        return $this->fileTmpName = $this->file[tmp_name];
    }
    /**
     * get a size of uploaded file
     * @return type
     */
    private function getFileSize()
    {
        return $this->fileSzie = $this->file[size];
    }
    /**
     * get a code of uploads result(
     * @return type
     */
    private function getFileError()
    {
        return $this->fileError = $this->file[error];
    }
    /**
     * 
     * @return string
     */
    private function getExtendion()
    {
        switch ($this->getFileType()) {
            case image/jpeg:
                $extend = .jpeg;
                break;
            case image/gif:
                $extend = .gif;
                break;
            case image/png:
                $extend = .png;
                break;
            default:
                $extend = . . strtolower(array_pop(explode(., $this->getFileName())));
                break;
        }
        return $extend;
    }
    /**
     * 
     * @param type $uploadPath
     */
    public function setUploadPath($uploadPath)
    {
        $this->uploadPath = $uploadPath;
    }
    /**
     * 
     * @param array $permitedExt
     */
    public function setPermitedExt(array $permitedExt = array(jpg, jpeg, gif, png, pdf, docs, doc, xlsx, csv, pem, avi, pem))
    {
        $this->permitedExt = $permitedExt;
    }
    /**
     * 
     * @param array $bannedExt
     */
    public function setBannedExt(array $bannedExt = array(php, php4, php5, exe, sh))
    {
        $this->bannedExt = $bannedExt;
    }
    /**
     * 
     * @param type $limitMaxSize
     */
    public function setLimitMaxSize($limitMaxSize = 1048576)
    {
        $this->limitMaxSize = $limitMaxSize;
    }
    /**
     * upload folder Prefix name
     * @param type $case
     */
    public function setPrefixFolder($case = d)
    {
        switch ($case) {
            case y:
                $this->prefixFolder = date(Y) . /;
                break;
            case m:
                $this->prefixFolder = date(Y-m) . /;
                break;
            case d:
                $this->prefixFolder = date(Y-m-d) . /;
                break;
            case h:
                $this->prefixFolder = date(Y-m-d) . / . date(H) . /;
                break;
            case i:
                $this->prefixFolder = date(Y-m-d) . / . date(H-i) . /;
                break;
            default:
                $this->prefixFolder = ;
        }
        return $this->prefixFolder;
    }
    /* --------------------- Validation ------------------------ */
    /**
     * 
     * @throws InvalidArgumentException
     */
    private function validationFileErrorCode()
    {
        if ($this->fileError == UPLOAD_ERR_INI_SIZE) {
            throw new \InvalidArgumentException(Sorry max file size is ( . ini_get(upload_max_filesize) . ));
        } else if ($this->fileError == UPLOAD_ERR_FORM_SIZE) {
            throw new \InvalidArgumentException(Sorry max file size over);
        } else if ($this->fileError == UPLOAD_ERR_PARTIAL) {
            throw new \InvalidArgumentException(a part of file uploaded);
        } else if ($this->fileError == UPLOAD_ERR_NO_FILE) {
            throw new \InvalidArgumentException(This file can not transfort to server);
        }
    }
    /**
     * 
     * @throws InvalidArgumentException
     */
    private function validationExtendion()
    {
        if (!$this->getExtendion()) {
            throw new \InvalidArgumentException(This files extendion is NOT allowed to upload to server);
        }
    }
    /**
     * 
     * @throws InvalidArgumentException
     */
    private function validationSize()
    {
        if ($this->getFileSize() < 0 || $this->getFileSize() > $this->limitMaxSize) {
            throw new \InvalidArgumentException(Sorry max file size is ( . $this->limitMaxSize . bite ));
        }
    }
    /**
     * 
     * @throws InvalidArgumentException
     */
    private function validationError()
    {
        if ($this->getFileError() != 0) {
            throw new \InvalidArgumentException(upload fail);
        }
    }
    /**
     * This method only validate from the filename.
     * 
     * @throws InvalidArgumentException
     */
    private function validationPermitedExtendion()
    {
        $ext = array_pop(explode(., $this->getFileName()));
        $chk = false;
        for ($j = 0; $j < count($this->permitedExt); $j++) {
            if ($ext == $this->permitedExt[$j]) {
                $chk = true;
            }
        }
        for ($i = 0; $i < count($this->bannedExt); $i++) {
            if ($ext == $this->bannedExt[$i]) {
                $chk = false;
            }
        }
        if ($chk == false) {
            throw new \InvalidArgumentException(This files extendion is NOT allowed to upload to server);
        }
    }
    /* -------------------------------------------------- */
    /**
     * excute to upload to server, if the file type is image(jpg,png,gif). GD library is running for security.
     * 
     * @param type $files
     * @return string
     * @throws InvalidArgumentException
     */
    function upload($files)
    {
        $this->file = $files;
        $this->inputValidationFile();
        $saveFileName = $this->uploadPath . $this->prefixFolder . $this->getNewImageName() . $this->getExtendion();
        switch ($this->getFileType()) {
            case image/jpeg:
                $image = imagecreatefromjpeg($this->getFileTempName());
                imagejpeg($image, $saveFileName, 100);
                break;
            case image/gif:
                $image = imagecreatefromgif($this->getFileTempName());
                imagejpeg($image, $saveFileName, 100);
                break;
            case image/png:
                $image = imagecreatefrompng($this->getFileTempName());
                imagejpeg($image, $saveFileName, 100);
                break;
            default :
                if (move_uploaded_file($this->getFileTempName(), $saveFileName) == false) {
                    throw new \InvalidArgumentException(Upload file Fail);
                }
        }
        if (is_file($saveFileName) == false) {
            throw new \InvalidArgumentException(Upload file Fail);
        }
        return $saveFileName;
    }
    /**
     * create a new file name 
     * @return type
     */
    private function getNewImageName()
    {
        return \sha1(\uniqid(\getmypid() . \rand(), true));
    }
    /**
     * filedelete 
     * @param type $url
     * @param type $filename
     * @return boolean
     */
    private function delete($url, $filename)
    {
        if (is_file($url . $filename)) {
            return unlink($url . $filename);
        } else {
            return false;
        }
    }
    /**
     * create the new upload folder if not exist
     * @throws InvalidArgumentException
     */
    private function setMakeDir()
    {
        if (is_dir($this->uploadPath . $this->prefixFolder) == false) {
            if (mkdir($this->uploadPath . $this->prefixFolder, 0755) == false) {
                throw new \InvalidArgumentException(there is no upload directory, Please make this folder ({$this->uploadPath}), Or give the permission (777));
            }
        }
    }
}

            
License


MIT Public License