DEV Community

Cover image for View embedded videos from youtube, vimeo and google drive
Walter Nascimento
Walter Nascimento

Posted on

View embedded videos from youtube, vimeo and google drive

I had to make a small adjustment that was necessary that whenever the user entered a new url, I would adjust it to the valid format of youtube and vimeo, and in that I thought it takes a little work, so to make the next one easier, I'll leave the code ready here.

CODE

FrontEnd

For the interface you can just use the html iframe

<iframe width="100%" height="460" 
src="{{url}}"
title="Video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
Enter fullscreen mode Exit fullscreen mode

💡 NOTE: In the src property is where we apply our formatted URL

BackEnd

For the back end you just need a simple method.

public function formatUrl($url)
{
        $urlParse = parse_url($url);
        // Extract id from youtube url
        if (strpos($urlParse["host"], 'youtube') !== false) {
            if (isset($urlParse["query"])) {
                parse_str($urlParse["query"], $query);
                return "https://www.youtube.com/embed/" . $query["v"];
            }
            $id = explode("/", $urlParse["path"]);
            return "https://www.youtube.com/embed/" . end($id);
        }
        // Extract id from vimeo url
        if (strpos($urlParse["host"], 'vimeo') !== false) {
            $urlParse = explode("/", $urlParse["path"]);
            return "https://player.vimeo.com/video/" . $urlParse[1];
        }
        // Extract id from google drive url
        if (strpos($urlParse["host"], 'drive.google') !== false) {
            $urlParse = explode("/", $urlParse["path"]);
            $urlParse = array_values(array_filter($urlParse));
            return "https://drive.google.com/file/d/" . $urlParse[2] . "/preview";
        }
}
Enter fullscreen mode Exit fullscreen mode

That's it

Extra

If you want the full php class, follow it below.


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
😊😊 See you! 😊😊


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso

Latest comments (0)