Mixpanel PHP Library

The Mixpanel PHP library is designed to be used for scripting, or in circumstances when a client can't or won't run client side scripts.

Mixpanel also provides a powerful and easy to use client-side JavaScript library for web applications. This library offers platform-specific features and conveniences that can make Mixpanel implementations much simpler, and can scale naturally to an unlimited number of clients. The client-side JavaScript library is the preferred way to add Mixpanel to user-facing web applications.

Installing the library

You can get the library using Composer by including the following in your project's composer.json requirements and running composer update:

"require": {
    ...
    "mixpanel/mixpanel-php" : "2.*"
    ...
}

If you're not using Composer for your package management, you can browse and download the library from GitHub at https://github.com/mixpanel/mixpanel-php.

Our library requires PHP 5.0 or greater.

Sending events

Track events in the mixpanel-php library by using the track method on the Mixpanel class:

<?php
// import dependencies (using composer's autoload)
// if not using Composer, you'll want to require the
// lib/Mixpanel.php file here
require 'vendor/autoload.php';

// get the Mixpanel class instance, replace with your
// project token
$mp = Mixpanel::getInstance("MIXPANEL_PROJECT_TOKEN");

// track an event
$mp->track("button clicked", array("label" => "sign-up"));

Mixpanel determines default geolocation data ($city, $region, mp_country_code) using the IP address on the incoming request. As all server-side calls will likely originate from the same IP (that is, the IP of your server), this can have the unintended effect of setting the location of all of your users to the location of your datacenter. Read about best practices for geolocation with server-side implementations.

Super properties

Super properties are properties that get sent with every subsequently tracked event. This is very useful for associating properties such as "Ad Source" to every event. If I want to send an "Ad Source" of "Google" for every event I track, I can store it in my Mixpanel instance with the register method:

<?php
require 'vendor/autoload.php';
$mp = Mixpanel::getInstance("MIXPANEL_PROJECT_TOKEN");

// register the Ad Source super property
$mp->register("Ad Source", "Google");

// track an event with a property "Ad Source" = "Google"
$mp->track("button clicked");
In the PHP Library, registered Super Properties are only persisted for the life of the Mixpanel class instance. In general this will mean for the life of a single HTTP request.

Managing user identity

In many cases you'll want to track multiple actions that a user takes over time. To do this, you'll need to provide a distinct id to the library- a unique identifier associated with the source of events (usually a user)

To associate a distinct id with the events that you send, call identify, which associates a user to subsequent tracked events.

<?php
require 'vendor/autoload.php';
$mp = Mixpanel::getInstance("MIXPANEL_PROJECT_TOKEN");

// identify the current request as user 12345
$mp->identify(12345);

// track an event associated to user 12345
$mp->track("Logged In");
In the PHP Library, the value passed to identify is only persisted for the life of the Mixpanel instance. In general this will mean for the life of a single HTTP request.

In situations where you want to link the two IDs (in practice, this really just means when a previously anonymous user signs up) you can use createAlias. Alias sends an update to mixpanel's servers, mapping a new id to existing distinct_id, so that events and profile updates associated with the new id will be remapped to the existing user's behavior.

<?php
require 'vendor/autoload.php';
$mp = Mixpanel::getInstance("MIXPANEL_PROJECT_TOKEN");

// create an alias for user 12345 (note that this is done asynchronously). Any subsequent events with a distinct_id equal to "johndoe1" will be remapped to "12345".
$mp->createAlias("12345", "johndoe1");

Storing user profiles

In addition to events, you can send People Analytics profile updates to Mixpanel. Mixpanel can maintain a profile of each of your users, storing information you know about them. An update is a message that changes the properties of a People Analytics profile.

You can use profiles to explore and segment users by who they are, rather than what they did. You can also use profiles to send notifications, such as emails, SMS, or push notifications.

Mixpanel determines default geolocation data ($city, $region, mp_country_code) using the IP address on the incoming request. As all server-side calls will likely originate from the same IP (that is, the IP of your server), this can have the unintended effect of setting the location of all of your users to the location of your datacenter. Read about best practices for geolocation with server-side implementations.

Setting profile properties

The Mixpanel class has a public property called people that exposes an instance of Producers_MixpanelPeople that you can use to make profile updates.

<?php
require 'vendor/autoload.php';
$mp = Mixpanel::getInstance("MIXPANEL_PROJECT_TOKEN");

// create or update a profile with First Name, Last Name,
// E-Mail Address, Phone Number, and Favorite Color
$mp->people->set(12345, array(
    '$first_name'       => "John",
    '$last_name'        => "Doe",
    '$email'            => "john.doe@example.com",
    '$phone'            => "5555555555",
    "Favorite Color"    => "red"
));

The call to people->set will set the value of properties on user 12345's profile. If there isn't a profile with distinct_id 12345 in Mixpanel already, a new profile will be created. If user 12345 already has has any of these properties set on their profile, the old value will be overwritten with the new ones.

Incrementing numeric properties

You can change the current value of numeric properties using people->increment. This is useful when you want to keep a running tally of things, such as games played, emails sent, or points earned.

<?php
require 'vendor/autoload.php';
$mp = Mixpanel::getInstance("MIXPANEL_PROJECT_TOKEN");

// increment user 12345's "login count" by one
$mp->people->increment(12345, "login count", 1);

// Use negative numbers to subtract- reduce
// "credits remaining" by 10
$mp->people->increment(12345, "credits remaining", -10);

Appending to list properties

Use people->append to add an item to an existing list-valued property. The values you send with the append will be added to the end of the list for each named property. If the property doesn't exist, it will be created with a one element list as its value.

<?php
require 'vendor/autoload.php';
$mp = Mixpanel::getInstance("MIXPANEL_PROJECT_TOKEN");

// append "Apples" to user 12345's "favorites"
$mp->people->append(12345, "favorites", "Apples");

Other types of profile updates

There are a few other types of profile updates. They're exposed as public methods of Producers_MixpanelPeople.

Tracking revenue

Mixpanel makes it easy to analyze the revenue you make from individual customers. By associating charges with user profiles, you can compare revenue across different customer segments and calculate things like lifetime value.

You can track a single transaction with the trackCharge method on the Mixpanel->people object. Sending a message created with trackCharge will add transactions to the individual user profile, which will be reflected in the Mixpanel Revenue report.

<?php
require 'vendor/autoload.php';
$mp = Mixpanel::getInstance("MIXPANEL_PROJECT_TOKEN");

// track a purchase or charge of $9.99 for user 12345
// where the transaction happened just now
$mp->people->trackCharge(12345, "9.99");

// track a purchase or charge of $20 for user 12345
// where the transaction happened on June 01, 2013 at 5pm EST
$mp->people->trackCharge(12345, "20.00", strtotime("01 Jun 2013 5:00:00 PM EST"));

Scaling your server side tracking

Message Consumers

The PHP library stores all events and profile updates in an in-memory queue, that is flushed automatically when the instance of Mixpanel is destroyed, or when the queue reaches a configurable threshold size (by default, 1000 items). You can also force the instance to send on demand by calling flush.

At flush time, the messages are processed by an implementation of the ConsumerStrategies_AbstractConsumer class that determines how the messages will be written. The default settings use ConsumerStrategies_CurlConsumer, which uses cURL to write the messages over SSL to Mixpanel.

As your application scales, you may want to separate the IO for communicating with Mixpanel out of the processes that observe your events. You can write your events and updates to a file or a distributed queue by writing your own custom consumer.

To create a custom consumer, you'll want to extend ConsumerStrategies_AbstractConsumer and implement the persist method. Then you'll want to register it with the Mixpanel class and specify it for use.

<?php
// Here's a simple consumer that just writes the events to
// send out to the client.
class MyLoggingConsumer extends ConsumerStrategies_AbstractConsumer {
    public function persist($batch) {
        echo "<pre>";
        echo "Would send batch:\n";
        echo json_encode($batch) . "\n";
        echo "</pre>"
        return true;
    }
}

$mp = new Mixpanel("MIXPANEL_PROJECT_TOKEN", array(
    // Provide the name of your consumer class to the Mixpanel constructor
    "consumers" => array("logger" => "MyLoggingConsumer"),

    // Now tell the Mixpanel instance to use your class
    "consumer" => "logger"
));

// This event will be sent to the client in a <pre> tag
$mp->track("test_event", array("color" => "blue"));