Make this code only execute once per visitor, help appreciated

mphp

New member
Hi I am using this code in my index.php to send myself android notification about what sites are referring visitors to my website.
Issue I have is that I usually get 2 even 3 notification per visitor sometimes.
Is there any way to edit this code so that it only send 1 notification per referrer?

Code:
if (!empty($_SERVER['HTTP_REFERER'])) {               
    $refer = $_SERVER['HTTP_REFERER'];
}

$word1 = "google.";

if (!empty($refer) and !strpos($refer, $word1)) {
  
        // Target URL
    $url = "https://xdroid.net/api/message?k=k-8278286d&t=FROM&c={$refer}&u={$refer}";
      
        // Fetching headers, aka visit/ping $url above
    $headers = get_headers($url);
}
 
Try using sessions ...
Store the referrers that have already been processed ...so before sending notifications, it checks if the referrer is already in the session
 
or you can store the referrer in a session and check if it has changed before sending a new notification. Here's how you can modify your code:

Code:
<?php
session_start();

if (!empty($_SERVER['HTTP_REFERER'])) {
    $refer = filter_var($_SERVER['HTTP_REFERER'], FILTER_SANITIZE_URL);  // Sanitize the referrer

    // Check if the referrer has changed since the last request
    if (!isset($_SESSION['last_refer']) || $_SESSION['last_refer'] !== $refer) {
        $_SESSION['last_refer'] = $refer;

        $word1 = "google.";

        if (!empty($refer) && strpos($refer, $word1) === false) {  // Corrected strpos usage
            // Target URL
            $url = "https://xdroid.net/api/message?k=k-8278286d&t=FROM&c={$refer}&u={$refer}";

            // Fetching headers, aka visit/ping $url above
            $headers = @get_headers($url);  // Suppress errors and handle potential failure
            if ($headers === false) {
                // Handle failure (log, throw error, etc.)
            }
        }
    }
}
?>
 
Back
Top