<?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);
?>
当我运行此文件时,相应的YouTube视频首先使用youtube-dl.exe
下载到此PHP文件所在的本地主机服务器文件夹,然后将其从该文件夹推送到浏览器下载(强制下载)。
如何直接开始下载到用户的浏览器?
此外,该文件在本地主机上运行良好,但在远程服务器上运行不正常。
首先,您需要将youtube-dl版本用于网络服务器平台。该youtube-dl.exe
是Windows的构建,而大多数虚拟主机使用Linux。
然后使用 passthru
PHP 函数运行带有-o -
命令行参数的youtube-dl
。这些参数使youtube-dl
下载的视频输出到其标准输出,而passthru
将标准输出传递给浏览器。
您还需要在passthru
之前输出标头。请注意,在这种情况下,您无法知道下载大小。
header("Content-Disposition: attachment; filename='"...'"" );
header("Content-Type: application/octet-stream");
passthru("youtube-dl -o - $youtubeUrl");
如果需要视频元数据(如文件名),可以先使用 -j
命令行参数运行youtube-dl
以获取 JSON 数据,而无需下载视频。
你还需要 1)Web服务器上的Python解释器2)能够使用passthru
功能3)从PHP脚本连接到YouTube。所有这些通常都限制在虚拟主机上。
问题可能出在: shell_exec("youtube-dl.exe $youtubeUrl ")
首先,某些主机出于安全原因禁用shell_exec。
其次,youtube-dl.exe看起来它可能是一个Windows脚本,因为你的远程服务器可能是基于Linux的。