4
votes
<?php
$youtubeUrl =  "https://www.youtube.com/watch?v=Ko2JcxecV2E"; 
$content = json_encode ($file = shell_exec("youtube-dl.exe $youtubeUrl "));
$input_string =$content;
$regex_pattern = "/Destination:(.*.mp4)/";
$boolean = preg_match($regex_pattern, $input_string, $matches_out);
$extracted_string=$matches_out[0];

$file =explode(': ',$extracted_string,2)[1];      

// Quick check to verify that the file exists
if( !file_exists($file) ) die("File not found");
// Force the download
header("Content-Disposition: attachment; filename=\"$file\"" );
header("Content-Length: " . filesize($file));
header("Content-Type: application/octet-stream;");
readfile($file);

?>

When I run this file the respective YouTube video is first downloaded to the localhost server folder where this PHP file is, using youtube-dl.exe and then it is pushed from that folder to browser download (forced download).

How to directly start the download to user's browser?

Also the file is running fine on localhost but not on remote server.

2
What is the question? Do you want to make the PHP code start streaming the file to browser immediately, when the youtube-dl.exe starts downloading it, without waiting for the download to finish? - Martin Prikryl
yes kind of.... but not streaming. download shlould start in browser instead of streaming - sky
one question, you accepted the answer by Martin Prikryl what working for me too but how do you create a mp4 file on that on the client side? - DealZg

2 Answers

4
votes

First, you need to use a version of youtube-dl for a platform of your webserver. The youtube-dl.exe is a build for Windows, while most webhostings use Linux.

Then use the passthru PHP function to run the youtube-dl with the -o - command-line parameter. The parameters makes youtube-dl output the downloaded video to its standard output, while the passthru passes the standard output to a browser.

You also need to output the headers before the the passthru. Note that you cannot know the download size in this case.

header("Content-Disposition: attachment; filename=\"...\"" );
header("Content-Type: application/octet-stream");

passthru("youtube-dl -o - $youtubeUrl");

If you need a video metadata (like a filename), you can run the youtube-dl first with the -j command-line parameter to get the JSON data without downloading the video.

Also you need 1) Python interpreter on the web server 2) to be able to use the passthru function 3) connectivity to YouTube from the PHP scripts. All these are commonly restricted on webhostings.

1
votes

The trouble is probably within: shell_exec("youtube-dl.exe $youtubeUrl ")

Firstly, some hosts disable shell_exec for security reasons.

Secondly, youtube-dl.exe looks like it is probably a windows script, where as your remote server is probably Linux based.