0

I am trying to write a PHP script that will download a file on the client side. The file can be Excel (xlsx) or JSON.

The URL will look like:
http://<server>/php/download.php?file=/some/path/file.xlsx&name=file.xlsx&format=xlsx

And my PHP script looks like this:

<?php
if($_GET['format']==='excel') {
    header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
} else if($_GET['format']==='json') {
    header('Content-type: application/json');
}

header("Content-disposition: attachment; filename=".$_GET['name']);
readfile($_GET['file']);
?>

I have double checked that the actual files are not corrupt or anything. But when I use the URL above, a 0 sized file is downloaded (albeit with the right name) and obviously that's wrong. What is wrong in my PHP code?

shikhanshu
  • 1,466
  • 2
  • 16
  • 32
  • 1
    Please don't use unsafe (user)input to serve files from your server – DarkBee Nov 04 '17 at 00:07
  • The URL is formed by me (I am writing the front-end too) and it is fully under my control. So the GET parameters being passed to server are not arbitrary or up to the user. Coming back to the question - what's wrong in the PHP that it is unable to serve the file? – shikhanshu Nov 04 '17 at 02:31
  • My bad! switch to `error_reporting(E_ALL)` and noticed that `readfile()` has been disabled by the admins. Is there any other way to serve up a file for download without using `readfile`? – shikhanshu Nov 04 '17 at 02:50
  • check workarounds and test for disabled functions (so you know out of which alternatives you can choose): https://stackoverflow.com/a/9289994/588079 **The GET parameters are completely up to the user, that is not a joke!** Anyone can make any request, **never** trust user-input! See https://www.owasp.org/index.php/Path_Traversal – GitaarLAB Nov 04 '17 at 05:05

1 Answers1

0

I was able to do this using echo file_get_contents($filename) instead of readfile which was disabled by server admin.

shikhanshu
  • 1,466
  • 2
  • 16
  • 32