Managing YouTube with Google Data API

Published in: PHP - YouTube

The Copy YouTube Playlists tool uses Google Data API (PHP) and YouTube API (v3) to clone any public YouTube playlist into the YouTube account of the authorized user.

You need to create your own OAuth2 secret keys from the Google Developer’s Console and also the redirect URL should point to the page where the PHP script is hosted.


    require_once 'php-google-api-client/src/Google_Client.php';
    require_once 'php-google-api-client/src/Google_YouTubeService.php';


    $OAUTH2_CLIENT_ID = '';
    $OAUTH2_CLIENT_SECRET = 'labnol';

    $redirect = "";

    $client = new Google_Client();

    $youtube = new Google_YoutubeService($client);

    if (isset($_GET['code'])) {

        if (strval($_SESSION['state']) !== strval($_GET['state'])) {
            die('The session state did not match.');

        $_SESSION['token'] = $client->getAccessToken();
        header('Location: ' . $redirect);


    if (isset($_SESSION['token'])) {

    if ($client->getAccessToken()) {

            try {

                if ( preg_match('/(PL[A-Za-z0-9_-]+)/', $_POST["url"], $match) ) {

                    $plID = $match[0];
                    $pl_options = array ("id" => $plID, "maxResults" => 1);
                    $playlistDetails = $youtube->playlists->listPlaylists("snippet", $pl_options);

                    if ( $playlistDetails["pageInfo"]["totalResults"] == 1 ) {

                        $options = array ("playlistId" => $plID, "maxResults" => 50);
                        $videos = "";

                        do {

                            $playlist = $youtube->playlistItems->listPlaylistItems("snippet", $options);
                            $nextPageToken = $playlist["nextPageToken"];
                            $options["pageToken"] = $nextPageToken;

                            foreach ($playlist["items"] as $playlistItem) {
                                $videos .=  $playlistItem["snippet"]["resourceId"]["videoId"] . "#";

                        } while ($nextPageToken);

                        $playlistSnippet = new Google_PlaylistSnippet();

                        $playlistStatus = new Google_PlaylistStatus();

                        $youTubePlaylist = new Google_Playlist();

                        $playlistResponse = $youtube->playlists->insert('snippet,status', $youTubePlaylist, array());

                        $ids = explode ( "#", $videos ) ;

                        for ($i=0; $i<count($ids); $i++) {

                            $resourceId = new Google_ResourceId();

                            $playlistItemSnippet = new Google_PlaylistItemSnippet();

                            $playlistItem = new Google_PlaylistItem();

                            $playlistItemResponse = $youtube->playlistItems->insert('snippet,contentDetails', $playlistItem, array());




            } catch (Google_ServiceException $e) {
                $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
            } catch (Google_Exception $e) {
                $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',

        } else {

            $htmlBody = <<<END
    <form method="post">
      <input type="text" name="url" id="url">
      <button type="submit">Copy Playlist to YouTube</button>


        $_SESSION['token'] = $client->getAccessToken();

    } else {

        $state = mt_rand();
        $_SESSION['state'] = $state;

        $authUrl = $client->createAuthUrl();
        $htmlBody = <<<END
                <p><a href="$authUrl">Step 1: Sign-in with YouTube</a></p>

<?= $htmlBody; ?>

📮  Subscribe to our Email Newsletter for Google tips and tutorials!
Published in: PHP - YouTube

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
Amit Agarwal

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch

Google Add-ons

Do more with your Gmail and GSuite account

We build bespoke solutions that use the capabilities and the features of Google Workspace for automating business processes and driving work productivity.

  1. Mail Merge with Attachments
    Send personalized email to your Google Contact with a Google Sheet and Gmail
  2. Save Emails and Attachments
    Download email messages and file attachments from Gmail to your Google Drive
  3. Google Forms Email Notifications
    Send email notifications to multiple people when a new Google Form is submitted
  4. Document Studio
    Create beautiful pixel perfect documents merging data from Google Sheets and Google Forms
  5. Creator Studio for Google Slides
    Turn your Google Slides presentations into animated GIFs and videos for uploading to YouTube