-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload.php
93 lines (76 loc) · 2.38 KB
/
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
define("UPLOAD_DIR", "uploads\\");
if (!is_dir(UPLOAD_DIR)) {
mkdir(UPLOAD_DIR);
}
/*
print_r($_POST);
print_r($_FILES);
*/
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$errorMsg = "Missing";
if(empty($_POST["dept"]))
$errorMsg = $errorMsg . " Department,";
if(empty($_POST["year"]))
$errorMsg = $errorMsg . " Year,";
if(empty($_POST["subject"]))
$errorMsg = $errorMsg . " Subject,";
if(empty($_POST["chapter"]))
$errorMsg = $errorMsg . " Chapter,";
if(empty($_FILES["myFile"]["name"]))
$errorMsg = $errorMsg . " File,";
if($errorMsg == "Missing") { // i.e. no text after Missing, means nothing is missing
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
//$data = mysqli_real_escape_string($data);
return $data;
}
$dept = test_input($_POST["dept"]);
$year = test_input($_POST["year"]);
$subject = test_input($_POST["subject"]);
$chapter = test_input($_POST["chapter"]);
if ($_FILES["myFile"]["error"] !== UPLOAD_ERR_OK) {
echo "An error occurred: ". $_FILES["myFile"]["error"];
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $_FILES["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"]; // create file with new name zzzz-1.pdf
}*/
$dest_path = UPLOAD_DIR . $dept . "\\" . $year . "\\" . $subject . "\\" . $chapter . "\\" . $name;
if(file_exists($dest_path)) {
echo "A file with same name $name exists in this directory. Please delete it first and then try to upload.";
}
else {
// preserve file from temporary directory
$success = move_uploaded_file($_FILES["myFile"]["tmp_name"], $dest_path);
if (!$success) {
echo "Unable to save file";
}
else {
echo "Success";
}
}
// set proper permissions on the new file
//chmod(UPLOAD_DIR . $name, 0644);
}
else {
echo rtrim($errorMsg, ",");
}
}
/*
$_FILES["myFile"]["name"] stores the original filename from the client
$_FILES["myFile"]["type"] stores the file’s mime-type
$_FILES["myFile"]["size"] stores the file’s size (in bytes)
$_FILES["myFile"]["tmp_name"] stores the name of the temporary file
$_FILES[“myFile”][“error”] stores any error code resulting from the transfer
*/
?>