Allow Only Logged in Users to View Files

Today i will explain how to allow only logged in users to view uploaded files using PHP, for this we need a logged in user, i have already wrote tutorial how to create simple user registration and login script in PHP and MySQL, in this tutorial i will upload file using PHP and save that file to our directory/folder, also insert record of uploaded file into table of our database. In the admin dashboard, i also placed view uploaded file option where only logged in user can view and delete uploaded files, if someone try to copy URL of specific file and open it without log in to your website then file will not be opened. I have also recently wrote tutorial how to insert, view, edit and delete record from database using PHP and MySQL, if you don’t know how to do it then i advise you first read it. In know you are thinking why am i telling you about my recent tutorials, this is because we must have them to implement this restriction.

Download Complete Source Code

View Uploaded PDF Files

Steps to Allow Access Only Logged in Users to View Files

Now lets come to our actual tutorial, i assume that you already created all files which was created in Insert, View, Edit and Delete Record from Database Using PHP and MySQL, you must have it to implement restriction that only logged in users can view uploaded files, follow the below steps.

  1. Create Another Table for Uploaded File Records
  2. Update Dashboard File
  3. Create Upload Page
  4. Create View Uploaded  File Page
  5. Create a folder name upload and create another file in this folder with name viewpdf.php, upload is a folder where all uploaded files will be saved.
  6. Create Delete File Page

1. Create Another Table for Uploaded File Records

Execute the below query in SQL

CREATE TABLE IF NOT EXISTS `filetable` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `trn_date` datetime NOT NULL,
 `filetitle` varchar(50) NOT NULL,
 `filename` varchar(50) NOT NULL,
 PRIMARY KEY (`id`)
 );

2. Update Dashboard Page

Update a dashboard.php just by paste the below code in it.

<?php 
require('db.php');
include("auth.php"); //include auth.php file on all secure pages ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dashboard - View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>Welcome to Dashboard.</p>
<p><a href="index.php">Home</a><p>
<p><a href="insert.php">Insert New Record</a></p>
<p><a href="view.php">View Records</a><p>
<p><a href="upload.php">Upload File</a><p>
<p><a href="viewfiles.php">View Files</a><p>
<p><a href="logout.php">Logout</a></p>
</div>
</body>
</html>

3. Create Upload Page

Create a page with name upload.php and paste the below code in it. I have also restricted only PDF file, this means only PDF files can be uploaded, this will be check extension on client side before upload file using jQuery.

Note: Don’t forget to include the jQuery library in the header or footer.

<?php 
require('db.php');
include("auth.php"); //include auth.php file on all secure pages
$uploadstatus = "";
if(isset($_REQUEST['filetitle']))
{
$trn_date = date("Y-m-d H:i:s");
$filetitle =$_REQUEST['filetitle'];
$target_dir = "upload/"; // Where the file is going to be placed
$path = pathinfo($_FILES['upload_file']['name']);
$filename = $path['filename'];
$ext = $path['extension'];
$temp_name = $_FILES['upload_file']['tmp_name'];
$pathfilenameext= $target_dir.$filename.".".$ext;

// Check if file already exists
if (file_exists($pathfilenameext)) {
 $uploadstatus = "Sorry, file already exists.";
 }
else 
 {
 move_uploaded_file($temp_name,$pathfilenameext);
 $uploadstatus = "File Uploaded Successfully.";
 $ins_query="insert into filetable(`trn_date`,`filetitle`,`filename`)values('$trn_date', '$filetitle', '$filename')";
 mysql_query($ins_query) or die(mysql_error());
 }
}
?>
<html>
<head>
<title>Upload File Using PHP and Save in Folder</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="dashboard.php">Dashboard</a> | <a href="viewfiles.php">View Files</a> | <a href="logout.php">Logout</a></p>
<h1>Upload File</h1>
<form name="form" method="post" action="" enctype="multipart/form-data" >
<input type="text" name="filetitle" placeholder="Enter File Title:" required /><br /><br />
<input type="file" name="upload_file" id="upload_file" /><br /><br />
<p id="error" style="display:none; color:#FF0000;">File format should be PDF.</p>
<input type="submit" name="submit" value="Upload" />
</form>
<p style="color:#FF0000;"><?php echo $uploadstatus; ?></p> 
</div>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$('input[type="submit"]').prop("disabled", true);
$('#upload_file').bind('change', function() {
var ext = $('#upload_file').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf','PDF']) == -1)
{ $('#error').slideDown("slow"); } else
{$('#error').slideUp("slow"); $('input:submit').attr('disabled',false);}
});
</script>
</body>
</html>

Upload File

4. Create View Uploaded File Page

Create a page with name viewfiles.php and paste the below code in it. In this file only logged in user can view and delete file, also note that i included a confirm function onclick event, so that when user click on delete button, it should ask that “Are you sure?” if OK is pressed, file will be deleted otherwise not. If user want to view file so simply click on file title (these files only accessible for logged in users) you can confirm it just by copying the opened file URL and open it another browser window.

<?php 
require('db.php');
include("auth.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>View Uploaded PDF Files</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="dashboard.php">Dashboard</a> | <a href="upload.php">Upload New File</a> | <a href="logout.php">Logout</a></p>
<h2>View Uploaded PDF Files</h2>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr><th><strong>S.No</strong></th><th><strong>File Title</strong></th><th><strong>Delete</strong></th></tr>
</thead>
<tbody>
<?php
$count=1;
$sel_query="Select * from filetable;";
$result = mysql_query($sel_query);
while($row = mysql_fetch_assoc($result)) { ?>
<tr><td align="center"><?php echo $count; ?></td><td align="center"><a href="upload/viewpdf.php?file=<?php echo $row["filename"]; ?>.pdf" target="_new"><?php echo $row["filetitle"]; ?></a></td><td align="center"><a href="deletefile.php?id=<?php echo $row["id"]; ?>&filename=<?php echo $row["filename"]; ?>" onclick="return confirm('Are you sure?')">Delete</a></td></tr>
<?php $count++; } ?>
</tbody>
</table>
</div>
</body>
</html>

View Uploaded PDF Files

5. Create a Folder with name Upload & Create Another File in this folder with name viewpdf.php

Create a page with name viewpdf.php and paste the below code in it. (Make sure this file should be placed into Upload directory) This is the main file which restrict that only logged in user is viewing file, it simply check is user session is set, if yes then allow to view file.

<?php
session_start();
if(!isset($_SESSION["username"])){
header("location: ../login.php");
}
else{
if (isset($_GET['file'])) {
$file = $_GET['file'];
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
header('Content-Type: application/pdf');
header("Content-Disposition: inline; filename=\"$file\"");
readfile($file);
}
} else {
header("Location: ../index.php");
}
}
?>

6. Create Delete File Page

Create a page with name deletefile.php and paste the below code in it. This file not only delete file record from DB table but also delete file from directory as well.

<?php 
require('db.php');
$id=$_REQUEST['id'];
$filename=$_REQUEST['filename'];
$query = "DELETE FROM filetable WHERE id=$id"; 
$result = mysql_query($query) or die ( mysql_error());
$target = "upload/".$filename.".pdf";
if (file_exists($target)) {
 unlink($target); // Delete File From Directory
}
header("Location: viewfiles.php"); 
?>

Download Complete Source Code

Leave your comments if you find this tutorial helpful.