Php: How to Block Direct Url Access to a File, But Still Allow It to Be Downloaded by Logged in Users

How can I block direct URL access to all file in a folder, but still allow it to be downloaded by users?

Instead of denying access by .htaccess file you could save your file at a folder outside public side of your server, that is, outside www directory.

PHP: How can I block direct URL access to a file, but still allow it to be downloaded by logged in users?

Into folder members create new folder files, move here all your songs, create new .htaccess file and add the following lines:

Order Deny,Allow
Deny from all



Into folder members create file get_song.php and add the following code:

if( !empty( $_GET['name'] ) )
{
// check if user is logged
if( is_logged() )
{
$song_name = preg_replace( '#[^-\w]#', '', $_GET['name'] );
$song_file = "{$_SERVER['DOCUMENT_ROOT']}/members/files/{$song_name}.mp3";
if( file_exists( $song_file ) )
{
header( 'Cache-Control: public' );
header( 'Content-Description: File Transfer' );
header( "Content-Disposition: attachment; filename={$song_file}" );
header( 'Content-Type: application/mp3' );
header( 'Content-Transfer-Encoding: binary' );
readfile( $song_file );
exit;
}
}
}
die( "ERROR: invalid song or you don't have permissions to download it." );


And now, you can use this URL to get the song file:

http://mysite.com/members/get_song.php?name=my-song-name

how to give access for downloading a file when user is logged in

Serve the file via PHP and you can check using the PHP session if the user is logged in.

Could do something like this... (Obviously setting something suitable in the session when you log a user in):

<?php
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
// or however you get the path
$yourfile = "/path/to/" . $_GET['file']. ".zip";

$file_name = basename($yourfile);

header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($yourfile));

readfile($yourfile);
exit;
} else {
echo "Please log in first.";
}
?>

Obviously you can pass the filename as a querystring parameter and use that in $yourfile to serve the appropriate file. If doing this, which is the correct way to do so, can do some check to ensure the file exists before you serve it.

Example useage would then look like: download.php?file=file1.zip

The above example assumes you are not using any frameworks (i.e. Laravel, CakePHP etc), if you are using a framework, I would advise to use the session objects/functions avaiable.

It is also best practice to store files outside the webroot, this way you will ensure their protection. But this will also work in your case, just set $yourfile to the absolute path to /data/downloads. Doing this you do not need the .htaccess stuff.

htaccess - disallow direct access to all files except logged in users (PHP)

You cannot do this with .htaccess alone. What you need to do is:

  1. Deny file access from all
  2. Have a "file provider" script which allows file passthrough after authentication.

Example:

proxy.php

<?php 
$proxiedDirectory = "./files/"; //Whatever the directory you blocked access to is.
$filename = isset($_GET["fn"])?$_GET["fn"]:null;

if (!user_is_authenticated()) { //Not a real method, use your own check
http_response_code(403);
exit;
}

if ($filename === null || !file_exists($proxiedDirectory.$filename)) {
http_response_code(404);
exit;
}

$fp = fopen($proxiedDirectory.$filename, 'rb');

header("Content-Type: image/???"); //May need to determine mime type somehow
header("Content-Length: " . filesize($proxiedDirectory.$filename));

fpassthru($fp);
exit;

And you'd use this via:

http://example.com/proxy.php?fn=filename.txt

prevent direct url access to php file

You can do it with PHP

<?php
/* at the top of 'check.php' */
if ( $_SERVER['REQUEST_METHOD']=='GET' && realpath(__FILE__) == realpath( $_SERVER['SCRIPT_FILENAME'] ) ) {
/*
Up to you which header to send, some prefer 404 even if
the files does exist for security
*/
header( 'HTTP/1.0 403 Forbidden', TRUE, 403 );

/* choose the appropriate page to redirect users */
die( header( 'location: /error.php' ) );

}
?>


Related Topics



Leave a reply



Submit