Php readfile - Force Download
I am using a flash player to play some mp3 files. At firefox it loads them normally but at IE it doesn't. When i go to the url of the .mp3 file it shows the source code of the mp3 (instead of offering eg to download). So i used a small script to fix it:
$url = $_GET['url'];
header('Content-type: application/force-download');
header('Content-Transfer-Encoding: Binary');
header("Content-disposition: attachment; filename=demo.mp3");
readfile($url);
I would like to ask you if the above is safe. Moreover, does the server losses bandwidth by this way? And finally, does it 开发者_开发百科influence the server's resources? Thanks.
No, that's not safe. If you had your database password in database.php
and I entered database.php
as $_GET['url']
, your script would send me that PHP file with your password in it.
Yes, this would use up bandwidth and some server resources.
It's not safe, and it shouldn't be necessary for you to do this way.
In addition to the security implications @ceejayoz outlines, if the allow_url_fopen
PHP setting is enabled, it is also possible to insert any URL into $url
. That way, your server could be easily misused to stream large amounts of data from other servers, with all kinds of implications.
This method of serving files should be used only when really necessary. It consumes more resources (because an expensive PHP process has to be started) than requesting a static resource through the web server.
It should not be necessary in your case anyway. It sounds like your web server is not serving the correct content-type
header along with your MP3 files. That is what you should fix.
Maybe, if you're on Apache, adding a .htaccess
file to the directory the MP3s are in with the following content:
AddType audio/mpeg .mp3
already fixes the problem. If it doesn't, but the force-download
thing works, then try
AddType application/force-download .mp3
Your actual problem is that you are not sending the content-type header to the client when you serve the mp3 file. Ensure that you are setting the content-type header prior to sending the contents of the mp3 file.
If you're serving them directly from your web server, without a script, you simply need to configure the content-type in your web server's configuration.
For Apache, you can configure this in an .htaccess file:
AddType audio/mpeg .mp3
Yeah there is definitely a security risk here since you aren't validating/sanitizing the requested file path. So make sure you check that before sending files down to the user!
Although this will use bandwidth and server resources, it would be minimally more than downloading files regularly. The only extra overhead is processing/running the PHP. You probably won't notice a difference.
精彩评论