Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

andremellow's avatar

Cache per session with Redis

I've a really dynamic app, where every content showed to user is based on his ( state / city / department / or even the user id )

So I would like to cache based on user ID. I can use the user ID in the end of key like KEY.USER_ID.

Is it possible to delete the keys using regex? Or any one have any other idea?

0 likes
2 replies
kfirba's avatar
kfirba
Best Answer
Level 50

@andremellow why would you want to manually remove an item from the cache when you don't know the ID?

Think about it, the only reason you would want to clear the cache would be when something about your user changes. When it does, you know the user ID so you can just easily build the key and remove it.

Anyways, you can do that through redis-cli:

redis-cli keys "KEY:*" | grep "KEY:[0-9]\+$" | xargs redis-cli DEL

You can run this directly in your terminal or just use php's exec command.

1 like
andremellow's avatar

@kfirba , thanks for your answer.

The content are published for other users, and on dashboard I have thinks like "Important" and "must read" content. But one post that are important for one user, can not be for other.

So, every time a new content flaged as important are published, I'll clear the cache for "dashboard important content", for example.

Please or to participate in this conversation.