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:
- Deny file access from all
- 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
Concatenation with Addition in It Doesn't Work as Expected
PHP APIs for Hotmail, Gmail and Yahoo
Understanding MVC: Whats the Concept of "Fat" on Models, "Skinny" on Controllers
How to Display Unicode Data with PHP
Switching Between Http and Https Pages with Secure Session-Cookie
How to Call a Controller Function Inside a View in Laravel 5
Getting Pear to Work on Xampp (Apache/MySQL Stack on Windows)
Will Xpath 2.0 And/Or Xslt 2.0 Be Implemented in PHP
Encryption/Decryption of Form Fields in Cakephp 3
PHP Regular Expression to Match Lines Starting with a Special Character
Mysqli_Query() Expects at Least 2 Parameters, 1 Given In
What Is an .Inc and Why Use It
Regex to Detect Invalid Utf-8 String
Regex to Strip Comments and Multi-Line Comments and Empty Lines
Access a Global Variable in a PHP Function
How to Use Array_Push on a Session Array in PHP
Is MySQL_Real_Escape_String() Necessary When Using Prepared Statements