Google Analytics API Tutorial with PHP for Dummies

Build awesome apps with Google Analytics API for PHP. Learn how to use the Google Analytics API and PHP to bring data directly to your site or app.

Build some awesome apps and site functionality with Google Analytics API for PHP.

Recently I needed to build a simple web app that uses the Google Analytics API. Google’s documentation on the subject is a little lackluster and with constant updates to their interface, the documentation often times lags behind. Other times steps are completely left out because they don’t need to hold the hands of dummies like me. Well other dummies, I’m here to hold your hand and walk you through how to use the GA API with PHP. Continue reading “Google Analytics API Tutorial with PHP for Dummies”

PHP Password Hashing API Tutorial

Learn how to use PHP 5.5’s password hashing API to store your user passwords more securely. A simple to use API that helps developers move towards bcrypt.

Are you hashing your user passwords? If not, you’re asking for trouble (just look at the recent password leaks). Keeping plain text passwords or using older, weaker algorithms like MD5 or SHA1 to store passwords have become outdated and less secure than newer, modern methods. For instance, with the release of PHP 5.5, you can use the new password hashing api.

Everybody knows that you should be hashing user passwords using bcrypt, but still a surprising number of developers uses insecure md5 or sha1 hashes. One of the reasons for this is that the crypt() API is ridiculously hard to use and very prone to programming mistakes.

PHP Password Hashing Functions

By adding a new, very simple to use API PHP hopes to move more developers towards bcrypt. It has four simple functions:

  • password_hash() – used to hash the password
  • password_verify() – used to verify a password against its hash
  • password_needs_rehash() – used when a password needs to be rehashed
  • password_get_info() – returns the name of the hashing algorithm and various options used while hashing

How to Hash Passwords Using PHP

Although the crypt() function is secure, it’s considered by many to be too complicated and prone to programmer error. Some developers then use a weak salt and weak algorithm for generating a hash instead, for example:

[code_highlight lang=”php”]$hash = md5($password . $salt); // works, but dangerous[/code_highlight]

But the password_hash() function can simplify our lives and our code can be secure. When you need to hash a password, just feed it to the function and it will return the hash which you can store in your database. Creating password hashes can’t be any simpler than this:

[code_highlight lang=”php”]$hash = password_hash( $password, PASSWORD_DEFAULT );[/code_highlight]

This will create a password hash using the default algorithm (currently bcrypt), the default load factor (currently 10) and an automatically generated salt. The used algorithm and salt will also be part of the resulting hash, so you don’t need to worry about them at all.

If you don’t want to stick with the defaults (which might change in the future), you can also provide algorithm and load factor yourself:

[code_highlight lang=”php”]$hash = password_hash( $password, PASSWORD_BCRYPT, [‘ cost’ => 12 ] );[/code_highlight]

That’s it! The first parameter is the password string that needs to be hashed and the second parameter specifies the algorithm that should be used for generating the hash.

The default algorithm is currently bcrypt, but a stronger algorithm may be added as the default later at some point in the future and may generate a larger string. If you are using PASSWORD_DEFAULT in your projects, be sure to store the hash in a column that’s capacity is beyond 60 characters. Setting the column size to 255 might be a good choice. You could also use PASSWORD_BCRYPT as the second parameter. In this case the result will always be 60 characters long.

The important thing here is that you don’t have to provide a salt value or a cost parameter. The new API will take care of all of that for you. And the salt is part of the hash, so you don’t have to store it separately. If you want to provide your own salt (or cost), you can do so by passing a third argument to the function, an array of options.

[code_highlight lang=”php”]$options = [
‘salt’ => custom_function_for_salt(), //write your own code to generate a suitable salt
‘cost’ => 12 // the default cost is 10
];
$hash = password_hash($password, PASSWORD_DEFAULT, $options);[/code_highlight]

In this way, you are always up-to-date with new security measures. If PHP later decides to implement a more powerful hashing algorithm your code can take advantage of it.

Verifying PHP Hashed Passwords

Now that you have seen how to generate hashes with the new API, let’s see how to verify a password. Remember that you store the hashes in a database, but it’s the plain password that you get when a user logs in.

The password_verify() function takes a plain password and the hashed string as its two arguments. It returns true if the hash matches the specified password. Verifying passwords is just as easy:

[code_highlight lang=”php”]// $password from user, $hash from database
if (password_verify($password, $hash)) {
// password valid!
} else {
// wrong password 🙁
}[/code_highlight]

Just remember that the salt is a part of the hashed password which is why we are not specifying it separately here.

Rehashing PHP Passwords

As time goes by you might want to change the password hashing algorithm or load factor, or PHP may change the defaults to be more secure. In this case new accounts should be created using the new options and existing passwords rehashed on login (you can do this only on login because you need the original password to do a rehash).

Doing this is also very simple:

[code_highlight lang=”php”]function password_verify_with_rehash( $password, $hash ) {
if ( ! password_verify( $password, $hash ) ) {
return false;
}

if ( password_needs_rehash( $hash, PASSWORD_DEFAULT ) ) {
$hash = password_hash( $password, PASSWORD_DEFAULT );

// update hash in database
}

return true;
}[/code_highlight]

The above snippet will keep your hashes up to date with the PHP default. But once again you can also specify custom options, e.g. password_needs_rehash($hash, PASSWORD_BCRYPT, ['cost' => 12']).

Retrieve PHP Hashed Password Info

Use password_get_info() to return an associative array with information about the given hash. When passed in a valid hash created by an algorithm supported by password_hash(), this function will return the following:

  • algo – a constant that identifies a particular algorithm
  • algoName – the name of the algorithm used
  • options – various options used while generating the hash

Compatibility for Older PHP Versions

The new API will only be introduced in PHP 5.5. Those who are using PHP 5.3.7 (or later) can use a library called password_compat which emulates the API and automatically disables itself once the PHP version is upgraded to 5.5.


Conclusion

The PHP password hashing API is definitely easier to work with than fumbling with the crypt() function. If your website is currently running on PHP 5.5, then I strongly recommended that you use the new hashing API. Learn more about the PHP password hashing API:

Facebook SDK PHP v4 & CodeIgniter

Trying to get the latest version of Facebook SDK for PHP (v4) working well with CodeIgniter? Me too! After doing a bunch of digging with a lot of trial and error, I finally figured it out. Learn how to build a library for CodeIgniter that will help bridge the gap between it and the Facebook SDK for PHP.

Trying to get the latest version of Facebook SDK for PHP (v4) working well with CodeIgniter? Me too! After doing a bunch of digging with a lot of trial and error, I finally figured it out. Learn how to build a library for CodeIgniter that will help bridge the gap between it and the Facebook SDK for PHP.

Step 1: Download & setup folders

The quickest & simplest way to install the Facebook SDK is via Composer. Installing is as easy as adding a require entry for the Facebook SDK for PHP to the composer.json file in the application directory:

application/composer.json

{
  "require" : {
    "facebook/php-sdk-v4" : "4.0.*"
  }
}

Navigate to the application directory and run composer install to download the required dependencies.

Step 2: Create & define config variables

You’ll also need to setup some config variables by creating a new config file:

application/config/facebook.php

$config['facebook']['api_id']       = 'YOUR APP ID';
$config['facebook']['app_secret']   = 'YOUR APP SECRET';
$config['facebook']['redirect_url'] = 'https://yourdomain.com/login';
$config['facebook']['permissions']  = array(
                                        'email',
                                        'user_location',
                                        'user_birthday'
                                      );

Open the application/config/autoload.php and add the Facebook config file you just created to the Auto-load Config files:

/*
| -------------------------------------------------------------------
|  Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
|	$autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files.  Otherwise, leave it blank.
|
*/

$autoload['config'] = array( 'facebook' );

Step 3: Create the Facebook CodeIgniter library

Create a new file called Facebook.php in the application/libraries directory.

This by no means is a complete library, but shows you how to use the API to create methods enabling you to access them in your controllers.

application/libraries/facebook/facebook.php:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// Autoload the required files
require_once( APPPATH . 'vendor/facebook/php-sdk-v4/autoload.php' );

// Make sure to load the Facebook SDK for PHP via composer or manually

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
// add other classes you plan to use, e.g.:
// use Facebook\FacebookRequest;
// use Facebook\GraphUser;
// use Facebook\FacebookRequestException;

class Facebook
{
  var $ci;
  var $session = false;

  public function __construct()
  {
    // Get CI object.
    $this->ci =& get_instance();

    // Initialize the SDK
    FacebookSession::setDefaultApplication( $this->ci->config->item('api_id', 'facebook'), $this->ci->config->item('app_secret', 'facebook') );
  }

  /**
   * Get FB session.
   */
  public function get_session()
  {
    if ( $this->ci->session->userdata('fb_token') ) {
      // Validate the access_token to make sure it's still valid
      $this->session = new FacebookSession( $this->ci->session->userdata('fb_token') );
      try {
        if ( ! $this->session->validate() ) {
          $this->session = false;
        }
      } catch ( Exception $e ) {
        // Catch any exceptions
        $this->session = false;
      }
    }
    else
    {
      // Add `use Facebook\FacebookRedirectLoginHelper;` to top of file
      $helper = new FacebookRedirectLoginHelper( $this->ci->config->item('redirect_url', 'facebook') );
      try {
        $this->session = $helper->getSessionFromRedirect();
      } catch( FacebookRequestException $ex ) {
        // When Facebook returns an error
        print_r($ex->getResponse());
        //redirect( base_url( 'login?err=' . $ex->getResponse() ) );
      } catch( \Exception $ex ) {
        print_r($ex->getResponse());
        // When validation fails or other local issues
        //redirect( base_url( 'login?err=' . $ex->getResponse() ) );
      }
    }
  }

  /**
   * Login functionality.
   */
  public function login()
  {
    $this->get_session();
    if ( $this->session )
    {
      $this->ci->session->set_userdata( 'fb_token', $this->session->getToken() );

      $user = $this->get_user();

      if ( $user && ! empty( $user['email'] ) )
      {
         $result = $this->ci->user_model->get_user( $user['email'] );

          if ( ! $result )
          {
            // Not registered.
            $this->ci->session->set_flashdata( 'fb_user', $user );
            redirect( base_url( 'register' ) );
          }
          else
          {
            if ( $this->ci->user_model->sign_in( $result->username, $result->password ) )
            {
              redirect( base_url( 'home' ) );
            }
            else
            {
              die( 'ERROR' );
              redirect( base_url( 'login' ) );
            }
          }
      }
      else
      {
        die( 'ERROR' );
      }
    }
  }

  /**
   * Returns the login URL.
   */
  public function login_url()
  {
    // Add `use Facebook\FacebookRedirectLoginHelper;` to top of file
    $helper = new FacebookRedirectLoginHelper( $this->ci->config->item('redirect_url', 'facebook') );

    return $helper->getLoginUrl( $this->ci->config->item('permissions', 'facebook') );
    // Use the login url on a link or button to
    // redirect to Facebook for authentication
  }

  /**
   * Returns the current user's info as an array.
   */
  public function get_user()
  {
    $this->get_session();
    if ( $this->session )
    {
      $request = ( new FacebookRequest( $this->session, 'GET', '/me' ) )->execute();
      $user    = $request->getGraphObject()->asArray();

      return $user;
    }
    return false;
  }

  /**
   * Get user's profile picture.
   */
  public function get_profile_pic( $user_id )
  {
    $this->get_session();
    if ( $this->session )
    {
      $request = ( new FacebookRequest( $this->session, 'GET', '/' . $user_id . '/picture?redirect=false&type=large' ) )->execute();
      $pic     = $request->getGraphObject()->asArray();

      if ( ! empty( $pic ) && ! $pic['is_silhouette'] ) {
        return $pic['url'];
      }
    }
    return false;
  }
}

The library above will give you access to the Facebook SDK Graph API. It creates and saves the Facebook token in session so you can access it later for calls to the API.


Example Usage

Once you’ve loaded the Facebook library you created above, you’ll have access to it within your controllers with the following:

For example, if you wanted to get the login URL (where user’s grant access):

Using the examples above, you should be able to add more methods to the library using the Graph API. If you need any help or run into any problems, drop me a comment below.


More on the Facebook SDK for PHP

Facebook PHP SDK v5.x (4.1) — a complete guide!

Facebook SDK PHP is a powerful library allowing you to retrieve user information, publish to profiles, enable Facebook registrations, logins and more. Learn how to easily implement the Facebook SDK PHP library (v4) with easy to follow examples to get your site integrated quickly.

Implement the Facebook SDK 5.x (4.1) for PHP to enable one-click registrations & logins, gain access to user photos, timelines and even publish to profiles.

Update (April 29, 2015): Facebook PHP SDK 5.x? What happened to 4.1 you ask? The Facebook PHP SDK will start following SemVer starting with v5.0. Before the decision to adopt SemVer, the official Facebook PHP SDK was going to be released as v4.1. But now v4.1 is just an alias to v5.0.0. So any references to 4.1 can be safely aliased to v5.0.0. For more information, see F8 2015 Facebook Developer Conference and the new PHP SDK.

Continue reading “Facebook PHP SDK v5.x (4.1) — a complete guide!”

MailChimp PHP API Class: Simple Library for MailChimp API V2

The past couple of months I’ve been working to move a little over 260,000 subscribers from Eloqua to MailChimp. The company that owns the site does heavy email marketing that differs from the typical MailChimp user. This requires some advanced functionality that MailChimp’s interface does not provide. The solution, MailChimp API which allows us to build out our own custom functionality where MailChimp falls short.

The past couple of months I’ve been working to move a little over 260,000 subscribers from Eloqua to MailChimp. The company that owns the site does heavy email marketing that differs from the typical MailChimp user. This requires some advanced functionality that MailChimp’s interface does not provide. The solution, MailChimp API which allows us to build out our own custom functionality where MailChimp falls short.

I was going to build out my own MailChimp PHP API class, but luckily after a little digging, found Drew McLellan‘s MailChimp v2 wrapper. Unlike a lot of the PHP libraries out that are complex, confusing wrappers, this one is super-simple and light-weight. It allows you to quickly access the MailChimp API and start coding your own applications.

Download the MailChimp PHP API Class

MailChimp PHP API Class

Using this MailChimp PHP API Class is as simple as the class is itself. You can either download it by clicking the button above or install the mailchimp-api using Composer. In order to install it with Composer, see the docs for more details.

Once you’ve got it installed, you’ll be ready to build out your application. Just grab your MailChimp API key and initialize the class.

Once initialized, you can begin calling out to the MailChimp API and request the data or functionality you need for your app.

MailChimp PHP API Class Examples

I’m a visual learner, so put together some examples for the MailChimp PHP API Class. I’m also interested in how others use APIs to build out applications. Be sure to comment below and let me know how you’ve integrated this API for your projects.

List Related Methods

List Related Methods

These are just a few examples using the MailChimp API. Check out their docs for a full list and details of all the methods they provide.


MailChimp List Related Methods

Get emails that complained.

MailChimp API Method:
lists/abuse-reports (string apikey, string id, int start, int limit, string since)

Access up to 180 days of aggregated activity for a list (does not include AutoResponder activity).

MailChimp API Method:
lists/activity (string apikey, string id)

Subscribe a batch of emails.

MailChimp API Method:
lists/batch-subscribe (string apikey, string id, array batch, boolean double_optin, boolean update_existing, boolean replace_interests)

Maximum batch sizes vary based on the amount of data in each record, though you should cap them at 5k – 10k records, depending on your experience. These calls are also long, so be sure you increase your timeout values.

Unsubscribe a batch of emails.

MailChimp API Method:
lists/batch-unsubscribe (string apikey, string id, array batch, boolean delete_member, boolean send_goodbye, boolean send_notify)

Retrieve the clients that the list’s subscribers have been tagged as being used.

MailChimp API Method:
lists/clients (string apikey, string id)

Access the Growth History by Month in aggregate or for a given list.

MailChimp API Method:
lists/growth-history (string apikey, string id)

Add a single Interest Group.

MailChimp API Method:
lists/interest-group-add (string apikey, string id, string group_name, int grouping_id)

If interest groups for the List are not yet enabled, adding the first group will automatically turn them on.

Delete a single Interest Group.

MailChimp API Method:
lists/interest-group-del (string apikey, string id, string group_name, int grouping_id)

If the last group for a list is deleted, this will also turn groups for the list off.

Change the name of an Interest Group.

MailChimp API Method:
lists/interest-group-del (string apikey, string id, string old_name, string new_name, int grouping_id)

Get the list of interest groupings for a given list.

MailChimp API Method:
lists/interest-groupings (string apikey, string id, bool counts)

Add a new Interest Grouping.

MailChimp API Method:
lists/interest-grouping-add (string apikey, string id, string name, string type, array groups)

If interest groups for the List are not yet enabled, adding the first grouping will automatically turn them on.

Delete an existing Interest Grouping.

MailChimp API Method:
lists/interest-grouping-del (string apikey, int grouping_id)

This will permanently delete all contained interest groups and will remove those selections from all list members.

Update an existing Interest Grouping.

MailChimp API Method:
lists/interest-grouping-update (string apikey, int grouping_id, string name, string value)

Retrieve all of the lists defined for your user account.

MailChimp API Method:
lists/list (string apikey, struct filters, int start, int limit, string sort_field, string sort_dir)

Retrieve the locations (countries) that the list’s subscribers have been tagged to.

MailChimp API Method:
lists/locations (string apikey, string id)

Get the most recent 100 activities for particular list members.

MailChimp API Method:
lists/member-activity (string apikey, string id, array emails)

Get all the information for particular members of a list.

MailChimp API Method:
lists/member-info (string apikey, string id, array emails)

Get all of the list members for a list.

MailChimp API Method:
lists/members (string apikey, string id, string status, struct opts)

MailChimp API Method:
gallery/list (string apikey, struct opts)

PHP Stock Market API

Here’s a quick API script I put together to help monitor my stocks. It’s a PHP Stock Market API that uses the Yahoo! Finance API and allows you to retrieve up to 20 current data points for a particular symbol. It’s simple to use and doesn’t require any knowledge on how to implement or use the Yahoo! Finance API.

Looking to grab the latest stock market data? There’s a surprising lack of stock market APIs out there and even fewer that work consistently or affordable. Never fear, the PHP Stock Market API is here!

The PHP Stock Market API is a simple PHP class that uses the Yahoo! Finance API allowing you to retrieve up to 20 current data points for a particular symbol. It’s simple to implement and doesn’t require you to learn how to use the Yahoo! API.

UPDATE (Nov. 28, 2014, v1.3): getData now allows an array to pull multiple stocks at once (thanks @d3vit).
UPDATE (Jan. 27, 2014, v1.2): You can now also retrieve historical data (open, high, low, close, volume & adjusted close).

Download Now (Version 1.3) Fork on GitHub


PHP Stock Market API Usage

With just a few lines of code, you can easily retrieve 20 current data points. Here’s how it works:

<?php
require_once('class.stockMarketAPI.php');
?>

<h1>Current Stock Information for AAPL</h1>

<?php
$StockMarketAPI = new StockMarketAPI;
$StockMarketAPI->symbol = 'AAPL';
?>
<pre><?php print_r($StockMarketAPI->getData());?></pre>

<?php
$start = '01-01-2013';
$end = '01-07-2013';
?>
<h1>Historical Stock Information for AAPL (<?php echo $start ?> - <?php echo $end ?>)</h1>
<?php
$StockMarketAPI = new StockMarketAPI;
$StockMarketAPI->symbol = 'AAPL';
$StockMarketAPI->history = array(
  'start'    => $start,
  'end'    => $end,
  'interval' => 'd' // Daily
);
?>
<pre><?php print_r($StockMarketAPI->getData());?></pre>

<hr>

<h1>Stock Information for AAPL, MSFT, GOOGL</h1>
<?php
$StockMarketAPI = new StockMarketAPI;
$StockMarketAPI->symbol = array('AAPL', 'MSFT', 'GOOGL');
?>
<pre><?php print_r($StockMarketAPI->getData());?></pre>