barreeeiroo barreeeiroo - 4 months ago 8
PHP Question

Error while trying to implement Google SignIn

I'm trying to add Google SignIn to my website, but I can't see anythig, but if I see de Page Source Code, I see this error:


Fatal error: Call to a member function createAuthUrl() on a non-object in /home/u289995868/public_html/es/php/glogin/app/classes/GoogleAuth.php on line 26






The code of this file:

<?php
class GoogleAuth
{
protected $client;

public function __construct(Google_Client $googleClient = null)
{
$this->client = $googleClient;

if($this->client)
{
$this->client->setClientId('xxxxxxxx');
$this->client->setClientSecret('xxxxxxxx');
$this->client->setRedirectUri('http://barreeeiroo.ga/es/php/glogin/index.php');
$this->client->setScopes('email');
}
}

public function isLoggedIn()
{
return isset($_SESSION['access_token']);
}

public function getAuthUrl()
{
return $this->client->createAuthUrl();
}
}
?>





Index.php code:

<?php
require_once 'app/init.php';
$googleClient = new Google_Client();
$auth = new GoogleAuth();
?>

... Here there is some code for navbar and other, not important

<h1>Prueba de Login de Google</h1>
<?php if(!$auth->isLoggedIn()): ?>
<a href="<?php echo $auth->getAuthUrl(); ?>">Iniciar Sesión</a>
<?php else: ?>
Ya has iniciado sesión
<?php endif; ?>





If you want to see the error, go to this website and View Source Code

Answer

You have to change from

$auth = new GoogleAuth();

to

$auth = new GoogleAuth($googleClient);

If you check the constructor of GoogleAuth:

public function __construct(Google_Client $googleClient = null)

You'll see that it defaults to null. This means that if don't pass anything to the constructor, the $googleClient parameter will be null.


Quick RDD:

  • {require and instantiate}
  • create an instance of GoogleAuth passing no parameters and put that into $auth;
    • since the parameter defaults to null, $googleClient is null;
    • set GoogleAuth::$client to $googleClient (so, null);
  • {check stuff}
  • call GoogleAuth::getAuthUrl()
    • call GoogleAuth::$client->createAuthUrl(); (Since GoogleAuth::$client is null, it's almost like you are calling null->createAuthUrl();

That's why you get that error.

Comments