PHP google api asks the user to log in twice

I use a google api in PHP provided by google (google-api-php-client). However, I face a problem that the api asks twice for the login. When I click on "Log In To Your Google Account" link for the first time, it redirects me to the google login page (which is correct). Then, after logging in, it redirects me back the page at the url I have given the api, but it asks me again to click on "Log In To Your Google Account" link instead of showing the result of the login action.

When I click on the login link again, it doesn't go to the login page again, but it gives me the result of the login action (after checking of the login status I guess) which should have been done in the first click.

My Code Below:

<?php
	/************************************************************************
	* Plugin Name: Google Drive Plugin										*
	* Plugin URI: http://www.picpixa.com/									*
	* Version: 1.0															*
	* Author: Ashish Shah													*
	* Description: Plugin To Import Images From User's Google Drive Account *
	************************************************************************/
	
	/*
	* Copyright 2011 Google Inc.
	*
	* Licensed under the Apache License, Version 2.0 (the "License");
	* you may not use this file except in compliance with the License.
	* You may obtain a copy of the License at
	*
	*     http://www.apache.org/licenses/LICENSE-2.0
	*
	* Unless required by applicable law or agreed to in writing, software
	* distributed under the License is distributed on an "AS IS" BASIS,
	* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	* See the License for the specific language governing permissions and
	* limitations under the License.
	*/
	session_start();
	ini_set("display_errors",1);
?>
<html>
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Google Drive Images</title>
		
		<!-- Bootstrap -->
		<link href="css/bootstrap.css" rel="stylesheet">
		<link href="css/style.css" rel="stylesheet">
		
		<style>
			.loader {
				position: fixed;
				left: 0px;
				top: 0px;
				width: 100%;
				height: 100%;
				z-index: 9999;
				background: url('Images/page-loader.gif') 50% 50% no-repeat rgb(249,249,249);
			}
		</style>
		
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
		<script type="text/javascript">
			$(window).load(function() {
				$(".loader").fadeOut("slow");
			});
		</script>
		<script>
			function loader(){
				$('#load').show();
			}
			function loadExistingImages(){
				window.opener.$('#loader_img').show();
				result=null;
				window.opener.$('#fileupload').each(function () {
					var that = this;
					window.opener.$.getJSON(this.action, function (result) {
						if (result && result.length) {
							window.opener.$(that).fileupload('option', 'done')
								.call(that, null, {result: result});
							//console.log('ss='+$('.table-striped tbody').find('.btn-danger').length);
							if(window.opener.$('.table-striped .files').find('.btn-danger').length>0){
								window.opener.$('.coo-images-other-buttons').show();
							}else{
								window.opener.$('.coo-images-other-buttons').hide();
							}
						}
						window.opener.$('#loader_img').hide();

						if (window.opener.$('.table-striped.files').children().length > 0)
						{
							window.opener.$('.table_tagline').show();
						}
					});
				});
			}
		</script>
		<script type="text/javascript">$('#load').hide();</script>
	</head>
	<body>
		<div id="load" class="loader"></div>
	
	<?php
	
	include_once "templates/base.php";
	//ini_set("display_errors",0);
	include_once '/home/picpixa/wp-config.php';
	
	set_include_path("src/" . PATH_SEPARATOR . get_include_path());
	require_once 'Google/Client.php';
	require_once 'Google/Http/MediaFileDownload.php';
	require_once 'Google/Service/Drive.php';
	
		if(isset($_POST['copy']) && $_POST['gDrive'])
		{
			$imgArray = $_POST['gDrive'];
			
			$current_user = wp_get_current_user();
			
			if(isset($current_user->ID) && trim($current_user->ID)!='' && trim($current_user->ID)!=0){
				$extraSessionStr = 'usr-'.md5($current_user->ID).'/';
				$user = $current_user->ID;
			}else{
				$sesstionId = session_id();
				$user = $sesstionId;
				$extraSessionStr = $sesstionId.'/';
			}
			
			foreach ($imgArray as $img)
			{
				$getName = explode ("(OR)",$img);
				$imgInfo = pathinfo($getName[1]); //This will become an array with keys ('dirname','basename','extension','filename')
				
				$oriFileName=$imgInfo['filename'];//Getting a file name without extension
				$fileName = (string) $oriFileName.".".$imgInfo['extension'];//Creating a file name with extension

				//Check weather the file is exists or not rename the file if exists
				$i=1;
				if(file_exists('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName)){
					while(file_exists('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName)){
						$fileName = (string) $oriFileName."(".$i.").".$imgInfo['extension'];
						$i++;
					}
				}
				
				// Read file content
				$file_content = file_get_contents($getName[0]);
				
				//Putting the main file into the directory
				file_put_contents('/home/picpixa/server/php/files/'.$extraSessionStr.$fileName, $file_content);
				
				//Putting the thumbnail in the directory
				//Get the image size
				$imgsize=get_headers($getName[0],1);
				$imgsize = number_format(($imgsize["Content-Length"]/1024),2);
				
				/* To create thumbnail */
				
				// Max vert or horiz resolution
				$maxsize=80;
				
				// create new Imagick object
				$image = new Imagick($getName[0]); //"input_image_filename_and_location"
				
				// Resizes to whichever is larger, width or height
				if($image->getImageHeight() <= $image->getImageWidth())
				{
					// Resize image using the lanczos resampling algorithm based on width
					$image->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
				}
				else
				{
					// Resize image using the lanczos resampling algorithm based on height
					$image->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
				}
				
				// Set to use jpeg compression
				$image->setImageCompression(Imagick::COMPRESSION_JPEG);
				// Set compression level (1 lowest quality, 100 highest quality)
				$image->setImageCompressionQuality(75);
				// Strip out unneeded meta data
				$image->stripImage();
				// Writes resultant image to output directory
				$image->writeImage('/home/picpixa/server/php/thumbnails/'.$extraSessionStr.$fileName); //"output_image_filename_and_location"
				
				/*Problem is in above line ($image->writeImage) otherwise all is working fine because of it Networkerror 500 occurs
				 * Need to find solution
				 */

				// Destroys Imagick object, freeing allocated resources in the process
				$image->destroy();
			}
			?>
				<script type="text/javascript">
					//window.opener.$("#fileupload").append(div);
					window.opener.$('tbody.files').find('tr').remove();
					loadExistingImages();
				</script>
			<?php
				echo "<h2>The selected images have been uploaded successfully.</h2>";
				//echo "<h3>Please click on \"Proceed With Uploaded Images\" button to Proceed OR ";
				//echo "Click on the \"Upload More Images\" Button to upload more images.</h3>";
			?>
			<div class="modal-footer">
				<input type='button' name='continue' value='Upload More Images' class='btn btn-primary' onclick='loader();window.location.href="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-google-drive/index.php";'>
				<input type='button' name='closeWindow' value='Close' class='btn btn-primary' onClick="window.close();">
			</div>
		<?php
			die();			
		}
		elseif (isset($_POST['copy']))
		{
			echo "<h2>You have not selected any image(s) to move.</h2><br><br>";
			//echo "<h3>Please click on \"Close\" button to Close the window OR ";
			//echo "Click on the \"Upload Images\" Button to upload images.</h3>";
		?>
			<div class="modal-footer">
				<input type='button' name='continue' value='Upload Images' class='btn btn-primary' onclick='loader();window.location.href="https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-google-drive/index.php";'>
				<input type='button' name='closeWindow' value='Close' class='btn btn-primary' onClick="window.close();">
			</div>
		<?php
			die();
		}
	?>
<?php
/************************************************
  ATTENTION: Fill in these values!
 ************************************************/
$client_id = 'YOUR_APP_ID';
$client_secret = 'YOUR_API_SECRET';
$redirect_uri = 'YOUR_REDIRECT_URI';

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);

/*echo "Client:<pre>";
print_r($client);
echo "</pre>Client End.<br>Service:<pre>";
print_r($service);
echo "</pre>Service End.<br>";
*/
if (isset($_REQUEST['logout'])) {
	unset($_SESSION['download_token']);
	echo "You are logged out.";
	echo "<br>";
}

if (isset($_GET['code'])) {
	
	//echo "Entered get_code<br>";

	$client->authenticate($_GET['code']);
	$_SESSION['download_token'] = $client->getAccessToken();
	$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
	
	//It never gets into this section
	//echo "Redirect: $redirect<br>";
	//echo "Header: ".filter_var($redirect, FILTER_SANITIZE_URL)."<br>";
	
	header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

/*echo "Session:<pre>";
print_r($_SESSION);
echo "</pre>Session End.<br>";
*/
if (isset($_SESSION['download_token']) && $_SESSION['download_token']) {
	
	//echo "Entered Session download token<br>";
	
	$client->setAccessToken($_SESSION['download_token']);
	if ($client->isAccessTokenExpired()) {
		//echo "Entered Session download token expire<br>";
		unset($_SESSION['download_token']);
	}
} else {
	//echo "Not Entered Session download token. Entered else part.<br>";
	$authUrl = $client->createAuthUrl();
	//echo "Auth url: $authUrl<br>";
}

/*echo "Session 2:<pre>";
print_r($_SESSION);
echo "</pre>Session 2 End.<br>";
*/
/********************************************************
  If we're signed in then lets try to download our file.
 ********************************************************/
if ($client->getAccessToken()) {
	
	//echo "Entered getAccessToken<br>";

	// This is downloading a file directly, with no metadata associated.
	$file = new Google_Service_Drive_DriveFile();
	$result = $service->files->listFiles(
    	$file,
		array('downloadType' => 'media')
	);

	/*echo "File:<pre>";
	print_r($file);
	echo "</pre>File End.<br>";
	echo "Result:<pre>";
	print_r($result);
	echo "</pre>Result End.<br>";
	*/
}

/*echo "File 1:<pre>";
print_r($file);
echo "</pre>File 1 End.<br>";
echo "Result 1:<pre>";
print_r($result);
echo "</pre>Result 1 End.<br>";
*/
?>
		<div class="container">
			<div class="row">
				<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
					<?php
					if (isset($authUrl)){ ?>
						<a class='login' href='<?php echo $authUrl; ?>'>Log In To Your Google Account!</a>
					<?php }else{ ?>
						<a class='logout' href='?logout'>Log Out</a>
					<?php } ?>
					
					<?php
						if (isset($result)){
							$i=0;
							$temp=0;
							$showBtn=False;
					?>
							<form method='post' action='index.php'>
								<div class='modal-body'>
					<?php
									/*echo "Result:<pre>";
									print_r($result);
									echo "</pre>Result End.<br>";
									die;*/
									foreach ($result as $key => $value){
										if(strcmp($result['modelData']['items'][$i]['mimeType'],'image/jpeg') == 0
											|| strcmp($result['modelData']['items'][$i]['mimeType'],'image/jpg') == 0
											|| strcmp($result['modelData']['items'][$i]['mimeType'],'image/png') == 0)
										{
											if(isset($result['modelData']['items'][$i]['thumbnailLink'])){
												//echo $result['modelData']['items'][$i]['thumbnailLink']."(OR)".$result['modelData']['items'][$i]['title']."<br>";
					?>
												<div class="baby_img">
													<input type="checkbox" id="gDrive_<?=$temp;?>" name="gDrive[]"  value="<?php echo $result['modelData']['items'][$i]['thumbnailLink']."(OR)".$result['modelData']['items'][$i]['title'];?>" class="styled" />
													<input type="hidden"  id="fileName_<?=$temp;?>" name="fileName[]"  value="<?php echo $result['modelData']['items'][$i]['title'];?>" class="styled" />
													<img src="<?php echo $result['modelData']['items'][$i]['thumbnailLink'];?>" class="img-responsive" style="width:100px !important; height:100px !important;"/>
												</div>
					<?php
											}
											$temp++;
										}
										$i++;
										$showBtn=True;
									}
					?>
								</div>
								<div class="clearfix"></div>
            					<div class="modal-footer">
            		<?php
            						if($showBtn){
					?>
										<input type='submit' name='copy' value='Copy Selected Files' class="btn btn-primary" onclick="loader()">
					<?php
									}
					?>
									<input type='button' name='closeWindow' value='Close This Window' class='btn btn-primary' onClick="window.close();">
								</div>
							</form>
					<?php
						}
					?>
				</div>
			</div>
		</div>
	</body>
</html>

Note: I have put echo and print_r to understand better the code behavior. You can freely remove them.