This repository has been archived by the owner on Apr 27, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathupload_image.php
62 lines (46 loc) · 1.7 KB
/
upload_image.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
try {
// File Route.
$fileRoute = "/uploads/";
$fieldname = "file";
// Get filename.
$filename = explode(".", $_FILES[$fieldname]["name"]);
// Validate uploaded files.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
// Get temp file name.
$tmpName = $_FILES[$fieldname]["tmp_name"];
// Get mime type.
$mimeType = finfo_file($finfo, $tmpName);
// Get extension. You must include fileinfo PHP extension.
$extension = end($filename);
// Allowed extensions.
$allowedExts = array("gif", "jpeg", "jpg", "png", "svg", "blob");
// Allowed mime types.
$allowedMimeTypes = array("image/gif", "image/jpeg", "image/pjpeg", "image/x-png", "image/png", "image/svg+xml");
// Validate image.
if (!in_array(strtolower($mimeType), $allowedMimeTypes) || !in_array(strtolower($extension), $allowedExts)) {
throw new \Exception("File does not meet the validation.");
}
// Generate new random name.
$name = sha1(microtime()) . "." . $extension;
$fullNamePath = dirname(__FILE__) . $fileRoute . $name;
// Check server protocol and load resources accordingly.
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] != "off") {
$protocol = "https://";
} else {
$protocol = "http://";
}
// Save file in the uploads folder.
move_uploaded_file($tmpName, $fullNamePath);
// Generate response.
$response = new \StdClass;
$response->link = $protocol.$_SERVER["HTTP_HOST"].dirname($_SERVER["PHP_SELF"]).$fileRoute . $name;
// Send response.
echo stripslashes(json_encode($response));
} catch (Exception $e) {
// Send error response.
echo $e->getMessage();
http_response_code(404);
}
?>