title: PHP Upload PDF to Google Drive API
body: <p>I have website created in PHP. Basically it is a send document kind of project. It uses a document store in Azure I will call and send it into Azure. Now I want to send in email as well as store in Google drive.</p>
  
  <p>So it should be stored to drive with public access. I have create following code. It works properly I don't want any input from user. </p>
  
  <pre><code>  $client-&gt;setAccessToken($_SESSION['accessToken']);
      $service = new Google_DriveService($client);
      $finfo = finfo_open(FILEINFO_MIME_TYPE);
      $file = new Google_DriveFile();
      foreach ($files as $file_name) {
          $file_path = 'files/'.$file_name;
          $mime_type = finfo_file($finfo, $file_path);
          $file-&gt;setTitle($file_name);
          $file-&gt;setDescription('This is a '.$mime_type.' document');
          $file-&gt;setMimeType($mime_type);
          $service-&gt;files-&gt;insert(
              $file,
              array(
                  'data' =&gt; file_get_contents($file_path),
                  'mimeType' =&gt; $mime_type
              )
          );
      }
      finfo_close($finfo);
  </code></pre>
  
  <p>I want upload from Azure URL using cURL or using API. When mail send it is automatically uploaded to drive at the same time. </p>
  
  <p><strong>Question Update</strong></p>
  
  <p>I have function to send a mail this is work perfectly. I would like to store an attachment to google drive and retrieve path store that path in to database.</p>
  
  <p>This all work will be based on API no user interaction required. That file is PDF in formate and not specific bytes its different as per data of file.</p>
  
  <p>Issue : </p>
  
  <p>When I upload a file to Drive original file name is rename to untitled. Here is code.</p>
  
  <pre><code>function uploadFile($credentials, $filename, $targetPath)
  {
  
      global $GAPIS;
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
  
      curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
      //curl_setopt($ch, CURLOPT_POSTFIELDS, array("title" =&gt;"newfile.txt"));
      curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
  
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER,
              array('Content-Type : text/plain', 'Content-Length:' . filesize($filename),
                      'Authorization: Bearer ' . getAccessToken($credentials))
      );
  
      $postResult = curl_exec($ch);
      curl_close($ch);
  
      return json_decode($postResult, true);
  }
  </code></pre>
  
  <p><strong>==========================================</strong></p>
  
  <p>Updated code  (Issue with Added code but still getting issue with Untitle.pdf in drive)</p>
  
  <p><strong>==========================================</strong></p>
  
  <pre><code>&lt;?php
  
  $GAPIS = 'https://www.googleapis.com/';
  $GAPIS_AUTH = $GAPIS . 'auth/';
  $GOAUTH = 'https://accounts.google.com/o/oauth2/';
  
  $CLIENT_ID = '709846732498-xxxxxxxx';
  $CLIENT_SECRET = 'XXXXXXXXXXXXXX';
  $REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
  $SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
  $STORE_PATH = 'credentials.json';
  
  function uploadFile($credentials, $filename, $targetPath)
  {
  
      global $GAPIS;
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
  
      curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER,
              array('Content-Type : application/pdf', 'Content-Length:' . filesize($filename),
                      'Authorization: Bearer ' . getAccessToken($credentials))
      );
  
      $postResult = curl_exec($ch);
      curl_close($ch);
  
      return json_decode($postResult, true);
  }
  
  function getStoredCredentials($path)
  {
  
      $credentials = json_decode(file_get_contents($path), true);
  
      if (isset($credentials['refresh_token']))
          return $credentials;
  
      $expire_date = new DateTime();
      $expire_date-&gt;setTimestamp($credentials['created']);
      $expire_date-&gt;add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
  
      $current_time = new DateTime();
  
      if ($current_time-&gt;getTimestamp() &gt;= $expire_date-&gt;getTimestamp())
      {
          $credentials = null;
          unlink($path);
      }
  
      return $credentials;
  }
  
  function storeCredentials($path, $credentials)
  {
  
      $credentials['created'] = (new DateTime())-&gt;getTimestamp();
      file_put_contents($path, json_encode($credentials));
      return $credentials;
  }
  
  function requestAuthCode()
  {
  
      global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
      $url = sprintf($GOAUTH . 'auth?scope=%s&amp;redirect_uri=%s&amp;response_type=code&amp;client_id=%s&amp;approval_prompt=force&amp;access_type=offline',
              urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
      );
      header('Location:' . $url);
  }
  
  function requestAccessToken($access_code)
  {
  
      global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
      $url = $GOAUTH . 'token';
      $post_fields = 'code=' . $access_code . '&amp;client_id=' . urlencode($CLIENT_ID) . '&amp;client_secret=' . urlencode($CLIENT_SECRET)
              . '&amp;redirect_uri=' . urlencode($REDIRECT_URI) . '&amp;grant_type=authorization_code';
  
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
      curl_setopt($ch, CURLOPT_POST, true);
  
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_URL, $url);
  
      $result = curl_exec($ch);
  
      curl_close($ch);
  
      return json_decode($result, true);
  }
  
  function getAccessToken($credentials)
  {
  
      $expire_date = new DateTime();
      $expire_date-&gt;setTimestamp($credentials['created']);
      $expire_date-&gt;add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
  
      $current_time = new DateTime();
  
      if ($current_time-&gt;getTimestamp() &gt;= $expire_date-&gt;getTimestamp())
          return $credentials['refresh_token'];
      else
          return $credentials['access_token'];
  
  }
  
  function authenticate()
  {
  
      global $STORE_PATH;
  
      if (file_exists($STORE_PATH))
          $credentials = getStoredCredentials($STORE_PATH);
      else
          $credentials = null;
  
      if (!(isset($_GET['code']) || isset($credentials)))
          requestAuthCode();
  
      if (!isset($credentials))
          $credentials = requestAccessToken($_GET['code']);
  
      if (isset($credentials) &amp;&amp; isset($credentials['access_token']) &amp;&amp; !file_exists($STORE_PATH))
          $credentials = storeCredentials($STORE_PATH, $credentials);
  
      return $credentials;
  }
  
  $credentials = authenticate();
  
  $result = uploadFile($credentials, 'example.pdf', '');
  
  if (!isset($result['id']))
      throw new Exception(print_r($result));
  else
      echo 'File copied successfuly (file Id: ' . $result['id'] . ')';
  
  echo '&lt;pre&gt;'; print_r($result);
  </code></pre>