How to get the UTM using PHP?

10,539

Before we worry about getting the value of the UTM attributes, you have a security issue that needs some attention. You are currently taking un-sanitised (unsafe) user input (via $_POST['var']) and putting it straight into a database query, which is an unsafe practice that allows SQL injection (e.g. a malicious user can send you a specially crafted string that gives them the ability to do whatever they like to your database).

Please have a read of this Stack Overflow question on how to avoid SQL injection in PHP.

Typically, the standard utm parameters for tracking where a user comes from form part of the query string, for example:

http://yoursite.com?utm_source=google&utm_campaign=campaign_name

Unless you are doing something non-standard, this will be a GET request to your server (as opposed to a POST) so your variables will be available via the $_GET superglobal. For example $_GET['utm_source'] and $_GET['utm_campaign']

Looking at your table schema, you may also need to add auto_increment to your ID column, so that it will get a value automatically when a new row is added.

ALTER TABLE `utm_param` 
CHANGE COLUMN `id` `id` INT(100) NOT NULL AUTO_INCREMENT;
Share:
10,539
User014019
Author by

User014019

:)

Updated on June 04, 2022

Comments

  • User014019
    User014019 almost 2 years

    I'm new with UTM (Urchin tracking module) and I want to get the UTM parameters where the user clicked the link from (e.g. facebook, google, twitter) and how many time the user clicked the link with same utm source and save it to the mysql database.

    I have a PHP snippet but the utm parameters didn't get and save in the database.

    How to fix this?

    if(isset($_SERVER['HTTP_REFERER'])){
     $utm_source = isset($_GET['utm_source']) ? $_GET['utm_source'] : '';
     $utm_medium = isset($_GET['utm_medium']) ? $_GET['utm_medium'] : '';
     $utm_campaign = isset($_GET['utm_campaign']) ? $_GET['utm_campaign'] : '';
     $utm_term = isset($_GET['utm_term']) ? $_GET['utm_term'] : '';
    
    echo $_SERVER['HTTP_REFERER'];
    
    $sql = "INSERT INTO utm_param(utm_source,utm_medium,utm_campaign)
            VALUES('".$conn->real_escape_string($utm_source)."',
                   '".$conn->real_escape_string($utm_medium)."',
                   '".$conn->real_escape_string($utm_campaign)."')";
    }
    

    utm_param db table structure

    Describe utm_param;