phpforce-download

PHP Force Download File Name with Spaces


Ok I seem to be having an issue with making my script download the file with the proper file name.

If I strip spaces and dashes which looks like this

if($type == 'mc'){
    $file_name = $_POST['Ids'];
    $file_name = str_replace('-', '', $file_name);
    $file_name = str_replace(' ', '&', $file_name);
    $url = base64_decode($stream);
    $file_url = "scd.php?stream=".$url."&name=".$file_name."";
    $url = array('url' => $file_url);
    echo json_encode($url);
}

Here is scd.php

<?php
$file = $_GET['stream'];
$name = $_GET['name'];
header("Content-type: application/x-file-to-save");
header("Content-Disposition: attachment; filename=".$name.".mp3");
readfile($file);
exit();
?>

It will force the download but it will only save the first word in the name that is sent. So say the name is Your Song Here it wants to save it as Your.mp3 but if I remove the str_replace from the $file_name variable then it will try to save the file as Your with no extension but still only the first word.

I need it to pass the entire $file_name variable ex. Your Song Here.mp3 and still save it as an MP3 file.

I am not quite sure what I am doing wrong


Solution

  • Wrap the filename in quotes, something like

    header("Content-Disposition: attachment; filename=\"${name}.mp3\"");
    

    (can't remember how to escape "s in a string in php).

    I believe this is actually required by the HTTP specification.