1

I have been following Google Sheets API v4 for performing specific tasks in my Google Sheet through PHP. I followed the API quickstart and just copy-pasted the code and changed the credentials of sheet in my code. When I run the code, the page isn't loading and giving this error:

localhost is currently unable to handle this request. HTTP ERROR 500.

I don't know that why it isn't loading. It might be problem in these lines, but I am not sure exactly:

if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}

My code is below

<?php
require __DIR__ . '/vendor/autoload.php';
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Sheets API PHP Quickstart');
    $client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
    $client->setAuthConfig('client_secret.json');
    $client->setAccessType('offline');
    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory('credentials.json');
    if (file_exists($credentialsPath)) {
        $accessToken = json_decode(file_get_contents($credentialsPath), true);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));
        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
        // Store the credentials to disk.
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, json_encode($accessToken));
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);
    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }
    return $client;
}
/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path)
{
    $homeDirectory = getenv('HOME');
    if (empty($homeDirectory)) {
        $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
    }
    return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (empty($values)) {
    print "No data found.\n";
} else {
    print "Name, Major:\n";
    foreach ($values as $row) {
        // Print columns A and E, which correspond to indices 0 and 4.
        printf("%s, %s\n", $row[0], $row[4]);
    }
}
// [END sheets_quickstart]

I actually don't know that how to run this api in my localhost exactly.

tehhowch
  • 9,645
  • 4
  • 24
  • 42
Zain Farooq
  • 2,956
  • 3
  • 20
  • 42
  • You may refer with this [link](https://stackoverflow.com/questions/40216761/the-localhost-page-isn-t-working-localhost-is-currently-unable-to-handle-this-re). Try to check your files access level using `$ sudo chmod -R 777 /"your files location"` command. Such kind of error normally happens when you try using functions wrongly. Here's an additional links which might also help: https://github.com/opensourcepos/opensourcepos/issues/923 and https://askubuntu.com/questions/881290/php-localhost-is-currently-unable-to-handle-this-request-http-error-500 – abielita Jul 11 '18 at 14:59

1 Answers1

0

Run the sample using the following command:

php quickstart.php / or your php file name

The first time you run the sample, it will prompt you to authorize access:

  1. Browse to the provided URL in your web browser.
    If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.

  2. Click the Accept button.

  3. Copy the code you're given, paste it into the command-line prompt, and press Enter.

JohnR
  • 59
  • 1
  • 8