Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cron Based Google Analytics API Requests using PHP

After reading the GA API documentation and looking at the sample code for PHP, I'm unable to see how to authenticate without the user being present.

For our website, we want to pull GA Data in once an hour and compare with additional metrics on our site. We aim to do this on a CRON which will then inform us of correlations between current site behaviour and historical GA trend data.

Is there a way to emulate the authentication in PHP so that these could be done via a CRON, assuming email and password are known for the GA account?

Many thanks

like image 242
MyStream Avatar asked Jul 31 '26 07:07

MyStream


1 Answers

Ok, after a clarification i think i got what you mean. Following is a huge generalization.

So, i assume you're using some kind of a framework, but if no, it's not a problem anyway. You can create separate php file on your public folder which will check from what ip we've requested it ($_SERVER['REMOTE_ADDR']) if it's local (works fine in default Apache, some additional config required if you're using proxy server like nginx) then you can proceed to getting GA data.

How to get it described in here: http://code.google.com/p/gapi-google-analytics-php-interface/

Pretty straightforward: include GAPI class and then run

$ga = new gapi('[email protected]','password');
$ga->requestReportData(145141242,array('browser','browserVersion'),array('pageviews','visits'));

If code above doesn't work, then you'll have to use OAuth2 to gain access to GA.

Description on how to do it:

  1. General - Core Reporting API - Authorization
  2. General - Using OAuth 2.0 to Access Google APIs
  3. Google APIs Client Library for PHP
like image 50
Kane Cohen Avatar answered Aug 01 '26 20:08

Kane Cohen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!