本文介绍了通过浏览器将 YouTube 视频文件直接下载到用户的计算机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?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 文件所在的 localhost 服务器文件夹,然后将其从该文件夹推送到浏览器下载(强制下载).

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.

推荐答案

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

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.

然后使用passthru使用 youtube-dl 的 PHP 函数rel="nofollow noreferrer">-o - 命令行参数.参数使 youtube-dl 将下载的视频输出到其标准输出,而 passthru 将标准输出传递给浏览器.

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.

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

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");

如果您需要视频元数据(如文件名),您可以先使用 -j 命令行参数运行 youtube-dl 以获取 JSON 数据无需下载视频.

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.

您还需要 1) 网络服务器上的 Python 解释器 2) 能够使用 passthru 功能 3) 从 PHP 脚本连接到 YouTube.所有这些通常都在网站托管上受到限制.

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.

这篇关于通过浏览器将 YouTube 视频文件直接下载到用户的计算机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 20:47