Jonathan Luke
Jonathan Luke

Reputation: 55

How to initiate download of mp4 from url (and prevent the mp4 from playing in the browser)?

I am trying to initiate the download of an mp4 file that is located at a url (I do not have access to the file itself). I do not want the video to play in the browser, and I do not want the user to have to leave the web page.

I have tried creating an <a> element and using the download attribute, but it has to be compatible with IE, which doesn't support the download attribute, so that is not viable.

I have tried window.open('https://example.com/file-name.mp4');, but some browsers will simply start playing the video in a new tab instead of downloading it.

I have also tried window.open('https://mywebsite.com/download.php?file-id'); where the download.php file checks to make sure the user is authorized to download the file, formats the url, sets Content-Type and Content-Disposition headers, and ends with readfile($file_url);. This works well except, on failure, the download.php page remains open. I would rather be able to display an error message on the original page than have to set up an error page for download.php.

I tried to use the above method with an AJAX call to avoid the redirect problem, but I cannot figure out how to take the response and start the download with it.

How can I initiate the download of the mp4 file without the chance of it playing in the browser or redirecting to another web page?

Upvotes: 2

Views: 1217

Answers (1)

SSpoke
SSpoke

Reputation: 5836

<?php
set_time_limit(0);
$file = 'file-name.mp4';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    if(!readfile($file)) {
       echo "error occured!";
    }
    exit;
} else {
    echo "Error file not found";
}
?>

Upvotes: 1

Related Questions