Many unknown users come to e-commerce websites and cannot be identified. And even if it comes again and again, it is not clear when which user is coming. And here’s a great solution: It’s possible to separate spam and unknown users by storing the unique ID in a cookie for 1 year.

I will show you how to do it using only php/js here. This is a very good thing for spam protection.

Anonymous User Protection Code In PHP

<?php
if (!isset($_COOKIE['user_uid'])) { 
$uid = "uid-" . time() . "-" . bin2hex(random_bytes(5));
 setcookie("user_uid", $uid, time() + (365*24*60*60), "/");
} else {
 $uid = $_COOKIE['user_uid'];
}
echo "Unique User ID: " . htmlspecialchars($uid);
?>

Anonymous User Protection Code In JS

<script>

function getUserId() {
    let uid = localStorage.getItem("user_uid");
    if (!uid) {
        uid = "uid-" + Date.now() + "-" + Math.random().toString(36).substr(2, 9);
        localStorage.setItem("user_uid", uid);
    }
    return uid;
}

</script>

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply