I wrote a file download script in PHP which enables users to download any specified file from my server. The script is working pretty fine for .txt, .pdf and .jpg etc. files.
But when the user is trying to download any .mp3 or .mp4 files then though script downloads the files but the file is unusable. The file is very less in size as compared to my original file. The file can't be opened in any media player - it is corrupted.
I don't know what is wrong with my this download script. Here's the full code:
Interface Page (index.php):
<a href="download.php?file=tutorial.pdf">Download Tutorial (pdf)</a><br /><br />
<a href="download.php?file=music.mp3">Download Music (mp3)</a><br /><br />
<a href="download.php?file=video.mp4">Download Video (mp4)</a>
PHP Script (download.php):
<?php
if(isset($_GET['file']) && !empty($_GET['file']))
{
$file = $_GET['file'];
$file_without_spaces = str_replace(' ', "%20", $file);
$path_parts = pathinfo($file);
$file_name = $path_parts['basename'];
$file_path = "files/" . $file_name;
$file_extension = $path_parts['extension'];
if(!is_readable($file_path))
{
die("File not found!");
}
// Figure out the correct MIME type
$mime_types = array(
// Documents
"pdf" => "application/pdf",
"doc" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"csv" => "application/csv",
"txt" => "text/plain",
// Archives
"zip" => "application/zip",
// Executables
"exe" => "application/octet-stream",
// Images
"jpg" => "image/jpeg",
"jpeg" => "image/jpeg",
"png" => "image/png",
"gif" => "image/gif",
"bmp" => "image/bmp",
// Audio
"mp3" => "audio/mpeg",
"wav" => "audio/x-wav",
// Video
"mpeg" => "video/mpeg",
"mpg" => "video/mpeg",
"mov" => "video/quicktime",
"avi" => "video/x-msvideo",
"mp4" => "video/mp4",
"3gp" => "video/3gpp"
);
if(array_key_exists($file_extension, $mime_types))
{
$mime_type = $mime_types[$file_extension];
}
header("Content-type: " . $mime_type);
header("Content-Disposition: attachment; filename=\"$file_without_spaces\"");
readfile($file_path);
}
?>
I downloaded a big .mp4
file of size around 250 MB. It came out to be just 2 KB. I found out this error in my notepad:
Fatal error: Allowed memory size of...