Title: ESI + PHP Snippet.
Last modified: January 21, 2024

---

# ESI + PHP Snippet.

 *  Resolved [malswe](https://wordpress.org/support/users/malswe/)
 * (@malswe)
 * [2 years, 4 months ago](https://wordpress.org/support/topic/esi-php-snippet/)
 * Hello! beginner dev here. I have tried to make this piece of PHP code to be excluded
   from being cached with ESI. But I can’t get it to work.
   This code:
 *     ```wp-block-code
       session_start(); // Start the session at the beginning of the script
   
       $servername = "localhost"; // your server name
       $username = "testbase"; // your database username
       $password = "123"; // your database password
       $dbname = "basetester"; // your database name
   
       // Check if either "msclkid" or "gclid" is present in the URL
       if (isset($_GET['msclkid']) || isset($_GET['gclid'])) {
           $conn = new mysqli($servername, $username, $password, $dbname);
           if ($conn->connect_error) {
               die("Connection failed: " . $conn->connect_error);
           }
   
           $ip_address = $_SERVER['REMOTE_ADDR'];
           $full_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
           $click_id = null;
   
           if (isset($_GET['msclkid']) && !empty($_GET['msclkid'])) {
               $click_id = urldecode($_GET['msclkid']);
           } elseif (isset($_GET['gclid']) && !empty($_GET['gclid'])) {
               $click_id = urldecode($_GET['gclid']);
           }
   
           // Store click_id in session
           $_SESSION['click_id'] = $click_id;
   
           $sql = "INSERT INTO visitor_log (ip_address, full_url, click_id) VALUES (?, ?, ?)";
           $stmt = $conn->prepare($sql);
           $stmt->bind_param("sss", $ip_address, $full_url, $click_id);
           if ($stmt->execute()) {
               echo "New record created successfully";
           } else {
               echo "Error: " . $stmt->error;
           }
           $stmt->close();
           $conn->close();
       }
       ```
   
 * However, I managed to get ESI working and exclude caching with the code below.
 *     ```wp-block-code
       add_action('litespeed_esi_load-custom_js_block', 'custom_js_block_load');
   
       function custom_js_block_load() {
   
           $ipList = [
               '192.168.0.1',
               '192.168.0.2',
               '192.168.0.3',
               // Add IPv6 addresses here, e.g., '2001:db8::/32'
           ];
   
           $userIp = $_SERVER['REMOTE_ADDR'];
           $matchFound = false;
           foreach ($ipList as $ipEntity) { 
               if (ipMatch($userIp, $ipEntity)) {
                   $matchFound = true;
                   break;
               }
           }
   
           if (!$matchFound) {
               return;
           }
           do_action('litespeed_control_set_nocache'); // Ensures this block isn't cached
           ?>
           <script type="text/javascript">
               window.addEventListener('beforeunload', function(e) {
                   e.preventDefault();
                   e.returnValue = '';
                   var confirmationMessage = 'Are you sure that you wanna quit?';
                   e.returnValue = confirmationMessage;
                   return confirmationMessage;
               });
           </script>
           <?php
       }
   
       function add_custom_js() {
           echo apply_filters('litespeed_esi_url', 'custom_js_block', 'Custom JS Block');
       }
       add_action('wp_footer', 'add_custom_js');
   
       function ipMatch($userIp, $ipEntity) {
           // If both IPs are IPv4
           if (strpos($userIp, ':') === false && strpos($ipEntity, ':') === false) {
               $userSegments = explode('.', $userIp);
               $entitySegments = explode('.', $ipEntity);
   
               $numSegments = count($userSegments);
               for ($i = 0; $i < $numSegments; $i++) {
                   if ($entitySegments[$i] === '*') {
                       continue;
                   }
                   if ($userSegments[$i] !== $entitySegments[$i]) {
                       return false;
                   }
               }
               return true;
           }
   
           // If both IPs are IPv6
           elseif (strpos($userIp, ':') !== false && strpos($ipEntity, ':') !== false) {
               return strtolower($userIp) === strtolower($ipEntity); // Simple equality check for IPv6
           }
   
           // Return false if none of the above conditions match
           return false;
       }
       ```
   
 * My best try:
 *     ```wp-block-code
       // Start the session at the beginning of the script
       session_start();
   
       // Function to handle database interaction
       function my_custom_db_code() {
           error_log('my_custom_db_code: Function called.'); // Debug
           do_action('litespeed_control_set_nocache'); // Ensures this block isn't cached
   
           $servername = "localhost"; // your server name
       $username = "testbase"; // your database username
       $password = "123"; // your database password
       $dbname = "basetester"; // your database name
   
           // Check if either "msclkid" or "gclid" is present in the URL
           if (isset($_GET['msclkid']) || isset($_GET['gclid'])) {
               error_log('my_custom_db_code: msclkid or gclid detected.'); // Debug
               $conn = new mysqli($servername, $username, $password, $dbname);
               if ($conn->connect_error) {
                   error_log('my_custom_db_code: Connection failed - ' . $conn->connect_error); // Debug
                   die("Connection failed: " . $conn->connect_error);
               }
   
               $ip_address = $_SERVER['REMOTE_ADDR'];
               $full_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
               $click_id = null;
   
               if (isset($_GET['msclkid']) && !empty($_GET['msclkid'])) {
                   $click_id = urldecode($_GET['msclkid']);
               } elseif (isset($_GET['gclid']) && !empty($_GET['gclid'])) {
                   $click_id = urldecode($_GET['gclid']);
               }
   
               // Store click_id in session
               $_SESSION['click_id'] = $click_id;
   
               $sql = "INSERT INTO visitor_log (ip_address, full_url, click_id) VALUES (?, ?, ?)";
               $stmt = $conn->prepare($sql);
               if ($stmt === false) {
                   error_log('my_custom_db_code: Prepare failed - ' . $conn->error); // Debug
               }
   
               $stmt->bind_param("sss", $ip_address, $full_url, $click_id);
               if ($stmt->execute()) {
                   error_log('my_custom_db_code: New record created successfully'); // Debug
               } else {
                   error_log('my_custom_db_code: Error on execute - ' . $stmt->error); // Debug
               }
               $stmt->close();
               $conn->close();
           } else {
               error_log('my_custom_db_code: msclkid and gclid not present.'); // Debug
           }
       }
   
       // Register the function with LiteSpeed ESI
       add_action('litespeed_esi_load-my_custom_db_code', 'my_custom_db_code');
   
       // Function to invoke ESI URL
       function add_my_custom_db_code() {
           error_log('add_my_custom_db_code: Function called.'); // Debug
           // This filter call outputs the ESI URL
           echo apply_filters('litespeed_esi_url', 'my_custom_db_code', 'My Custom DB Code');
       }
   
       // Hook the ESI URL invocation function to wp_head
       add_action('wp_head', 'add_my_custom_db_code');
       ```
   
 * 
   Could someone please help me? Many thanks!
 * The page I need help with: _[[log in](https://login.wordpress.org/?redirect_to=https%3A%2F%2Fwordpress.org%2Fsupport%2Ftopic%2Fesi-php-snippet%2F%3Foutput_format%3Dmd&locale=en_US)
   to see the link]_

Viewing 4 replies - 1 through 4 (of 4 total)

 *  Plugin Support [qtwrk](https://wordpress.org/support/users/qtwrk/)
 * (@qtwrk)
 * [2 years, 4 months ago](https://wordpress.org/support/topic/esi-php-snippet/#post-17360712)
 * which part of code it didn’t work ?
 * for instance I don’t think ESI request will have these msclkid or glicid query
   strings
 *  Thread Starter [malswe](https://wordpress.org/support/users/malswe/)
 * (@malswe)
 * [2 years, 4 months ago](https://wordpress.org/support/topic/esi-php-snippet/#post-17361103)
 * Nothing works, only on warm-up :/
 *  Thread Starter [malswe](https://wordpress.org/support/users/malswe/)
 * (@malswe)
 * [2 years, 4 months ago](https://wordpress.org/support/topic/esi-php-snippet/#post-17361146)
 * (original code works only on warm up)
   The ESI code does not work at all
 *  Plugin Support [qtwrk](https://wordpress.org/support/users/qtwrk/)
 * (@qtwrk)
 * [2 years, 4 months ago](https://wordpress.org/support/topic/esi-php-snippet/#post-17364313)
 * none of these error_log’s show anything ?

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘ESI + PHP Snippet.’ is closed to new replies.

 * ![](https://ps.w.org/litespeed-cache/assets/icon-256x256.png?rev=2554181)
 * [LiteSpeed Cache](https://wordpress.org/plugins/litespeed-cache/)
 * [Frequently Asked Questions](https://wordpress.org/plugins/litespeed-cache/#faq)
 * [Support Threads](https://wordpress.org/support/plugin/litespeed-cache/)
 * [Active Topics](https://wordpress.org/support/plugin/litespeed-cache/active/)
 * [Unresolved Topics](https://wordpress.org/support/plugin/litespeed-cache/unresolved/)
 * [Reviews](https://wordpress.org/support/plugin/litespeed-cache/reviews/)

## Tags

 * [esi](https://wordpress.org/support/topic-tag/esi/)

 * 4 replies
 * 2 participants
 * Last reply from: [qtwrk](https://wordpress.org/support/users/qtwrk/)
 * Last activity: [2 years, 4 months ago](https://wordpress.org/support/topic/esi-php-snippet/#post-17364313)
 * Status: resolved