download youtube video in php

One way to download a YouTube video in PHP is using a library such as youtube-dl. You can use exec() or the Process component from Symfony to execute the command-line tool.

Here is an example implementation that downloads a video from YouTube given its URL:

main.php
$videoUrl = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
$outputDir = '/path/to/download/directory';

// Download video using youtube-dl
$cmd = sprintf('youtube-dl %s -o %s', $videoUrl, $outputDir);
exec($cmd);

// Check download directory for video file
$videoFile = sprintf('%s/%s.*', $outputDir, $videoId);
$downloaded = count(glob($videoFile)) > 0;

if ($downloaded) {
  echo 'Video downloaded successfully!';
} else {
  echo 'Failed to download video.';
}
463 chars
17 lines

This code assumes that youtube-dl is installed and available on the system. You can install it using apt-get install youtube-dl (on Debian-based systems) or by downloading the binary from the official repository: https://github.com/ytdl-org/youtube-dl. The code also assumes that the user running the script has sufficient permissions to access the output directory.

related categories

gistlibby LogSnag