Skip to content
PHP Logo

How can PHP be used to download a Twitch clip?

To download a Twitch clip using PHP, you can make use of the Twitch API to retrieve the clip URL and then use PHP to download the clip to your server. You will need to make an API request to get the clip URL and then use PHP's `file_put_contents` function to save the clip to a file on your server.

php
<?php
$clip_id = "YOUR_CLIP_ID";
$api_url = "https://api.twitch.tv/helix/clips?id=$clip_id";
$api_headers = array(
    'Client-ID: YOUR_CLIENT_ID',
    'Authorization: Bearer YOUR_ACCESS_TOKEN'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $api_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);
$data = json_decode($response, true);

if(isset($data['data'][0]['thumbnail_url'])) {
    $clip_url = str_replace('-preview-480x272.jpg', '.mp4', $data['data'][0]['thumbnail_url']);
    $clip_data = file_get_contents($clip_url);
    file_put_contents("downloaded_clip.mp4", $clip_data);
    echo "Clip downloaded successfully!";
} else {
    echo "Error downloading clip.";
}

curl_close($ch);
?>