Andrew Wilson Andrew Wilson - 25 days ago 6
PHP Question

Unexpected T_Variable $client in PHP

I've just been staring at this forever because I cannot figure out what is wrong from this code. This is just slightly modified from what Google posted on the php drive api quickstart guide to get rid of 5 other errors. I don't know if I'm missing something but for a company as big as Google I can't even imagine why there unedited code would have 4 errors in the first 16 lines. Anyways, here's the code:

require_once __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Drive API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');

define('SCOPES', implode(' ', array(Google_Service_Drive::DRIVE_METADATA_READONLY)));

if(php_sapi_name() != 'cli') {

function getClient(){
$client = new Google_Client();

  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);

  if ($client->isAccessTokenExpired()) {
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  return $client;

function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  return str_replace('~', realpath($homeDirectory), $path);

$client = getClient();
$service = new Google_Service_Drive($client);

$optParams = array(
  'pageSize' => 10,
  'fields' => 'nextPageToken, files(id, name)'
$results = $service->files->listFiles($optParams);

if (count($results->getFiles()) == 0) {
  print "No files found.\n";
} else {
  print "Files:\n";
  foreach ($results->getFiles() as $file) {
    printf("%s (%s)\n", $file->getName(), $file->getId());


It just keeps giving me the following error:

PHP Parse error: syntax error, unexpected '$client' (T_VARIABLE) in
C:\xampp\htdocs\quickstart.php on line 17

Parse error: syntax error, unexpected '$client' (T_VARIABLE) in
C:\xampp\htdocs\quickstart.php on line 17


For those who see this post and have other problems:

Possible problem

  • Do you have some strange invisible chars? Then re-type it; or just copy your code which is pasted here.
  • Do you have a { without matching }?
  • Do you forget a ;?
  • Do you use strange visible chars like Chinese and so on?