Downloading a file using PHP saves an empty file

Downloading a file using PHP saves an empty file

Problem Description:

I created a download.php file in my vps server which has some images, if users request the file using this file, the file is saved to the devices. But this creates an empty file. This is the code.

<?php
if(isset($_GET['file']))
{
    $filename = $_GET["file"];
    if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i', $file)){
        $filepath = "images/" . $file;
        if(file_exists($filepath)) {
            header("Content-Type: application/octet-stream");
            header("Content-Transfer-Encoding: Binary");
            header("Content-disposition: attachment; filename="".$filename."""); 
           readfile($filepath);
        }
    }
?>

I have corrected the typos and removed echo still , it is the same, The file is downloaded when download.php?file=abstract.jpg is invoked on the server.

Solution – 1

There is still a couple of errors in your code:

  1. There is no closing parentheses for your initial if block

  2. Your preg_match – you’re passing a variable $file to it which hasn’t been declared. I think you mean to pass $filename. If I am not mistaken, your code is continuing because the preg_match isn’t returning false.

  3. You’re passing $file to create the $filepath variable too, so again, it’s just trying to download images/ instead of the full path.

This code works:

<?php
if(isset($_GET['file']))
{
    $filename = $_GET["file"];
    if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i', $filename)){
        $filepath = "images/" . $filename;
        if(file_exists($filepath)) {
            header("Content-Type: application/octet-stream");
            header("Content-Transfer-Encoding: Binary");
            header("Content-disposition: attachment; filename="".$filename."""); 
           readfile($filepath);
        }
    }
}
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject