PDA

View Full Version : Dynamic Downloads in PHP


Reven
01-22-2006, 10:28 PM
I want to create a script which will allow people to download files, but through dynamic links. For example, instead of using a static link such as example.com/files/file1.zip, where hot-linking can occur, I would like to do something like example.com/files/filedownload.php?file=file1, in which I can do checks to make sure the person downloading is logged in to vBulletin and stuff.

I don't know the name of the process of generating dynamic downloads, so I can't find anything on php.net. All I can think of doing is changing the header to the mime type of the file, but I don't know then how to start the download without the user having to click on something.

I don't want to redirect to the static file location either, as this is a security risk.

Any help would be fab. Cheers.

Hellcat
01-23-2006, 01:21 AM
I have a script that does almost what you described - except for the logged in to vB thing (it checks an own login).

If it would help you I could just send you that script so you can "walk" through it and see how it does what.
IMHO that's always the best way to get such questions answered.

But a short one anyways :D
If you want to send a file, rather then a HTML page, you could use this block of code BEFORE you output anything else:
header ( "Content-Type: application/octet-stream"); // or whatever mime-type is appropriate
header ( "Content-Length: ".$filesize); // filesize in bytes!
header ( "Content-Disposition: attachment; filename=\"$filename\"");
readfile($filepath);

Reven
01-23-2006, 08:27 AM
Great, I'll give that a shot. Cheers.

I want to allow people to download .zips and stuff, not HTML pages. I can do all of the vBulletin checks and stuff, I just didn't know how to send files like that.

Thanks again. If I have problems using the script, I'll know where to look ;)

EDIT: I have built a script using the above info, but when the file is downloaded it is always 0 bytes in length. This is the script:

if ($_REQUEST['do'] == "download")
{
$file = $_REQUEST['file'];
$filetype = $_REQUEST['type'];
$filename = $file . "." . $filetype;
$file_location = getcwd() . "/band_files/" . $filename;
$filesize = filesize($file_location);

header ("Content-Type: audio/mpeg");
header ("Content-Length: ".$filesize);
header ("Content-Disposition: attachment; filename=\"$filename\"");
readfile($filepath);
}

It doesn't work properly when using file_get_contents() in place of readfile() either. Anyone know what's wrong?

Hellcat
01-23-2006, 01:29 PM
You are putting the path of your file in $file_location but in the readfile() call you use $filepath - try using $file_location there as well....

Reven
01-23-2006, 02:56 PM
Haha, I'm an idiot. It worked.

Thanks very much :)

I'd give you reputation if I could, and if it actually had any effect.