Skip to main content

track email link


1. Database Setup
First, create a database table to store the click information. This example uses a MySQL table called link_clicks. 

sql

2. The Tracking Script (track_click.php) 
This PHP script will receive the click request, log the data to the database, and redirect the user. 

php
<?php
// track_click.php

// Include your database connection file (e.g., db_connect.php)
// Ensure you use prepared statements for security against SQL injection.
$servername = "localhost";
$username = "db_user";
$password = "db_password";
$dbname = "your_database";

try {
    $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    // In a production environment, you would log this error and display a generic message
    die("Database connection failed: " . $e->getMessage());
}

// Get parameters from the URL
$userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$linkId = isset($_GET['link_id']) ? (int)$_GET['link_id'] : 0;
// The actual destination URL (must be URL-encoded when creating the link)
$redirectUrl = isset($_GET['redirect_url']) ? urldecode($_GET['redirect_url']) : '';

if ($userId > 0 && $linkId > 0 && !empty($redirectUrl)) {
    // Log the click in the database
    $stmt = $pdo->prepare("INSERT INTO link_clicks (user_id, link_id, ip_address) VALUES (?, ?, ?)");
    $ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN'; // Get the user's IP address
    $stmt->execute([$userId, $linkId, $ipAddress]);

    // Redirect the user to the original destination URL
    header("Location: " . $redirectUrl);
    exit(); // Important to exit after a header redirect
} else {
    // Handle cases where parameters are missing or invalid
    header("HTTP/1.1 400 Bad Request");
    die("Invalid tracking parameters.");
}
?>

3. Generating Trackable Links in the Email
When you send the email, you programmatically generate links that point to your track_click.php script and include the necessary data as query parameters. 

php
<?php
// Code to generate the email content

$userId = 123; // Example User ID
$linkId = 1;   // Example Link ID
$destinationUrl = "https://www.example.com/special-offer"; // The final destination

// URL-encode the destination URL
$encodedUrl = urlencode($destinationUrl);

// Construct the tracking link
$trackingLink = "yourdomain.com" . $userId . "&link_id=" . $linkId . "&redirect_url=" . $encodedUrl;

// In your HTML email body:
$emailBody = '<a href="' . htmlspecialchars($trackingLink) . '">Click here for the special offer!</a>';
// ... rest of your email sending code
?>
By implementing this method, the click will first hit your PHP script, which records the event, and then automatically redirect the user to their intended destination without them noticing the intermediate step.