download youtube video with youtube-dl in php

To download YouTube videos with youtube-dl in PHP, you can use the exec() function to execute a command that downloads the video.

First, you need to install youtube-dl on your server. You can do this by running the following command:

main.php
sudo apt-get install youtube-dl
32 chars
2 lines

Once youtube-dl is installed, you can use the following PHP code to download a video from YouTube:

main.php
<?php

$url = 'https://www.youtube.com/watch?v=VIDEO_ID';

// Escape shell arguments
$escaped_url = escapeshellarg($url);

// Build command to be executed
$command = "youtube-dl -f mp4 -o '/path/to/save/%(title)s.%(ext)s' $escaped_url";

// Execute command
exec($command);

echo "Video downloaded successfully.";

?>
317 chars
17 lines

Replace VIDEO_ID with the ID of the YouTube video you want to download, and /path/to/save/ with the path where you want to save the video.

This code downloads the video in MP4 format and saves it with the title of the video as the filename in the specified path.

Note that running shell commands from PHP can be dangerous if not done properly. Make sure to validate the URL and escape any arguments before building the command to avoid command injection vulnerabilities.

related categories

gistlibby LogSnag