forked from allinhtml/FileUploadsWithPHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.php
53 lines (46 loc) · 1.49 KB
/
index.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
<?php
define("UPLOAD_DIR", "/srv/www/uploads/");
// show upload form
if ($_SERVER["REQUEST_METHOD"] == "GET") {
?>
<em>Only GIF, JPG, and PNG files are allowed.</em>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="myFile"/>
<br/>
<input type="submit" value="Upload"/>
</form>
<?php
}
// process file upload
else if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// verify the file type
$fileType = exif_imagetype($_FILES["myFile"]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
if (!in_array($fileType, $allowed)) {
echo "<p>File type is not permitted.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
echo "<p>Uploaded file saved as " . $name . ".</p>";
}