-
Notifications
You must be signed in to change notification settings - Fork 525
/
15_file_upload.php
58 lines (52 loc) · 1.63 KB
/
15_file_upload.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
<?php
/* ----------- File upload ---------- */
$allowed_ext = array('png', 'jpg', 'jpeg', 'gif');
if(isset($_POST['submit'])) {
// Check if file was uploaded
if(!empty($_FILES['upload']['name'])) {
$file_name = $_FILES['upload']['name'];
$file_size = $_FILES['upload']['size'];
$file_tmp = $_FILES['upload']['tmp_name'];
$target_dir = "uploads/${file_name}";
// Get file extension
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
// echo $file_ext;
// Validate file type/extension
if(in_array($file_ext, $allowed_ext)) {
// Validate file size
if($file_size <= 1000000) { // 1000000 bytes = 1MB
// Upload file
move_uploaded_file($file_tmp, $target_dir);
// Success message
echo '<p style="color: green;">File uploaded!</p>';
} else {
echo '<p style="color: red;">File too large!</p>';
}
} else {
$message = '<p style="color: red;">Invalid file type!</p>';
}
} else {
$message = '<p style="color: red;">Please choose a file</p>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<?php echo $message ?? null; ?>
<form action="<?php echo htmlspecialchars(
$_SERVER['PHP_SELF']
); ?>" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="upload">
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>