Home / Log into the Google Analytics API using PHP and CURL using Username/Password Authentication

Log into the Google Analytics API using PHP and CURL using Username/Password Authentication

Google have finally made an API available for Google Analytics although it’s currently in beta and the specs are subject to change. I’ve been playing around this morning logging in using ClientLogin Username/Password Authentication with PHP and CURL and show how to do this here. In future posts I’ll look at how to actually use the API but this will get us all started for now.

The code example below attempts to log in using $email and $password which are the email address and password you would normally use to log into Analytics.

$data = array(
    'accountType' => 'GOOGLE',
    'Email' => $email,
    'Passwd' => $password,
    'service' => 'analytics',
    'source' => ''

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);

$auth = '';
if($info['http_code'] == 200) {
    preg_match('/Auth=(.*)/', $output, $matches);
    if(isset($matches[1])) {
        $auth = $matches[1];

The API will return a status code of 401 if the login failed or a status of 200 if the login was successful. On a successful login the content returned looks like this:

Auth=DQAAAH4AAA etc etc

The regular expression at the end of the code example above extracts the auth key from the result data. In subsequent requests you would something like this when making API calls:

$headers = array("Authorization: GoogleLogin auth=$auth");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

I’ll continue to play around with this over the next couple of days and will post some more tutorials and code examples of accessing the Google Analytics API with PHP and CURL.

Update April 28th 2009: I’ve started a series about this and created a PHP class. The full class, which I will continue to update over the next few days, can be downloaded here.