0
votes

I'm downloading a file through php script and everything work perfectly except one ugly truth. The downloaded file keep the same url and with original name appended. How do I maintain the same filename when file downloaded?

http://bachday.com/index.php?page=custom&file=mmailer/download.php?mfile=sample.docx
if (isset($_GET['mfile'])) {
    $file = $_SERVER['DOCUMENT_ROOT'].'/oc-content/plugins/mmailer/pfile/'.$_GET['mfile'];

    if (file_exists($file) && is_readable($file) && preg_match('/\.docx$/',$file)) {
        header('Content-Type: application/docx');
    header("Content-Disposition: attachment; filename=\"$file\"");
    readfile($file);
    /*
    header("Expires: 0");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
    echo (readfile($file));*/


    }
    else
    {
        header("HTTP/1.0 404 Not Found");
        echo "Error 404: File Not Found: 
$file"; }
3
try this code. header("Content-Disposition: attachment; filename={$name}.{$file_ending}"); the difference is in concatenating.Dipesh Parmar

3 Answers

3
votes

header('Content-Disposition: attachment; filename="name_of_file_here"') would have done the trick. You are passing the full path of the file there as header("Content-Disposition: attachment; filename=\"$file\""); since your $file contains full path. Instead just send the name of the file.

1
votes

header('Content-Disposition: attachment; filename='.basename($file));

This line can perhaps solve the issue.

0
votes
if (isset($_GET['mfile'])) {
    $file = $_SERVER['DOCUMENT_ROOT'].'/oc-content/plugins/mmailer/pfile/'.$_GET['mfile'];

    if (file_exists($file) && is_readable($file) && preg_match('/\.docx$/',$file)) {
        header('Content-Type: application/docx');
    header("Content-Disposition: attachment; filename=\"".basename($file)."\"");//use basename to extract filename from full file path
    readfile($file);
    /*
    header("Expires: 0");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
    echo (readfile($file));*/


    }
    else
    {
        header("HTTP/1.0 404 Not Found");
        echo "Error 404: File Not Found: 
$file";
    }