Welcome Guest, Not a member yet? Register   Sign In
Cache best practice?
#1

(This post was last modified: 02-27-2024, 03:27 AM by CIDave.)

Hello all!
I am currently implementing caching to my site. I'm using Memcached with a fallback to files.
I wanted to know what is the best practice for caching in terms of validating user input.
I am caching an article, where I get the article slug from the URI.
PHP Code:
$slug $this->clean($slug);

$content $cache->get("article_" $slug);
if(!
$content) {
  // Get article from DB and recache
  
  
if(!$articleerror("Bad article");

  // cache
  $cache->save("article_" $article->slug$article->content3600);
}

echo 
$content
This is just a crude example. I'm assuming it is fine to lookup the cache object based on user input (i.e. the $cache->get("article_" . $slug) line). I can see a static::validateKey in the cache library file that seems to do it's own sanitizing too.
Or should I always be checking to see if the article exists by doing a DB query (kinda defeating the point i guess).
Does this seem correct and valid?
Reply
#2

Your approach looks good! Here's a confirmation and some additional tips for caching with user input validation:

Yes, using a cache key derived from sanitized user input (like your $slug) is a common practice.  Cache libraries often have built-in validation methods (like static::validateKey).  Trust but verify is a good approach -  letting the cache library handle basic validation but also validating the slug existence in your application logic for an extra layer of security.

Here are some resources for best practices on caching with user input validation:

OWASP Cache Invalidation https://owasp.org/omegle/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/04-Authentication_Testing/06-Testing_for_Browser_Cache_Weaknesses
Key Considerations for Caching https://stackoverflow.com/questions/7441...issing-key
Reply




Theme © iAndrew 2016 - Forum software by © MyBB