Created
July 27, 2024 09:53
-
-
Save laxmariappan/69df42ddfd92b2e10df5a054b06c9a3b to your computer and use it in GitHub Desktop.
Download video from Pixabay using PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Downloads the publicly accessible videos. | |
* This is just a basic demo, can be improved with proper file handling. | |
* | |
* @param string $video_url Video URL. | |
* @param string $referer Referer site. | |
*/ | |
function download_video( $video_url, $referer ) { | |
$video_name = basename( $video_url ); | |
$video_path = '/' . $video_name; // Path to downloads folder. | |
try { | |
$ch = curl_init($video_url); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, [ | |
'Origin: ' . $referer, | |
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' | |
]); | |
curl_setopt($ch, CURLOPT_REFERER, $referer); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); | |
$video = curl_exec($ch); | |
if (curl_errno($ch)) { | |
throw new Exception('Error: ' . curl_error($ch)); | |
} else { | |
$file = fopen($video_path, 'w'); | |
if ($file === false) { | |
throw new Exception('Failed to open file for writing.'); | |
} | |
fwrite($file, $video); | |
fclose($file); | |
echo "Video downloaded successfully."; | |
} | |
curl_close($ch); | |
} catch (Exception $e) { | |
echo $e->getMessage(); | |
} | |
} | |
/** | |
* How to use it? | |
*/ | |
download_video( 'https://cdn.pixabay.com/video/2022/11/22/140111-774507949_large.mp4', 'https://pixabay.com/' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment