Upload video on youtube without client authentication using codeigniter

Here we are going to create a form in codeigniter using this form we can upload video on youtube without authentication.
- download library from following link  and copy src folder place it in libraries folder.
https://github.com/sameerpspaceo/Youtube_Demo

step 1)
go to google console link where you have to create a project
https://console.developers.google.com/apis

Step 2)
- create new project
- go to library tab
- enable libraries
- YouTube Data API v3, YouTube Analytics API, Gmail API, Google+ API, Google Calendar API

Step 3)
- create credentials for new project
- click on oAuth Client ID.
- select Web application from Application type.
- give your auth oAuth name
- enter you controller Authorized redirect URIs.
Auth Redirect Url
ex:- http://localhost/example/youtube_controller/youtube_upload
- and save it
- copy your Client ID and Client secret.







Step 4)
- if you want to upload video without client authentication you have to follow below steps.
- create the_key.txt file in application folder. This file will save access_token,refresh_token and other details
- create youtubeUpload.log in the root directory to save logs.
- or if not than comment

$key = file_get_contents(APPPATH.'the_key.txt'); 
$client->setAccessToken($key);
$fp = fopen(APPPATH.'the_key.txt', 'w');
fwrite($fp, $json);
fclose($fp);

- create youtubeDelete.log file in application folder.this file will save delete logs

Youtube_controller.php



<?php

class Youtube_controller extends CI_Controller
{
 public function __construct()
 {
        parent::__construct();
  $this->load->library('session');
  $this->load->helper('url');
  $this->load->helper('form');
  $this->load->model('user_model');
    }

 /* create function to upload video first on local server and than upload on youtube after successfully upload unlink local server video to clean up space */
 
 function youtube_upload(){
  
  $userId = $this->session->userId;
  /* add client id here */
  $oauthClientID = '*******************************************.apps.googleusercontent.com';

  /* add client secret id here */
  $oauthClientSecret = '****************';
  $baseUri = base_url();

  /* add redirect link as you use in Authorized redirect URIs. */
  $redirectUri = base_url().'en/youtube_controller/youtube_upload';
  
  define('OAUTH_CLIENT_ID',$oauthClientID);
  define('OAUTH_CLIENT_SECRET',$oauthClientSecret);
  define('REDIRECT_URI',$redirectUri);
  define('BASE_URI',$baseUri);
    
  require_once(APPPATH.'libraries/src/autoload.php');
  require_once(APPPATH.'libraries/src/Client.php');
  require_once(APPPATH.'libraries/src/Service/YouTube.php');
  
  $key = file_get_contents(APPPATH.'the_key.txt');
  
  $client = new Google_Client();
  $client->setClientId(OAUTH_CLIENT_ID);
  $client->setClientSecret(OAUTH_CLIENT_SECRET);
  $client->setAccessToken($key);
  $client->setScopes('https://www.googleapis.com/auth/youtube');
  $client->setRedirectUri(REDIRECT_URI);
  $client->setAccessType('offline');
  $client->setApprovalPrompt('force');
  
  $youtube = new Google_Service_YouTube($client);
  
  $videoTitle = $this->input->post('title');
  $videoDesc = $this->input->post('description');
  $videoTags = $this->input->post('tags');
  
  $tag = array_filter( explode(",", $videoTags) );
  
  $videoTags = implode(',',$tag);
  
  if(isset($_FILES)){
  
   if($_FILES["videoFile"]["name"] != ''){
    
    $user_folder = './upload/youtube_video/'.$userId;
    if(!is_dir($user_folder)){
     mkdir($user_folder, 0777);
    }
    
    $VideoName = str_replace(' ', '_', $_FILES['videoFile']['name']);
    
    $configVideo['upload_path'] = $user_folder; # check path is correct
    $configVideo['allowed_types'] = 'mp4|mpeg|mpg|mov|wmv|avi'; # add video extenstion on here
    $configVideo['overwrite'] = FALSE;
    $configVideo['remove_spaces'] = TRUE;
    $video_name = $userId.'_'.time().'_'.$VideoName;
    $configVideo['file_name'] = $video_name;
    
    $this->load->library('upload', $configVideo);
    $this->upload->initialize($configVideo);

    if (!$this->upload->do_upload('videoFile')) # form input field attribute
    {
     $this->session->set_flashdata('error', $this->upload->display_errors());
     redirect('youtube_controller/upload_video');
    }
    else
    {
     $url = 'upload/youtube_video/'.$userId.'/'.$video_name;
     $upload_video = array('pv_userId'=>$userId,'pv_video_title'=>$videoTitle,'pv_video_description'=>$videoDesc,'pv_video_tags' =>$videoTags,'pv_video_path'=>$url,'pv_updatedBy'=>$userId,'pv_createdDtm'=>date('Y-m-d H:i:s'),'pv_updatedDtm'=>date('Y-m-d H:i:s'));
     
     $result = $this->user_model->upload_youtube_video($upload_video);
     
     $this->session->set_userdata('uploaded_video',$result);
     
    }
   }
  }
  
  $_SESSION['token'] = $client->getAccessToken();
  
  if (isset($_GET['code'])) {
   /* if (strval($_SESSION['state']) !== strval($_GET['state'])) {
     die('The session state did not match.');
   } */

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

   header('Location: ' . REDIRECT_URI);
  }

  if (isset($_SESSION['token'])) {
   $client->setAccessToken($_SESSION['token']);
   $json = $_SESSION['token'];
   
   $fp = fopen(APPPATH.'the_key.txt', 'w');
   fwrite($fp, $json);
   fclose($fp);
  }
  
  $htmlBody = '';
  
  // Check to ensure that the access token was successfully acquired.
  if ($client->getAccessToken()) {
   
   try{
    
    $uploadedVideoId = $this->session->userdata('uploaded_video');
    $result = $this->user_model->lastUploadedVideo($uploadedVideoId);
        
   // REPLACE this value with the path to the file you are uploading.
   $videoPath = $result[0]->pv_video_path;
   
   // Create a snippet with title, description, tags and category ID
   // Create an asset resource and set its snippet metadata and type.
   // This example sets the video's title, description, keyword tags, and
   // video category.
   $snippet = new Google_Service_YouTube_VideoSnippet();
   $snippet->setTitle($result[0]->pv_video_title);
   $snippet->setDescription($result[0]->pv_video_description);
   //$snippet->setTags(explode(",",$result[0]->pv_video_tags));
   $snippet->setTags($result[0]->pv_video_tags);
   //$snippet->setTags('soccer');

   // Numeric video category. See
   // https://developers.google.com/youtube/v3/docs/videoCategories/list 
   $snippet->setCategoryId("22");

   // Set the video's status to "public". Valid statuses are "public",
   // "private" and "unlisted".
   $status = new Google_Service_YouTube_VideoStatus();
   $status->privacyStatus = "public";
 
   // Associate the snippet and status objects with a new video resource.
   $video = new Google_Service_YouTube_Video();
   $video->setSnippet($snippet);
   $video->setStatus($status);

   // Specify the size of each chunk of data, in bytes. Set a higher value for
   // reliable connection as fewer chunks lead to faster uploads. Set a lower
   // value for better recovery on less reliable connections.
   $chunkSizeBytes = 1 * 1024 * 1024;

   // Setting the defer flag to true tells the client to return a request which can be called
   // with ->execute(); instead of making the API call immediately.
   $client->setDefer(true);

   // Create a request for the API's videos.insert method to create and upload the video.
   $insertRequest = $youtube->videos->insert("status,snippet", $video);
   
   // Create a MediaFileUpload object for resumable uploads.
   $media = new Google_Http_MediaFileUpload(
    $client,
    $insertRequest,
    'video/*',
    null,
    true,
    $chunkSizeBytes
   );
   
   $media->setFileSize(filesize($videoPath));
   
   
   // Read the media file and upload it.
   $status = false;
   $handle = fopen( FCPATH.$videoPath, "rb");
    
   while (!$status && !feof($handle)) {
     $chunk = fread($handle, $chunkSizeBytes);
     
     $status = $media->nextChunk($chunk);
   }
   fclose($handle);
   
   // If you want to make other calls after the file upload, set setDefer back to false
   $client->setDefer(false);
   
   // Update youtube video ID to database
   //$db->update($result['video_id'],$status['id']);
   $youtube_video_key = $status['id'];
   $videoId =  $uploadedVideoId;
   
   $videoKey = $this->user_model->youtube_videoID($videoId,$youtube_video_key); 
   
   // delete video file from local folder
   unlink(FCPATH.$videoPath);
   
   $htmlBody .= "<p class='succ-msg'>Video have been uploaded successfully.</p><ul>";
   $htmlBody .= '<embed width="400" height="315" src="https://www.youtube.com/embed/'.$status['id'].'"></embed>';
   $htmlBody .= '</ul>';
      
   $content = file_get_contents("php://input");
   $post = $status;
   $fp = fopen("youtubeUpload.log","a+");
   fwrite($fp,"\n\n\n");
   fwrite($fp,"=====================".date('Y-m-d H:i:s')."===========================");
   fwrite($fp,ob_get_clean());
   fwrite($fp,"\n\n\n");
   ob_start();
   print_r($post);
   fwrite($fp,ob_get_clean());
   fwrite($fp,"\n\n");
   fwrite($fp,"================================================");
   fwrite($fp,"\n\n\n");
   fclose($fp);
   
   $this->session->set_flashdata('video_upload', 'Video have been uploaded successfully');
   redirect("youtube_controller/player_video_list");
   
    } catch (Google_ServiceException $e) {
   /* $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
    htmlspecialchars($e->getMessage())); */
    
    $uploadedVideoId = $this->session->userdata('uploaded_video');
    $result = $this->user_model->lastUploadedVideo($uploadedVideoId);
    
    $videoPath = $result[0]->pv_video_path;
    unlink(FCPATH.$videoPath);
    
    $content = file_get_contents("php://input");
    $post = $e->getMessage();
    $fp =fopen("youtubeUpload.log","a+");
    fwrite($fp,"\n\n\n");
    fwrite($fp,"=====================".date('Y-m-d H:i:s')."===========================");
    fwrite($fp,ob_get_clean());
    fwrite($fp,"\n\n\n");
    ob_start();
    print_r($post);
    fwrite($fp,ob_get_clean());
    fwrite($fp,"\n\n");
    fwrite($fp,"================================================");
    fwrite($fp,"\n\n\n");
    fclose($fp);
    
    $this->session->set_flashdata('video_upload_error', $e->getMessage());
    redirect("youtube_controller/upload_video");
    
    } catch (Google_Exception $e) {
   /*$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
    $htmlBody .= 'Please reset session <a href="'.BASE_URI.'en/youtube_controller/reset_youtube_upload_session">Logout</a>'; */
   
    $uploadedVideoId = $this->session->userdata('uploaded_video');
    $result = $this->user_model->lastUploadedVideo($uploadedVideoId);
    
    $videoPath = $result[0]->pv_video_path;
    unlink(FCPATH.$videoPath);
   
    $content = file_get_contents("php://input");
    $post = $e->getMessage();
    $fp =fopen("youtubeUpload.log","a+");
    fwrite($fp,"\n\n\n");
    fwrite($fp,"=====================".date('Y-m-d H:i:s')."===========================");
    fwrite($fp,ob_get_clean());
    fwrite($fp,"\n\n\n");
    ob_start();
    print_r($post);
    fwrite($fp,ob_get_clean());
    fwrite($fp,"\n\n");
    fwrite($fp,"================================================");
    fwrite($fp,"\n\n\n");
    fclose($fp);
    
    $this->session->set_flashdata('video_upload_error', $e->getMessage());
    redirect("youtube_controller/upload_video"); 
    }
    
  }else{
   // If the user hasn't authorized the app, initiate the OAuth flow
   $state = mt_rand();
   $client->setState($state);
   $_SESSION['state'] = $state;
    
   $authUrl = $client->createAuthUrl();
   $htmlBody = "<h3>Authorization Required</h3>
   <p>You need to <a href='".$authUrl."'>authorize access</a> before proceeding.<p>";
   $this->session->set_flashdata('video_upload_error', $htmlBody);
   redirect("youtube_controller/upload_video");
  }
  
  $this->isFrontLoggedIn();
  
  $currentURL = $this->uri->segment(3);
  $this->lang->load('label');
  
  $userId = $this->session->userId;
  
  $data['userDetail'] = $this->user_model->getUserDetail($userId);
  $data['clang'] = $this->uri->segment(1);
  $data['userInfo'] = $this->user_model->getUserInfo($userId);
  $data['youtube_response'] = $htmlBody;
  
  $this->load->view('includes/header',$data);
  $this->load->view('validation_msg');
  $this->load->view('myaccount_sidebar',$data);
  $this->load->view('upload_video',$data);
  $this->load->view('includes/footer',$data);
 }
 
 /* Delete uploaded video with youtube video key used ajax to delete video
    call this function from video list and pass videoId and uploader id from form
*/
 
 function delete_uploadVideo(){
  
  $this->isFrontLoggedIn();
  $userId = $this->session->userId;
  
  /* get video Id from your post */
  $videoId = $this->input->post('videoId');
  
  /* check from database posted videoId is uploaded by user or not */
  $videoStatus = $this->user_model->checkVideoUploader($videoId,$userId);
  
  if(empty($videoStatus)){
   $response['code'] = '0';
   $response['msg'] = 'You are not uploader of this video';
   
   echo json_encode($response);
   die;
  }
  
  $oauthClientID = '**********************************.apps.googleusercontent.com';
  $oauthClientSecret = '**********************';
  $baseUri = base_url();
  $redirectUri = base_url().'en/youtube_controller/youtube_upload';
  
  define('OAUTH_CLIENT_ID',$oauthClientID);
  define('OAUTH_CLIENT_SECRET',$oauthClientSecret);
    
  require_once(APPPATH.'libraries/src/autoload.php');
  require_once(APPPATH.'libraries/src/Client.php');
  require_once(APPPATH.'libraries/src/Service/YouTube.php');
  
  $key = file_get_contents(APPPATH.'the_key.txt');
  
  $client = new Google_Client();
  $client->setClientId(OAUTH_CLIENT_ID);
  $client->setClientSecret(OAUTH_CLIENT_SECRET);
  $client->setAccessToken($key);
  $client->setScopes('https://www.googleapis.com/auth/youtube');
  $client->setAccessType('offline');
  $client->setApprovalPrompt('force');
  
  $youtube = new Google_Service_YouTube($client);
  
  $_SESSION['token'] = $client->getAccessToken();
  
  if (isset($_GET['code'])) {
   // if (strval($_SESSION['state']) !== strval($_GET['state'])) {
   //  die('The session state did not match.');
   //} 

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

   header('Location: ' . REDIRECT_URI);
  }

  if (isset($_SESSION['token'])) {
   $client->setAccessToken($_SESSION['token']);
   $json = $_SESSION['token'];
  }
  
  if ($client->getAccessToken()) {
   
   try{
    
    error_reporting(0);
    
    $youtube->videos->delete($videoId);
    
    $videoDetail = array('pv_isDeleted'=>'1','pv_updatedBy'=>$userId,'pv_updatedDtm'=>date('Y-m-d H:i:s'));
  
    $videoKey = $this->user_model->deleteYoutube($videoId,$videoDetail);
    
    $videoDeleted = array();
    $videoDeleted['video_id'] = $videoId;
    $videoDeleted['deletedBy'] = $userId;
    $videoDeleted['time'] = date('Y-m-d H:i:s');
       
    
    $content = file_get_contents("php://input");
    $post = $videoDeleted;
    $fp =fopen("youtubeDelete.log","a+");
    fwrite($fp,"\n\n\n");
    fwrite($fp,"=====================".date('Y-m-d H:i:s')."===========================");
    fwrite($fp,ob_get_clean());
    fwrite($fp,"\n\n\n");
    ob_start();
    print_r($post);
    fwrite($fp,ob_get_clean());
    fwrite($fp,"\n\n");
    fwrite($fp,"================================================");
    fwrite($fp,"\n\n\n");
    fclose($fp);
    
    $response['code'] = '1';
    $response['msg'] = 'Video deleted successfully';
    
    echo json_encode($response);
    die;
   
   }catch (Google_ServiceException $e) {
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
    $e->getMessage());
    
    $content = file_get_contents("php://input");
    $post = $htmlBody;
    $fp =fopen("youtubeDelete.log","a+");
    fwrite($fp,"\n\n\n");
    fwrite($fp,"=====================".date('Y-m-d H:i:s')."===========================");
    fwrite($fp,ob_get_clean());
    fwrite($fp,"\n\n\n");
    ob_start();
    print_r($post);
    fwrite($fp,ob_get_clean());
    fwrite($fp,"================================================");
    fwrite($fp,"\n\n\n");
    fclose($fp);
    
    $response['code'] = '0';
    $response['msg'] = $e->getMessage();
    
    echo json_encode($response);
    die;
    
    
   }catch (Google_Exception $e) {
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', $e->getMessage());
    
    $content = file_get_contents("php://input");
    $post = $htmlBody;
    $fp =fopen("youtubeDelete.log","a+");
    fwrite($fp,"\n\n\n");
    fwrite($fp,"=====================".date('Y-m-d H:i:s')."===========================");
    fwrite($fp,ob_get_clean());
    fwrite($fp,"\n\n\n");
    ob_start();
    print_r($post);
    fwrite($fp,ob_get_clean());
    fwrite($fp,"================================================");
    fwrite($fp,"\n\n\n");
    fclose($fp);
    
    $response['code'] = '0';
    $response['msg'] = 'The video that you are trying to delete cannot be found.';
    
    echo json_encode($response);
    die;
    
   }
    
  }else {
   // If the user hasn't authorized the app, initiate the OAuth flow
   $state = mt_rand();
   $client->setState($state);
   $_SESSION['state'] = $state;
    
   $authUrl = $client->createAuthUrl();
   $htmlBody = "<h3>Authorization Required</h3>
   <p>You need to <a href='".$authUrl."'>authorize access</a> before proceeding.<p>";
   
   $content = file_get_contents("php://input");
   $post = $htmlBody;
   $fp =fopen("youtubeDelete.log","a+");
   fwrite($fp,"\n\n\n");
   fwrite($fp,"=====================".date('Y-m-d H:i:s')."===========================");
   fwrite($fp,ob_get_clean());
   fwrite($fp,"\n\n\n");
   ob_start();
   print_r($post);
   fwrite($fp,ob_get_clean());
   fwrite($fp,"\n\n");
   fwrite($fp,"================================================");
   fwrite($fp,"\n\n\n");
   fclose($fp);
  } 
 }
 
} 
?>


- Create model User_model.php

<?php 

function upload_youtube_video($upload_video){
 $this->db->insert('tbl_playervideos', $upload_video);
 $insert_id = $this->db->insert_id();
 return $insert_id;
}

function lastUploadedVideo($uploadedVideoId){
 $this->db->select('*');
 $this->db->from('tbl_playervideos');
 $this->db->where('pv_video_id', $uploadedVideoId);
 $query = $this->db->get();
 $result = $query->result();
 return $result;
}

function youtube_videoID($videoId,$youtube_video_key){
 $this->db->set('pv_youtube_video_id', $youtube_video_key);
 $this->db->where('pv_video_id', $videoId);
 $this->db->update('tbl_playervideos');
 return $this->db->affected_rows();
}

function getUserInfo($userId)
{
 $this->db->select('*');
 $this->db->from('tbl_users');
 $this->db->where('isDeleted', 0);
 $this->db->where('roleId !=', 1);
 $this->db->where('userId', $userId);
 $query = $this->db->get();
 
 return $query->result();
}

function getUserDetail($userId)
{
 $this->db->select('*');
 $this->db->from('tbl_userdetail');
 $this->db->where('ud_userId', $userId);
 $query = $this->db->get();
 
 return $query->result();
}

function checkVideoUploader($videoId,$userId){
 $this->db->select('*');
 $this->db->from('tbl_playervideos');
 $this->db->where('pv_youtube_video_id', $videoId);
 $this->db->where('pv_userId', $userId);
 $query = $this->db->get();
 $result = $query->result();
 
 return $result;
}

function deleteYoutube($videoId,$videoDetail){
 $this->db->where('pv_youtube_video_id', $videoId);
 $this->db->update('tbl_playervideos', $videoDetail);
 
 return $this->db->affected_rows();
}
 
?>

-  create view file to fill form for upload video videoUpload.php
- must use video title, description,tags and upload file

<form id="multiple_upload_form" enctype="multipart/form-data" action="<?php echo base_url($clang.'/youtube_controller/youtube_upload');?>" method="post">
 <div class="box-body">

 <div class="form-group">
  <label for="title">Title:</label><input type="text" name="title" id="title" class="form-control" value="" / >
 </div>
 <div class="form-group">
  <label for="description">Description:</label> <textarea name="description" id="description" class="form-control" cols="20" rows="2" ></textarea>
 </div>
 <div class="form-group">
  <label for="tags">Tags:</label>
  
  <select name="tags[]" multiple="multiple" class="tags form-control">
   <option value="cartoon">Cartoon</option>
   <option value="fun">Fun</option>
   <option value="soccer">Soccer</option>
   <option value="new">New</option>
     
  </select>
 </div>
 <br>
 <div class="form-group">
  <label for="video_file">Choose Video File:</label> <input type="file" name="videoFile" id="videoFile" class="form-control" >
 </div>
 <div class="form-group">
  <input class="btn btn-default" id="submit_video" type="submit" value="Upload">
 </div>
 
 </div>
</form> 

Comments