php - 通过浏览器将 YouTube 视频文件直接下载到用户计算机

标签 php youtube tcp

<?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-dl.exe 将相应的 YouTube 视频下载到此 PHP 文件所在的本地主机服务器文件夹,然后将其从该文件夹推送到浏览器下载(强制下载)。

如何直接开始下载到用户的浏览器?

此外,该文件在本地主机上运行良好,但在远程服务器上运行不正常。

最佳答案

首先,您需要为您的网络服务器平台使用一个版本的 youtube-dl。 youtube-dl.exe 是为 Windows 构建的,而大多数虚拟主机使用 Linux。

然后使用 passthru使用 -o - command-line parameter 运行 youtube-dl 的 PHP 函数.这些参数使 youtube-dl 将下载的视频输出到其标准输出,而 passthru 将标准输出传递到浏览器。

您还需要在 passthru 之前输出 header 。请注意,在这种情况下您无法知道下载大小。

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。所有这些通常都限制在虚拟主机上。

关于php - 通过浏览器将 YouTube 视频文件直接下载到用户计算机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29074295/

相关文章:

sockets - tcp 服务器和客户端交互

ruby - 通过ruby TCP Socket接收大量数据时出现问题

php - 通过php无表单提交数据到Mysql

php - 使用 class.upload.php 编辑上传的图像

PHP 正则表达式组捕获

javascript - 尝试从 YouTube &lt;iframe&gt; 捕获 console.log 消息

php - mysql_fetch_assoc 函数替换

google-chrome-extension - 我无法在Chrome扩展程序上播放youtube chromeless播放器

javascript - 在 Chrome 中的页面标题右侧插入图标

c socket发送大文件时出现broken pipe错误