Tracking unique visitors is one of the most common tasks in web development. Whether you need analytics, personalization, or user session continuity, assigning each client a unique identifier and saving it in a cookie is a reliable and widely supported approach.
In this article, you’ll learn how to:
- Generate a unique identifier for each user
- Store the identifier in a cookie
- Retrieve the cookie on future visits
- Use modern techniques in languages like PHP, JavaScript, Node.js, and Python
- Follow best practices for security and SEO
Let’s begin with the classic: PHP.
Why Use a Unique Client Identifier?
A unique identifier (UID) allows your website to:
- Recognize returning visitors
- Track user actions across sessions (e.g., analytics)
- Personalize content
- Maintain long-term preferences
- Improve conversion tracking
Unlike sessions—which expire when the browser closes—cookies can last days, months, or years, depending on your needs.
1. Creating a Unique Client Identifier in PHP
PHP makes cookie management straightforward. The logic is simple:
- Check whether a cookie already exists.
- If it does, use its stored value.
- If not, generate a new unique ID and save it in a cookie.
Basic Example (PHP)
<?php
$cookieName = 'client_uid';
// Check if the cookie already exists
if (isset($_COOKIE[$cookieName])) {
$clientId = $_COOKIE[$cookieName];
echo "Welcome back! Your unique ID is: $clientId";
} else {
// Generate a strong unique identifier
$clientId = bin2hex(random_bytes(16));
// Cookie valid for 1 year
setcookie($cookieName, $clientId, [
'expires' => time() + 365*24*60*60,
'path' => '/',
'secure' => isset($_SERVER['HTTPS']),
'httponly' => true,
'samesite' => 'Lax'
]);
echo "Hello new visitor! A unique ID has been generated for you.";
}
?>
Why this version is better than the usual uniqid()
random_bytes()provides cryptographically secure randomnessbin2hex()makes it URL-safesetcookie()with an array uses modern PHP 7.3+ syntax- Secure flags help prevent cookie theft
2. Using the Identifier in Your Application
Once you have $clientId, you can:
Store user analytics
file_put_contents("visitors.log", "$clientId visited at ".date('c')."\n", FILE_APPEND);
Personalize content
if ($clientId === 'some-known-id') {
echo "Welcome back, loyal visitor!";
}
Save preferences in a database
$stmt = $pdo->prepare("UPDATE users SET last_visit=NOW() WHERE uid=?");
$stmt->execute([$clientId]);
3. A More Advanced PHP Example With User-Agent + IP
Sometimes you want a UID based on client characteristics (still anonymous):
$entropy = $_SERVER['HTTP_USER_AGENT']
. $_SERVER['REMOTE_ADDR']
. microtime(true);
$clientId = hash('sha256', $entropy);
Use this with caution because IP-based identifiers may change.
Modern Examples in Other Languages
Today’s applications often use JavaScript, Node, or Python. Here are equivalent implementations.
4. JavaScript (Client-Side)
Client-side JavaScript cannot set HTTP-only cookies, but it can set regular cookies.
Generate UID and store in cookie (JavaScript)
function getClientId() {
const cookieName = "client_uid=";
const cookies = document.cookie.split(";");
// Check if cookie exists
for (const c of cookies) {
const trimmed = c.trim();
if (trimmed.startsWith(cookieName)) {
return trimmed.substring(cookieName.length);
}
}
// Create new identifier
const uid = crypto.randomUUID();
document.cookie = `client_uid=${uid}; path=/; max-age=${365*24*60*60}`;
return uid;
}
const clientId = getClientId();
console.log("Client ID:", clientId);
Uses:
- lightweight analytics
- single-page applications
- personalization
5. Node.js Example (Express)
Node.js is commonly used for modern backend APIs.
Express Example
const express = require('express');
const cookieParser = require('cookie-parser');
const crypto = require('crypto');
const app = express();
app.use(cookieParser());
app.get('/', (req, res) => {
let clientId = req.cookies.client_uid;
if (!clientId) {
clientId = crypto.randomBytes(16).toString('hex');
res.cookie('client_uid', clientId, {
maxAge: 365*24*60*60*1000,
httpOnly: true,
secure: true,
sameSite: 'lax',
});
res.send("New visitor. Unique ID generated.");
} else {
res.send(`Welcome back! Your ID is: ${clientId}`);
}
});
app.listen(3000, () => console.log("Server running on port 3000"));
6. Python Example (Flask)
Flask Example
from flask import Flask, request, make_response
import secrets
app = Flask(__name__)
@app.route("/")
def index():
client_id = request.cookies.get("client_uid")
if not client_id:
client_id = secrets.token_hex(16)
resp = make_response("New visitor. ID generated.")
resp.set_cookie("client_uid", client_id, max_age=365*24*60*60, httponly=True, samesite='Lax')
return resp
else:
return f"Welcome back! Your ID is: {client_id}"
if __name__ == "__main__":
app.run()Best Practices for Client Identifiers
- Use HTTPS to avoid cookie theft
- Prefer secure random identifiers
- Avoid storing personal data in cookies
- Inform users about cookies (GDPR compliance in EU)
- Use
HttpOnly,Secure, andSameSite - Never use IP address alone—it changes
- Set reasonable expiration times
Final Thoughts
Creating a unique client identifier and storing it in cookies is a fundamental technique for building modern, intelligent web applications. With just a few lines of code—whether in PHP, JavaScript, Node.js, or Python—you can reliably track users, personalize content, and build advanced analytics.

