PHP

API Integration

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

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.

EU Data Residency

Route data to Mixpanel's EU servers by setting a host configuration during initialization.

<?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 with your project token
$mp = Mixpanel::getInstance("YOUR TOKEN", array("host" => "api-eu.mixpanel.com"));

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");

📘

NOTE

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.

Super Properties Live in Local Storage

Mixpanel's server-side libraries do not automatically append "super properties" to their events. You are more than welcome to roll your own system to append whatever properties you'd like to events for a given user. The most important thing to note when dealing with appending properties server side is that you must include a value for the (traditionally super) property "distinct_id" in order to use the events in most Mixpanel reports. The distinct_id property ties an event to a specific user.

Managing User Identity

Mixpanel groups events sent with different distinct_ids, presenting them in reports as different user event streams. You can connect events with different distinct_ids using alias, identify, or merge, ultimately attributing them to one user.

📘

ID Merge

If a project has ID merge enabled, the $identify event can connect pre- and post-authentication events. If ID merge is not enabled, identify events will not link identities however alias can be used to connect pre and post registration events.

Storing User Profiles

In addition to events, you can send user 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 user 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 messages, 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
// without updating geolocation data or $last_seen
$mp->people->set(12345, array(
    '$first_name'       => "John",
    '$last_name'        => "Doe",
    '$email'            => "[email protected]",
    '$phone'            => "5555555555",
    "Favorite Color"    => "red"
), $ip = 0, $ignore_time = true);

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.

📘

NOTE

Pick your property names wisely. Once you've sent them to Mixpanel, there is no way to change them. Feel free to use capitalization and spaces in between words.
There are a few limitations:

  • Your property names should not begin with $ or mp_. These properties are reserved for special properties sent by Mixpanel.
  • Your property names cannot begin or end with a space as they will automatically be trimmed.
  • Your property names and values cannot be longer than 255 characters. In practice they should be much shorter than that. Property names get cut off by our user interface at about 20 characters.

Click here to see a list of Mixpanel's reserved user profile properties.

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"));

Debugging and Logging

You can turn on Mixpanel logging by enabling the "debug" flag in your initialization:

<?php
require "vendor/autoload.php";
$mp = Mixpanel::getInstance("MIXPANEL_PROJECT_TOKEN", array("debug" => true));

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"));