0
votes

I have followed https://developers.google.com/sheets/api/quickstart/php quickstart document but it's CLI based.

I want to read and write sheet using browser request.

// In quickstart example they have used cli function.
$authCode = trim(fgets(STDIN));

Can anyone please provide sample code Google sheet API 4 for browser request?

1
To be perfectly honest with you - I got so fed up of their SDK I built my own with a little CURL function. You may find its easier - use the Google SDK for Oauth connections and then just pass the token and JSON over to the server. In answer to your question though the guide runs it through the CLI it will work perfectly well through the browser. - Antony
@Antony Thanx for reply. Could you please provide sample code Google Sheet API 4 for browser request? - Mr. HK
So if you save the .php file somewhere public and run it through the browser - then as long as all the dependencies load correctly then the script should "just run". - Antony
@Antony Thanx for the reply, But I'm looking for sample code, Could you please provide? - Mr. HK
I refer to the code in the original link you provided. - Antony

1 Answers

0
votes

Create A Index.php and paste below code.

require_once __DIR__ . '/vendor/autoload.php';
function getClient()
{
    $client = new Google_Client();
  $client->setAuthConfig( __DIR__ .'/client_secret.json');
$client->setScopes(['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive','https://docs.google.com/feeds/']);
    $client->setAccessType('offline');
      $authUrl = $client->createAuthUrl();        
      header("location:".$authUrl);
}

Then Create another callback.php for redirect page and paste below code. #Please Make sure that you have entered this redirect url in client_secret.json And Google Developer Api Project too. And You Ready To go.

require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig( __DIR__ .'/client_secret.json');
$client->setScopes(['https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive']);
    $client->authenticate($_GET['code']);
   $access_token = $client->getAccessToken();