View difference between Paste ID: uTpYYYyn and 92bYZa6N
SHOW: | | - or go back to the newest paste.
1
<?php
2
3
/**
4
* krs1911@gmail.com
5
*/
6
7
/**
8
* You can add more file inputs by just copying & pase line
9
* <input name='p1' type='file' accept='<?= implode(',', $settings['ext']); ?>' />
10
* remember about changing the field name eg. p2, p3, p4, ...
11
*/
12
13
/* ----------------------------------------------- */
14
/* SETTINGS */
15
/* ----------------------------------------------- */
16
17
$settings = array(
18
    //Maximum file size defined in Bytes. However it depends on what values are set for directives in php.ini: upload_max_filesize, post_max_size and memory_limit
19
    'file_maxsize'  => 5000000, 
20
    
21
    // Accepted extensions
22
    'ext'           => array(
23
        'image/gif'
24
    ),
25
    
26
    // Directory where files should be placed. Note this is relative path, so folder images/ will be serached in the same location as script execution
27
    'dir'           => 'images/',
28
    
29
    'handleUps'             => true, // Upload enabled/disabled -> options: true/false
30
    'createDirIfNoExist'    => true, // Create output directory (specified at 'dir') when doesn't exist. Options true/false
31
    'allowNoFile'           => false // Allow to execute script if no file has been selected for at least one file field. Options true/false
32
);
33
34
/* ----------------------------------------------- */
35
/* NO MORE FURTHER EDITING NEEDED */
36
/* ----------------------------------------------- */
37
38
try
39
{
40
    // Check if file handling on and ifdata has been sent
41
    if ($settings['handleUps'] && array_key_exists('send', $_POST))
42
    {
43
        // yes - proceed
44
        $errors = array();
45
        
46
        // Check if files has been sent without any problems
47
        foreach ($_FILES as $fieldname => $fileprop)
48
        {
49
            // Check file error
50
            if ($fileprop != UPLOAD_ERR_OK)
51
            {
52
                switch ($fileprop['error'])
53
                {
54
                    case UPLOAD_ERR_INI_SIZE:
55
                    case UPLOAD_ERR_FORM_SIZE: 
56
                        $errors[] = 'File '.$fileprop['name'].' is too big (maximum size is '.sizeFormat($settings['file_maxsize'], 'MB').')';
57
                    break;
58
                    case UPLOAD_ERR_PARTIAL:
59
                    case UPLOAD_ERR_NO_TMP_DIR:
60
                    case UPLOAD_ERR_CANT_WRITE:
61
                        $errors[] = 'File '.$fileprop['name'].' wasn\'t succesfully uploaded.';
62
                    break;
63
                    case UPLOAD_ERR_NO_FILE:
64
                        if (!$settings['allowNoFile'])
65
                        {
66
                            $errors[] = 'No file has been selected at field '.$fieldname.'.';
67
                        }
68
                    break;
69
                    case UPLOAD_ERR_EXTENSION:
70
                        $errors[] = 'File '.$fileprop['name'].' extension is not correct.';
71
                    break;
72
                }
73
            }
74
        }
75
        
76
        // If there are errors -> do not proceed
77
        if (!empty($errors))
78
        {
79
            throw new Exception(implode('<br />', $errors));
80
        }
81
        
82
        // Create target directory if not exists and if script allowed to
83-
        if (!file_exists($settings['dir']) && !mkdir($settings['dir'], 0777))
83+
        if (!file_exists($settings['dir']))
84
        {
85-
            throw new Exception('Target directory error.');
85+
            if (!$settings['createDirIfNoExist'])
86
            {
87
                throw new Exception('Target directory does not exists.');
88
            } 
89
            
90
            if (!mkdir($settings['dir'], 0777))
91
            {
92
                throw new Exception('Target directory error.');
93
            }
94
        }
95
        
96
        // Continue with checking size, veryfing extensions and moving files to te proper directory
97
        $filesExt = array();
98
        
99
        foreach ($_FILES as $filename => $fileprop)
100
        {   
101
            try
102
            {
103
                // If file is uploaded one
104
                if (!is_uploaded_file($fileprop['tmp_name']))
105
                {               
106
                    throw new Exception('There was a problem with handling '.$fileprop['name'].' file.');
107
                }
108
                
109
                // Filesize
110
                if ($fileprop['size'] > $settings['file_maxsize'])
111
                {                
112
                    throw new Exception('File '.$fileprop['name'].' is too big (maximum size is '.sizeFormat($settings['file_maxsize']).').');
113
                }
114
                
115
                // Check claimed extension
116
                if (!in_array($fileprop['type'], $settings['ext']))
117
                {
118
                    throw new Exception('File '.$fileprop['name'].' has inapropriate extension.');
119
                }
120
                
121
                // Verify extension
122
                if (class_exists('finfo') && floatval(phpversion()) >= 5.3)
123
                {
124
                    $finfo = finfo_open(FILEINFO_MIME_TYPE);
125
                    $type = finfo_file($finfo, $fileprop['tmp_name']);
126
                }
127
                else if (function_exists('exif_imagetype'))
128
                {                  
129
                    $type = exif_imagetype($fileprop['tmp_name']);
130
                }
131
                else
132
                {    
133
                    $type = $fileprop['type'];
134
                }
135
                
136
                if (!in_array($type, $settings['ext']))
137
                {               
138
                    throw new Exception('File '.$fileprop['name'].' has inappropriate extension.');
139
                }
140
                
141
                // Save ext
142
                $filesExt[$filename] = end(explode('/', $type));
143
            }
144
            catch (Exception $ex)
145
            {
146
                $errors[] = $ex->getMessage();
147
            }
148
        }
149
        
150
        // Save files only if there are no errors
151
        if (!empty($errors))
152
        {
153
            throw new Exception(implode('<br />', $errors));
154
        }
155
        
156
        foreach ($_FILES as $filename => $fileprop)
157
        {
158
            // Move uploaded file
159
            if (!move_uploaded_file($fileprop['tmp_name'], $settings['dir'].time().'.'.$filesExt[$filename]))
160
            {
161
                throw new Exception('File '.$fileprop['name'].' couldn\'t be saved.');
162
            }
163
        }
164
    }
165
}
166
catch (Exception $ex)
167
{
168
    echo '<div style=\'border: 1px solid red; background-color: rgba(255, 0, 0, 0.1); color: red; padding: 15px; text-align: center;\'>'.$ex->getMessage().'</div>';
169
}
170
171
function sizeFormat($size, $format)
172
{
173
    switch ($format)
174
    {
175
        case 'GB': $size /= 1000;
176
        case 'MB': $size /= 1000;
177
        case 'KB': $size /= 1000;
178
    }
179
    
180
    return $size.' '.$format;
181
}
182
183
?>
184
185
<form method='post' enctype='multipart/form-data'>
186
    <input name='MAX_FILE_SIZE' type='hidden' value='<?= $settings['file_maxsize']; ?>' />
187
    <input name='p1' type='file' accept='<?= implode(',', $settings['ext']); ?>' />
188
    <input name='send' type='submit' value='Send' />
189
</form>