Download the YouTube video file directly to user's computer through browser

我是研究僧i 提交于 2019-12-21 21:43:41

问题


<?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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/29074295/download-the-youtube-video-file-directly-to-users-computer-through-browser

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!