[FREE] Secure image upload script

Discussion in 'PHP' started by Vincent94, Dec 11, 2021.

  1. #1
    Hi there!

    I'm here to post a free secure upload script in PHP. The script checks the mimetype of a uploaded file to make sure the extension is not manipulated and to NOT upload harm files.

    Below is the script:

    class.upload.php:

    
    <?php
    namespace main;
    
    
    class Upload
    {
    
        public static $protectFiles_MimeCheck = array('application/x-httpd-php', 'application/rtf', 'application/x-sh', 'text/plain', 'application/xhtml+xml', 'text/html', 'application/java-archive', 'text/javascript');
        public static $accepted_mime = array('image/jpeg', 'image/png', 'image/gif', 'image/jpeg');
        public static $accepted_files = array('jpg', 'png', 'gif', 'jpeg');
        public static $upload_location = "uploads/";
    
    
        public function _uploadSecure($file)
        {
            $fileName = basename($_FILES["$file"]['name']);
            $ext = explode('.', basename($_FILES["$file"]['name']));
            $file_extension = end($ext);
            $name = preg_replace("/\.[^.]+$/", "", $fileName);
    
            //new information
            $hash = md5($name);
            $name = "$hash.$file_extension";
    
            $targetFilePath = self::$secure_location . $name;
            $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
    
    
            if(in_array($_FILES["$file"]['type'], self::$protectFiles_MimeCheck))
            {
                return "hack_attempt";
                exit();
            }
    
    
            if(in_array($fileType, self::$accepted_files) && !in_array($_FILES["$file"]['type'], self::$protectFiles_MimeCheck))
            {
                if(move_uploaded_file($_FILES["$file"]["tmp_name"], $targetFilePath))
                {
                    return $name;
                }
                else
                {
                    return "failed";
                }
            }
            else
            {
                return "failed";
            }
        }
    }
    
    $Upload = new Upload;
    ?>
    PHP:
    To use the script:

    
    <?php
    
    include_once('class.upload.php');
    
    use main\Upload;
    
    $uploaded_file = (new Upload)->_uploadSecure("file");
    
    PHP:
    The $uploaded_file will return the file name is everything went well..

    In the input field we have to use the name="". The word between the brackets is the $file of the Upload function.
     
    Last edited: Dec 11, 2021
    Vincent94, Dec 11, 2021 IP
    Vooler likes this.