Search code examples
phpfiledownloadreadfile

Readfile returns an empty file


I have this code to force a download, $file is a url of a existing .jpg, .png or .pdf file (I made sure it exists)

 <?php
    $file = $_REQUEST['file'];
    $file_extension = end(explode('.', $file));
    $file_name = end(explode('/', $file));
    switch ($file_extension) {
        case 'jpg':
            header('Content-Type: image/jpeg');
            header('Content-Disposition: attachment; filename='.$file_name);
            header('Pragma: no-cache');
            readfile($file);
            break;
        case 'png':
            header('Content-Type: image/png');
            header('Content-Disposition: attachment; filename='.$file_name);
            header('Pragma: no-cache');
            readfile($file);
            break;
        case 'pdf':
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename='.$file_name);
            header('Pragma: no-cache');
            readfile($file);
            break;
    }

But it's downloading an empty (0KB) file (with the correct name)

Any thought about what may be happening?


Solution

  • Since file_get_contents() return null too, your problem is probably a setting in the php.ini configuration.

    The parameter allow_url_fopen must be On.