Download File Using PHP

Listen Audio
0:00 / 0:00
Download file using PHP image

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);
    }
}

 



Leave a non public comment how to improve it.



Characters Remaining

We are sorry for your bad experience. Leave a non public comment how to improve it.



Characters Remaining

Related Posts (11)

How to create a custom archive page template on your website layout image
Test the video layout design(Upload and Store video to MySQL Database with PHP) image
How to set the expiry period for a reset password link. image
Getting User Device Location and Updating Database image
Send A verification email when a new user registered  image
How to Send Verification link when a new user register image
How to limit the number of login attempts  image
How to limit the number of login attempt using PHP part 2(PHP functionality) image
Inactive user enforce to login (SESSION expired) or Limmit the resource image
How to count page viewers based on the IP Address of the device image
Pagination in PHP image

Share this on

Search


Archives

No archives data found yet in 2016.

Find Us on Facebook

Subscribe for new updates



Back to Top