I have a site where users have to pay to for downloads of videos they create on the site. Because of this I need to hide the path for the downloads.
I have the php page where the download button is -
<form id="dl_script_form" action="dl-script.php" method="post" target="_blank">
<input name="userID" type="hidden" value="<?php echo $user->ID;?>" />
<input name="videosID" type="hidden" value="<?php echo $vId; ?>" />
<input name="downloadvids" id="downloadvids" type="submit" value="Download"/>
</form>
And on the dl-script.php --
require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php';
global $post;
$userid = $_POST['userID'];
$videosid = $_POST['videosID'];
$nameOld = '/path/to/'.$userid.'/'.$videosid.'/'.$videosid.'.mp4';
$nameNew = "download.mp4";
header('Content-type: video/mp4');
header("Content-disposition: attachment; filename=$nameNew");
header("Content-Length: ".filesize($nameOld));
readfile($nameOld);
exit();
When trying to click submit, a download is started (with the filename as download.mp4) but when I try opening the mp4 in windows media player, it tells me -
Windows Media Player cannot play the file. The Player might not support the file type or might not support the codec that was used to compress the file.
I've checked the file path and was able to play the video in my browser or right click download without a problem.
So with php script the file must be corrupted somehow. I tried adding/removing header content-*
and file_get_contents
, but still no luck.
What am I doing wrong?
EDIT
For testing purposes I modified the code to download from my second server to my original server where I am running the script from.
$userid = $_POST['userID'];
$videosid = $_POST['videosID'];
$path = 'https://path/to/'.$userid.'/'.$videosid.'/'.$videosid.'.mp4';
$save = '/var/path/to/'.$userid.'/'.$videosid.'/'.$videosid.'.mp4';
file_put_contents($save, fopen($path, 'r'));
$nameNew = "download.mp4";
header('Content-type: video/mp4');
header("Content-disposition: attachment; filename=$nameNew");
header("Content-Length: ".filesize($save));
readfile($save);
This however still doesnt download correctly. If I download the file directly though without the script, it works fine.