Mixpanel SDKs: PHP

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

The Full API Reference, Library Source Code, and example scripts are documented in our Github repo.

Installing the Library

Note: Our library requires PHP 5.0 or greater.

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.*"
    ...
}

Once the library is installed, create an instance of the Mixpanel class with the getInstance() method using your project token.

Any data tracked using this Mixpanel instance will target your selected project.

<?php
// import dependencies
require 'vendor/autoload.php';
 
// create an instance of the Mixpanel class
$mp = Mixpanel::getInstance("YOUR_PROJECT_TOKEN");
 
?>

Manual Installation

If you’re not using Composer for your package management, you can browse and download the library from GitHub, extract the zip file to a directory called “mixpanel-php” in your project root, then import the library.

<?php
// import Mixpanel
require 'mixpanel-php/lib/Mixpanel.php';
 
// create an instance of the Mixpanel class
$mp = Mixpanel::getInstance("YOUR_PROJECT_TOKEN");
 
?>

Library Configuration

The Mixpanel class can be initialized with different configurations. See a complete list of the configuration options and default values here.

You can override the default configuration using the $options constructor argument when creating the Mixpanel instance.

<?php
// import dependencies
require 'vendor/autoload.php';
 
// create an instance of the Mixpanel class
$mp = Mixpanel::getInstance("YOUR_PROJECT_TOKEN", array(
    "max_batch_size" => 100,    // set the maximum batch size to 100
    "debug"          => true    // enable debug mode
    ));
 
?>

EU Data Residency

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

<?php
// import dependencies
require "vendor/autoload.php";
 
// create an instance of the Mixpanel class
$mp = Mixpanel::getInstance("YOUR_PROJECT_TOKEN", array(
    "host" => "api-eu.mixpanel.com" // set host name for api calls to EU domain
    ));
 
?>

Sending Events

Track events using the track() method on the Mixpanel class. The track() method accepts two arguments ($event string and $properties array) to generate an event payload, then triggers a request to the /track API endpoint to ingest the event to your project.

The /track endpoint will only validate events with timestamps within the last 5 days of the request. Events with timestamps older than 5 days will not be ingested. See below on best practices for historical imports.

<?php
// import dependencies
require 'vendor/autoload.php';
 
// create an instance of the Mixpanel class
$mp = Mixpanel::getInstance("YOUR_PROJECT_TOKEN");
 
// Send a "button clicked" event containing 2 event properties
$mp->track("button clicked", array(
  "label"       => "sign-up", // "label" prop is set to "sign-up"
  "distinct_id" => "SOME_ID"  // "distinct_id" prop is set to "SOME_ID"
));
 
//by default, no distinct_id is included on events unless specified in the properties
//you can call identify so it's included in events during that script execution
?>

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 data center. Learn more about Geolocation best practices.

Importing Historical Events

The PHP SDK is a tracking SDK designed for real-time tracking in a server-side environment. Calling the track() method triggers a request to our /track API endpoint, which will validate for events with a timestamp that is within the last 5 days of the request. Events older than 5 days will not be ingested.

For bulk import of historical events older than 5 days, we will need to use the /import API endpoint which is optimized for scripting and supports ingesting historical data. We recommend the Python SDK (see the .import_data() function) and mixpanel-utils module (see the import_events() function) which both leverages the /import API for event ingestion.

You can also leverage the /import API directly for a more customized solution.

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, ultimately attributing them to one user. You will want to check which version of ID management you have enabled within Project Settings -> Identity Merge

If you have Original ID Merge enabled, you can an anonymous ID and your chosen user ID by calling the identify() method. This will send an $identify event containing both IDs and merge them under one identity cluster.

<?php
// import dependencies
require 'vendor/autoload.php';
 
// create an instance of the Mixpanel class
$mp = Mixpanel::getInstance("YOUR_PROJECT_TOKEN");
 
// send an "$identify" event to merge "USER_ID" and "ANON_ID" together
$mp->identify('USER_ID','ANON_ID');
 
?>

If you have Simplified ID Merge enabled, you will want to send any event that contains both the $device_id (set to the anonymous ID) and $user_id (set to your chosen user ID) properties. When a $user_id and a $device_id is detected in the same event for the first time, it triggers a merge of the 2 IDs.

<?php
// import dependencies
require 'vendor/autoload.php';
 
// create an instance of the Mixpanel class
$mp = Mixpanel::getInstance("YOUR_PROJECT_TOKEN");
 
//the call to identify is not necessary to connect the IDs,
//but it is practical as it will add the distinct_id to all events moving forward
$mp->identify("USER_ID");
 
// when a $user_id/$device_id pair is detected in the same event for the first time,
// a merge is triggered to map the 2 IDs together.
$mp->track("sign-up", array(
  '$device_id' => "ANON_ID",
  '$user_id' => "USER_ID"
));
 
?>

Note: For projects on our legacy ID management model (it will read as ID Merge is not enabled within project settings), you can read about using $create_alias to link IDs here.

Learn more about ID management in our tracking guide.

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. Learn more about best practices for geolocation.

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.

Use the people->set() method to create properties on a user record. If the profile does not exist, it will be created using the properties defined in the method. If the properties already exist, they will be overwritten.

<?php
// import dependencies
require 'vendor/autoload.php';
 
// create an instance of the Mixpanel class
$mp = Mixpanel::getInstance("YOUR_PROJECT_TOKEN");
 
// create or update a profile with First Name, Last Name,
// E-Mail, Phone Number, and Favorite Color
$mp->people->set("USER_ID", array(
    '$first_name'       => "John",
    '$last_name'        => "Doe",
    '$email'            => "john.doe@example.com",
    '$phone'            => "5555555555",
    "Favorite Color"    => "red"
), $ip = 0, $ignore_time = true);   // set $ip to 0 to prevent profile geolocation update

Note: Pick your property names wisely. Please note the following guidelines:

  • 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
// import dependencies
require 'vendor/autoload.php';
 
// create an instance of the Mixpanel class
$mp = Mixpanel::getInstance("YOUR_PROJECT_TOKEN");
 
// increment user 12345's "login count" by one
$mp->people->increment("USER_ID", "login count", 1);
 
// Use negative numbers to subtract
// reduce "credits remaining" by 10
$mp->people->increment("USER_ID", "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
// import dependencies
require 'vendor/autoload.php';
 
// create an instance of the Mixpanel class
$mp = Mixpanel::getInstance("YOUR_PROJECT_TOKEN");
 
// append "Apples" to user 12345's "favorites"
// favorites = ["Apples"]
$mp->people->append("USER_ID", "favorites", "Apples");
 
// append "Orange" to user 12345's "favorites"
// favorites = ["Apples","Orange"]
$mp->people->append("USER_ID", "favorites", "Orange");

Other Types of Profile Updates

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

Debugging and Logging

You can turn on Mixpanel logging by enabling the debug flag in your Mixpanel class configuration:

<?php
// import dependencies
require 'vendor/autoload.php';
 
// create an instance of the Mixpanel class
$mp = Mixpanel::getInstance("YOUR_PROJECT_TOKEN", array(
    "debug" => true //set debug to true
    ));
 
?>

Scaling your Server-Side Tracking

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

Was this page useful?