How to upload video to bunyy.net using API PHP

392 Views Asked by At

I'm trying to upload video to my library on bunny cdn using API but I can't find how to upload it. In their docs you I can't find how to upload the video only create a title for the video but no upload the video its self.

Here is the API request from the docs

<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('PUT', 'https://video.bunnycdn.com/library/libraryId/videos/videoId', [
  'headers' => [
    'accept' => 'application/json',
  ],
]);

echo $response->getBody();

I have found here that you have to create a video first and this ok but the part of uploading the video content is not the same. You can see they add a link to the docs but its not the same same as in the image as there is a upload video button in the image but in the docs there isn't.

The image from bunny support webste

2

There are 2 best solutions below

0
On

The Bunny API is really poorly documented, I spent a lot of time figuring out how to make it work:

Let's move forward step by step. First of all we must select the file to upload: below is the html code to do so:

index.html

<form id="uploadForm" enctype="multipart/form-data">
  <input type="file" name="videoFile" accept="video/*">
  <progress value="0" max="100" id="progressBar"></progress>
  <button type="button" onclick="uploadVideo()">Upload Video</button>
</form>

I also included a progress bar to visually display the upload progress. As you can see there is an onclick action with a javascript function to handle the loading. Also include jQuery to handle the upload

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

then the function

function uploadVideo() {
        const formData = new FormData(document.getElementById('uploadForm'));

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            xhr: function () {
                const xhr = new XMLHttpRequest();
                xhr.upload.addEventListener('progress', function (event) {
                    if (event.lengthComputable) {
                        const percent = (event.loaded / event.total) * 100;
                        $('#progressBar').val(percent);
                    }
                }, false);
                return xhr;
            },
            success: function (data) {
                alert('Video uploaded successfully!');
                $('#progressBar').val(0);
            },
            error: function () {
                alert('Error uploading video. Please try again.');
                $('#progressBar').val(0);
            }
        });
    }

upload.php

$apiKey = "your-library-api-key"; //the library apiKey
$libraryId = "the-library-id";
$file = $_FILES['videoFile']['tmp_name'];
$videoName = "the-name-of-the-video";

function upload_video($video_path, $auth_key, $library_id, $video_name) {
  $base_url = "https://video.bunnycdn.com/library/";

  // Initialize cURL session
  $ch = curl_init();

//first of all we have to create the video

  // Set cURL options
  curl_setopt($ch, CURLOPT_URL, $base_url . $library_id . "/videos");
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array("title" => $video_name)));
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "AccessKey: " . $auth_key,
    "Content-Type: application/json"
  ));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // Execute cURL request
  $response = curl_exec($ch);

  // Close cURL session
  curl_close($ch);

  // Check if video create was successful
  //then begin the upload process
  if ($response !== false) {
    // Initialize cURL session
    $ch = curl_init();

    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $base_url . $library_id . "/videos/" . json_decode($response)->guid);
    curl_setopt($ch, CURLOPT_PUT, 1);
    curl_setopt($ch, CURLOPT_INFILE, fopen($video_path, "rb"));
    curl_setopt($ch, CURLOPT_INFILESIZE, filesize($video_path));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      "AccessKey: " . $auth_key
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Execute cURL request
    $response = curl_exec($ch);

    // Close cURL session
    curl_close($ch);

    // Check if upload was successful
    if ($response !== false) {
      return true;
    }
  }

  return false;
}


$response = upload_video($file, $apiKey, $libraryId, $videoName);
//get the bunny response
echo $response;

I hope I have been helpful. However with this code I have some problems with files larger than 100Mb. I'm still trying to figure out why.

0
On

Upload it as a raw file not an encoded one. This is from a laravel PHP and it worked for me. You can also test it in postman and set the Headers with the AccessKey and Go to Body and choose Binary and upload a video e.g mp4.

$fileData = file_get_contents($request->file('video')->getRealPath());

$uploadResponse = Http::withHeaders($uploadHeaders)
    ->withBody($fileData, 'application/json')
    ->put($apiEndpoint);

if ($uploadResponse->successful()) {
    return response($uploadResponse->body())->header('Content-Type',
    $uploadResponse->header('Content-Type'));
} else {
    return response()->json(['error' => 'File upload failed'], $uploadResponse->status());
}