Upload and save a file in to a database using PHP and MySQL. let's implement upload a file.
create an upload form input file type
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="File" id="File">
<button type="submit" class="btn" name="btn-upload">Upload</button>
</form>
I have not applied on upload file type extension but you can add a restriction based on your need
if(isset($_POST['btn-upload']))
{
global $conn, $errors, $file;
$file = rand(1000,100000)."-".$_FILES["File"]['name'];
$file_loc = $_FILES["File"]['tmp_name'];
$file_size = $_FILES["File"]['size'];
$file_type = $_FILES["File"]['type'];
$folder="uploads/";
// new file size in KB
$new_size = $file_size/1024;
// new file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if (empty($file)) { array_push($errors, "File is required"); }
if(!move_uploaded_file($file_loc,$folder.$final_file))
{
array_push($errors, "Failed to upload file. Please check file settings for your server");
}
// Ensure that no post is saved twice.
$post_check_query = "SELECT * FROM uploadfile WHERE File='$final_file' LIMIT 1";
$result = mysqli_query($conn, $post_check_query);
if (mysqli_num_rows($result) > 0) { // if post exists
array_push($errors, "A file already exists with that file name.");
}
// create post if there are no errors in the form
if (count($errors) == 0) {
$sql="INSERT INTO uploadfile(File,type,size,downloads,Date) VALUES('$final_file','$file_type','$new_size',0,NOW())";
mysqli_query($conn, $sql);
$_SESSION['upload_message'] = "File Uploaded successfully";
header('location: upload.php');
exit(0);
}
}
then download the file when a user click a download link
// Downloads files
if (isset($_GET['file_id'])) {
$id = $_GET['file_id'];
// fetch file to download from database
global $conn;
$sql = "SELECT * FROM uploadfile WHERE FID=$id";
$result = mysqli_query($conn, $sql);
$file = mysqli_fetch_assoc($result);
$filepath = 'admin/uploads/' . $file['File'];
if (file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Cache-Control: must-revalidate');
header('Expires: 0');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Content-Length: ' . filesize('admin/uploads/' . $file['File']));
header('Pragma: public');
flush();
readfile('admin/uploads/' . $file['File']);
// Now update downloads count
$newCount = $file['downloads'] + 1;
$updateQuery = "UPDATE uploadfile SET downloads=$newCount WHERE FID=$id";
mysqli_query($conn, $updateQuery);
exit(0);
}
else{
$_SESSION['message'] = "File does not exist.";
header('location: ' . BASE_URL . '#.php');
exit(0);
}
}
We have made the source code available for download. You will be able to access it once you have logged in. Please log in to download the source code.