cant upload file to directory php

Solutions on MaxInterview for cant upload file to directory php by the best coders in the world

showing results for - "cant upload file to directory php"
Claudia
17 Jan 2020
1
2You'd better check $_FILES structure and values throughly.
3The following code cannot cause any errors absolutely.
4
5Example:
6<?php
7
8header('Content-Type: text/plain; charset=utf-8');
9
10try {
11    
12    // Undefined | Multiple Files | $_FILES Corruption Attack
13    // If this request falls under any of them, treat it invalid.
14    if (
15        !isset($_FILES['upfile']['error']) ||
16        is_array($_FILES['upfile']['error'])
17    ) {
18        throw new RuntimeException('Invalid parameters.');
19    }
20
21    // Check $_FILES['upfile']['error'] value.
22    switch ($_FILES['upfile']['error']) {
23        case UPLOAD_ERR_OK:
24            break;
25        case UPLOAD_ERR_NO_FILE:
26            throw new RuntimeException('No file sent.');
27        case UPLOAD_ERR_INI_SIZE:
28        case UPLOAD_ERR_FORM_SIZE:
29            throw new RuntimeException('Exceeded filesize limit.');
30        default:
31            throw new RuntimeException('Unknown errors.');
32    }
33
34    // You should also check filesize here. 
35    if ($_FILES['upfile']['size'] > 1000000) {
36        throw new RuntimeException('Exceeded filesize limit.');
37    }
38
39    // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
40    // Check MIME Type by yourself.
41    $finfo = new finfo(FILEINFO_MIME_TYPE);
42    if (false === $ext = array_search(
43        $finfo->file($_FILES['upfile']['tmp_name']),
44        array(
45            'jpg' => 'image/jpeg',
46            'png' => 'image/png',
47            'gif' => 'image/gif',
48        ),
49        true
50    )) {
51        throw new RuntimeException('Invalid file format.');
52    }
53
54    // You should name it uniquely.
55    // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
56    // On this example, obtain safe unique name from its binary data.
57    if (!move_uploaded_file(
58        $_FILES['upfile']['tmp_name'],
59        sprintf('./uploads/%s.%s',
60            sha1_file($_FILES['upfile']['tmp_name']),
61            $ext
62        )
63    )) {
64        throw new RuntimeException('Failed to move uploaded file.');
65    }
66
67    echo 'File is uploaded successfully.';
68
69} catch (RuntimeException $e) {
70
71    echo $e->getMessage();
72
73}
74
75?>
76
77