Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running uncached PHP in a Drupal template?

I need to run a PHP code snippet in a Drupal template and prevent it from being cached. The PHP snippet sniffs for a cookie and if found, returns a message based on the cookie value.

ie:

if(isset($_GET['key'])) { 
    $cookievalue = $_GET['key']; 
}

if(isset($_COOKIE['cookname'])) { 
    $cookievalue = $_COOKIE['cookname']; 
}

switch ($cookievalue) { 
    case hmm01: echo "abc"; 
    break; 
    case hmm02: echo "def";
    break; 
    case hmm03: echo "ghi"; 
    break; 
    default: echo "hello"; 
}

Right now, Drupal renders the messages randomly according to when the page was first cached and based on the cookie used at the time.

I can't see a great deal of info on how I might go about this - it seems that you have to turn the cache off for the page rather than run php code uncached.

Can the community guide me on how to use the correct technique with regards to Drupal templating and PHP based on the information I posted or direct me to a guide or tutorial that may be useful for my situation?

like image 880
lokust Avatar asked Dec 31 '25 04:12

lokust


1 Answers

Your problem is that Drupal caches pages which is a good thing since you would probably get a huge performance hit otherwise.

A solution, though not so pretty is to let a js post the data with Ajax. Since Drupal don't cache post requests this could be a solution. It is however js dependant and makes an extra request which requires extra system resources. But atleast it is better than disBling the page cache.

Edit:

After giving it some thought, I think a better solution would be to create a custom block. Since Drupal blocks has their own caching system you should be able to get the functionality you want. Custom blocks is created with the use of hook_block

like image 111
googletorp Avatar answered Jan 04 '26 00:01

googletorp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!