简体   繁体   中英

Rename mp3 file and Download file in PHP

I have an issue while downloading an mp3 file in PHP. I need to download the file, also rename it. Below is the download.php file which contains the following code:

$file = $_GET['file'];
$flname = explode("/",$file);
$num = sizeof($flname);
$filenme = $flname[$num-1];
$name_of_file = $filenme;

header('Content-Description: File Transfer');
header('Content-type: application/mp3');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: '.filesize($name_of_file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');

readfile_chunked($file);

function readfile_chunked($file) 
{ 
    $chunksize = 1*(1024*1024); // how many bytes per chunk 
    $buffer = ''; 
    $handle = fopen($filename, 'rb');

    if ($handle === false) 
    { 
        return false; 
    } 

    while (!feof($handle))   
    { 
        $buffer = fread($handle, $chunksize); 
        print $buffer; 
    } 

    return fclose($handle); 
}

I am getting the file path in $file :

$file = $_GET['file']; 

where $file becomes:

$file = "localhost/project/mp3 file path";

Then I am exploding it to get the mp3 file name only (thus removing the path). I don't know what the problem is, but it's always showing some 490 bytes in the download dialogue of Firefox even if file is of 1-2MB. Can someone explain what I'm doing wrong?

Thank you in advance.

Open the downloaded file in a text editor. It probably contains php errors that will tell you what exactly is going on. It might be an issue with the path or permissions of the file you are trying to download.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM