title: Connect to Google drive API without user interaction using PHP
body: <p>I want to upload files to Google Drive using the API, but I need to do this using a cron job (autobackup of webfiles+sql to Google drive). </p>
  
  <p>That means (I suppose) that I need to authenticate using something else than the user interaction method.</p>
  
  <p>The example that I have been using: <a href="https://developers.google.com/api-client-library/php/auth/web-app" rel="nofollow noreferrer">https://developers.google.com/api-client-library/php/auth/web-app</a> to get me going, and its working with user authenticating.</p>
  
  <p>I would appreciate some tips on how to do this without user interaction, so it can run on a cronjob.</p>
  
  <p>Here are the PHP code for authenticate and upload file (working example with manual user auth and single file upload)</p>
  
  <pre><code>  &lt;?php
  
      require_once 'google-api-php-client/vendor/autoload.php';
  
      /* Config */
      $servername = 'content here';
      $redirect_uri = 'https://example.com/';
  
      $client = new Google_Client();
      $client-&gt;setAuthConfig('client_manual_authentiation.json');
      $client-&gt;addScope(Google_Service_Drive::DRIVE);
  
      if(isset($_SESSION['access_token']) &amp;&amp; $_SESSION['access_token']) {
  
          $client-&gt;setAccessToken($_SESSION['access_token']);
          $drive = new Google_Service_Drive($client);
  
          foreach($drive-&gt;files-&gt;listFiles(array("q" =&gt; "name = '{$servername}'"))-&gt;getFiles() as $key =&gt; $element){
  
              if($element-&gt;name == $servername){
  
                  //create todays folder on Google Drive
                  $today_folder_meta = new Google_Service_Drive_DriveFile(array(
                      'name' =&gt; 'myfile.txt',
                      'mimeType' =&gt; 'application/vnd.google-apps.folder',
                      'parents' =&gt; array($element['id'])
                  ));
  
                  $today_folder = $drive-&gt;files-&gt;create($today_folder_meta, array(
                      'fields' =&gt; 'id'
                  ));
  
              }
          }
      }else{
  
          if (!isset($_GET['code'])) {
              $auth_url = $client-&gt;createAuthUrl();
              header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
          } else {
              $client-&gt;authenticate($_GET['code']);
              $_SESSION['access_token'] = $client-&gt;getAccessToken();
              header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
          }
      }
  
  ?&gt;
  </code></pre>