0

I want users who visit my site with a valid URL (get parameter is checked in database)

to be able to download a file from the server while others who don't access the site with a valid URL aren't able to do so.

Currently i am able to do

if (isValid($get_param))
{
    print link to file
} else {    
    print some other message
}

This is fine but doesn't prevent someone from simply visiting the direct link to the file say site.com/file.mp3.

How do I prevent someone from being able to download the file in that manner but allow them download it if the URL has a valid get parameter?

hakre
  • 184,866
  • 48
  • 414
  • 792
algorithmicCoder
  • 6,395
  • 20
  • 67
  • 117

4 Answers4

0

You have to do that in your file permissions on the server.

Only allow the PHP code permissions to access that file.

Naftali
  • 142,114
  • 39
  • 237
  • 299
0

You might consider moving your protected files outside of the web server document root to avoid the direct access, then using readfile() in combination with header() to force a download as shown in the first example on the readfile() manual page.

jcmeloni
  • 1,246
  • 1
  • 15
  • 21
0

Instead of printing the link to it, try adding this code after the validation.

$file = "something.zip/pdf";

header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Content-Type: application/force-download"); 
header("Content-Disposition: attachment; filename=".$file);
header("Content-Description: File Transfer"); 
@readfile($file); 

This will just start the download directly and the user doesnt get to know where the file is coming from

Kartik
  • 8,725
  • 8
  • 46
  • 52
  • This code doesnt depend of what type of file it is, it will work the same for text, zip, mp3 or any other file. – Kartik Jan 26 '12 at 23:14
0

You have to process your download in PHP, to prevent unauthorized access:

$file = "path/to/file.mp3";

header("Content-Disposition: attachment; filename=".basename( $file ));
header("Content-Type: audio/mpeg"); // you need the correct mime-type for your file
header("Content-Length: ". filesize( $file ) );
header("Content-Transfer-Encoding: binary");
readfile($file);
exit;
DerVO
  • 3,639
  • 1
  • 22
  • 27