In this article I will be showing you how to download a file from your server securely with php script. Many programmers faces a problem of returning 0 byte file size during file download, even I also faced the same problem when I first tried to download a file from my server using php. I will also be showing you why it happens. So following is the simple php code snippet to download a file from the server.

$fileName="filename.jpg"; // the file path have to be the absolute path to 
                                            // the file like in linux "/var/www/..../filename.jpg"
                                            // and in windows "C:\\wamp\www\...\filename.jpg
if (file_exist($fileName)) {
            header("Pragma: public");
            header("Expires: 0");
            header('Content-Description: File Transfer');
            header('Content-Type: application/' . $fileType);
            header('Content-Disposition: attachment; filename=' . basename($fileName));
            header('Content-Transfer-Encoding: binary');
            header('Cache-Control: post-check=0, pre-check=0', false);
            header('Cache-Control: no-store, no-cache, must-revalidate');
            header("Cache-Control: private", false);
            header('Pragma: no-cache');
            header('Content-Length: ' . filesize($fileName));
            readfile($fileName);
            exit;
        } else {
            echo 'File does not exists.';
        }



Note: In the above program if the $fileName does not refer to the absolute file path you are expected to have 0 byte filesize.

Check Page Rank