Ephenodrom
Ephenodrom

Reputation: 1893

How to access files from a certain php page that are protected by htaccess?

I have a page ( example : http://mypage.com/getfiles.php ) where the user can enter a keycode and then the page generates the links( html http://mypage.com/download/myfile.zip) to the files zu download and the user can click on the links to get the files.

The problem is that the files are stored in a folder ( download ) which is protected so nobody can directly access the files under http://mypage.com/download/myfile.zip.

I tried some differnt thinks i read on the internet to change the .htaccess file to alow access from a certain page... but it didn't work !

So I have 2 Questions : 1. Is this the easiest way ? Or is it better to use another way to give the user access to the files ( filesize from 50mb to 500mb ) 2. If the idea to customize the .htaccess file is the best way whats wrong with it ?

# set an environtment variable "noauth" if the request starts with certain string
SetEnvIf Request_URI "^http://mypage.com/getfiles.php" noauth=1

AuthType Basic
AuthName "Access to /download"
AuthUserFile ****
Require user ****

# Here is where we allow/deny
Order Deny,Allow
Satisfy any
Deny from all
Require valid-user
Allow from env=noauth

Or do i have to guide the user to an php script which forwards him to the file, because with link it doesn't work ?

Thank you very much !

Upvotes: 0

Views: 203

Answers (2)

anubhava
anubhava

Reputation: 784968

  1. Let this basic authentication be "as is" for someone who directly comes to /download folder.
  2. Make these changes in getfiles.php. Rather than giving direct link to zip file you can generate a link like this:

    1. Validate keycode and store it in session.
    2. If keycode is valid generate a download link: http://mypage.com/files.php?path=/download/myfile.zip
    3. Inside a new file files.php check if session has valid keycode. If yes then access the file using PHP file operations with correct Content-Type header.

Upvotes: 1

Waqar Alamgir
Waqar Alamgir

Reputation: 9968

You can create an script say download.php under http://mypage.com/ which eventaully copy content from file "download/myfile.zip" and auto download it to the user.

Example code:

// Add some keycode security, then download file for user.

$file_url = 'download/myfile.zip';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url); // do the double-download-dance (dirty but worky)

Upvotes: 3

Related Questions