download youtube video with curl in php

You can download a YouTube video using cURL in PHP by making a GET request to the video's URL and then saving the response in a file. Here's an example code snippet:

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

// Initialize cURL
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Get the video content
$response = curl_exec($ch);

// Close cURL
curl_close($ch);

// Save the video content to a file
$file = fopen('video.mp4', 'w');
fwrite($file, $response);
fclose($file);
406 chars
21 lines

Replace VIDEO_ID with the actual ID of the video you want to download. The code will save the video content in a file named video.mp4 in the same directory as the PHP script.

Note that downloading YouTube videos can be against YouTube's terms of service, and you should ensure that you have the necessary rights to download and use the video before doing so.

related categories

gistlibby LogSnag