Skip to content
Advertisement

Generate thumbnail from video using ffmpeg and add to mysql database

Im a noobie in php but still im trying 🙂 Im making bulk video uploader/importer to database. Looking ideas how to extract thumbnails from videos on upload and add those thumbnails to mysql database for each video… :/ Im trying using ffmpeg, but i dont found the way how to implement it to my code…

<?php 
    // Database
    include 'config/database.php'; 

    if(isset($_POST['submit'])){
        
        $url = "localhost/";
        $uploadsDir = "uploads/";
        $allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
        
        // Velidate if files exist
        if (!empty(array_filter($_FILES['fileUpload']['name']))) {
            
            // Loop through file items
            foreach($_FILES['fileUpload']['name'] as $title=>$val){
                // Get files upload path
                $fileName        = $_FILES['fileUpload']['name'][$title];
                $tempLocation    = $_FILES['fileUpload']['tmp_name'][$title];
                $targetFilePath  = $uploadsDir . $fileName;
                $fileType        = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
                $withOutExtension = pathinfo($fileName, PATHINFO_FILENAME);
                $uploadDate      = date('Y-m-d H:i:s');
                $uploadOk = 1;


                if(in_array($fileType, $allowedExts)){
                        if(move_uploaded_file($tempLocation, $targetFilePath)){
                            $sqlVal = $withOutExtension;
                            $sqlVal2 = $url . $uploadsDir . $fileName;
                            $sqlVal3 = null;
                            $randomID = rand(1000, 999999);
                            $sqlVal4 = ('<p><video controls="" src="/' . $sqlVal2 . '" width="640" height="360" class="note-video-clip"></video><br></p>');
                            $slug = str_replace(' ', '-', $withOutExtension);;
                            $file = $uploadsDir . $fileName;
                            $filesize = filesize($file); // bytes
                            $filesize = round($filesize / 1024 / 1024, 1);
                            

                        } else {
                            $response = array(
                                "status" => "alert-danger",
                                "message" => "File coud not be uploaded."
                            );
                        }
                    
                } else {
                    $response = array(
                        "status" => "alert-danger",
                        "message" => "I want mp4 file."
                    );
                }
                // Add into MySQL database
                if(!empty($sqlVal)) {
                    $insert = $conn->query("INSERT INTO applications (id, title, description, custom_description, details, image, slug, file_size, license, developer, url, buy_url, type, votes, screenshots, total_votes, counter, hits, category, platform, must_have, featured, pinned, editors_choice, created_at, updated_at) VALUES ('$randomID', '$sqlVal', 'Video .mp4 Live Wallpaper. Animated wallpaper is a cross between a screensaver and desktop wallpaper. Like a normal wallpaper, an animated wallpaper serves as the background on your desktop, which is visible to you only when your workspace is empty, i.e. no program windows block it from view.', '$sqlVal3', '$sqlVal4', '99999.jpg', '$slug', '$filesize MB', 'free', 'n/a', '$sqlVal2', '$sqlVal3', '1', '0.00', '', '0', '0', '1', '22', '6', '1', '1', '0', '1', '2021-11-11 16:55:36', '2021-11-11 16:55:36')");
                    if($insert) {
                        $response = array(
                            "status" => "alert-success",
                            "message" => "Files successfully uploaded."
                        );
                    } else {
                        $response = array(
                            "status" => "alert-danger",
                            "message" => "Files coudn't be uploaded due to database error."
                        );
                    }
                }
            }

        } else {
            // Error
            $response = array(
                "status" => "alert-danger",
                "message" => "Please select a file to upload."
            );
        }
    } 
    
    
    


?>

Advertisement

Answer

Concerning the FFMpeg part, I think a good way to start is to actually use the PHP-FFMpeg library. The Basic Usage section in the documentation contains an example on how to generate a frame for a given video:

require 'vendor/autoload.php';

$ffmpeg = FFMpegFFMpeg::create();
$video = $ffmpeg->open('video.mpg');

$video->frame(FFMpegCoordinateTimeCode::fromSeconds(10))
      ->save('frame.jpg');

A simplified process would be as follows:

  1. The user uploads a video, after which the video gets moved to a different directory.
  2. Now you can use the snippet above, with the frame method to get a thumbnail for your video.
  3. After the image saving is done, you just need to add it to your database.
    • If the thumbnails refer to the image column in your table, you can get away with just inserting the filename, frame.jpg (or even the complete filepath, /public/path/to/frame.jpg).
    • If the thumbnails refer to the screenshots column in your table, and you want to have multiple thumbnails for your video, then you should consider creating a new table with a one-to-many relationship (from your video/application to a new table, e.g. thumbnails)
  4. Then when the user gets to a page where the image should be displayed, just select it from the table and display it with an <img> tag (with the public filepath).

I would also strongly recommend not to save the complete <video> tag into your database, but instead add it to the page where you actually want to show your video.

Example:

<?php
$result = $conn->query('SELECT ...');
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        ?>
        <video src="<?php echo $row['video-column-path']; ?>"</video>
        <?php
    }
} else {
    ?>
    No videos here
    <?php
}
$conn->close();
?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement