-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfilesLogic.php
75 lines (60 loc) · 2.46 KB
/
filesLogic.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
<?php
// connect to the database
$conn = mysqli_connect('localhost', 'root', '', 'file-management');
$sql = "SELECT * FROM files";
$result = mysqli_query($conn, $sql);
$files = mysqli_fetch_all($result, MYSQLI_ASSOC);
// Uploads files
if (isset($_POST['save'])) { // if save button on the form is clicked
// name of the uploaded file
$filename = $_FILES['myfile']['name'];
// destination of the file on the server
$destination = 'uploads/' . $filename;
// get the file extension
$extension = pathinfo($filename, PATHINFO_EXTENSION);
// the physical file on a temporary uploads directory on the server
$file = $_FILES['myfile']['tmp_name'];
$size = $_FILES['myfile']['size'];
if (!in_array($extension, ['zip', 'pdf', 'docx'])) {
echo "You file extension must be .zip, .pdf or .docx";
} elseif ($_FILES['myfile']['size'] > 1000000) { // file shouldn't be larger than 1Megabyte
echo "File too large!";
} else {
// move the uploaded (temporary) file to the specified destination
if (move_uploaded_file($file, $destination)) {
$sql = "INSERT INTO files (name, size, downloads) VALUES ('$filename', $size, 0)";
if (mysqli_query($conn, $sql)) {
echo "File uploaded successfully";
}
} else {
echo "Failed to upload file.";
}
}
}
// Downloads files
if (isset($_GET['file_id'])) {
$id = $_GET['file_id'];
// fetch file to download from database
$sql = "SELECT * FROM files WHERE id=$id";
$result = mysqli_query($conn, $sql);
$file = mysqli_fetch_assoc($result);
$filepath = 'uploads/' . $file['name'];
if (file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filepath));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('uploads/' . $file['name']));
//This part of code prevents files from being corrupted after download
ob_clean();
flush();
readfile('uploads/' . $file['name']);
// Now update downloads count
$newCount = $file['downloads'] + 1;
$updateQuery = "UPDATE files SET downloads=$newCount WHERE id=$id";
mysqli_query($conn, $updateQuery);
exit;
}
}