Google Authentication with PHP

Here you'll find a very simple Google Authentication feature that you can modify and integrate into your own projects. I'm including the code that I used in two files below, test.php and block.php, so you can see how the code (displayed below each) works with the jetGoogleAuth.php file.

Instructions

Set up a work space that allows you to run php files in your browser. (If you don't know how to do this, you'll want to learn that first.)

Download this .zip file.

In addition to using this set of files, you'll want to use the Google API Client (PHP). Go get set up with a Client ID and Client Secret there and then come back and follow the rest of these instructions. I'm including an empty folder for reference, but you'll want to download and install the latest library from Google, as well as make an adjustment (if necessary) to the path to the autoload in config.php once you're done.

Have a look through the test.php and block.php files that are included in the folder as demos. You should be able to view test.php, but be redirected to block.php when you log in. Then, when you log out in block.php, you should be redirected back to test.php. If you try to visit block.php without logging in, you should also be redirected. The code for each is displayed below, and is also included in the zip file.


test.php
<?php
require_once("jetGoogleAuth.php");

$authOptions = new stdClass();
$authed = jetGoogleAuth::requireLogin($authOptions);
$displayOptions = new stdClass();
$displayOptions->redirect = "./block.php";		// redirect if logged in
jetGoogleAuth::display($displayOptions);

print "<hr />";
if ($authed) {
	?>
	<a href="block.php">block.php</a>
	<?php
}
?>
block.php
<?php
require_once("jetGoogleAuth.php");
$authOptions = new stdClass();
$authOptions->redirect = "./test.php";	// redirect if NOT logged in
$authOptions->_fun = function() {
	print "test";
};
$authed = jetGoogleAuth::requireLogin($authOptions);
$displayOptions = new stdClass();
$displayOptions->redirect = "./test.php";	// redirect after logout
jetGoogleAuth::display($displayOptions);

if ($authed) {
	?>
	<a href="test.php">test.php</a>
	<?php
}
?>