6

I have a basic cache system setup which saves a file based on the parameters in the url so that if that page gets viewed again it accesses the static file. eg if my url is

http://www.example.com/female/?id=1

I have a file located in a cache folder called id=1.html

female/cache/id=1.html

currently this is cached for a specified amount of time however I want it to always use the cached file unless the page is updated.

So I implemented the below php code.

 <?
 unlink('../' . $gender . '/cache/id=' . $_POST['id'] . '.html');
 ?>

this works fine however, some times there are additional parameters in my url. So currently I have the below files in my cache folder

 female/cache/id=1.html
 female/cache/id=1&type=2.html
 female/cache/id=1&type=3.html
 female/cache/id=1&type=3&extra=4.html

But when I save my content only female/cache/id=1.html is removed.

How would I go about removing any file in this folder with the id=1

asked Aug 16, 2013 at 22:31
2
  • Please don't use short open tags <? ?> because it's a pain if you moved to an environment where it's disabled by default. Commented Aug 16, 2013 at 22:43
  • @HamZa thanks for the tip I hadn't thought about it to much but looking at my code here it is all using <?php but I will make sure I keep it in mind. Commented Aug 16, 2013 at 22:47

2 Answers 2

23

You could use glob:

<?php
foreach (glob("female/cache/id=1*.html") as $filename) {
 unlink($filename);
}
?>

Where the asterisk * matches all the variations of the filename.

answered Aug 16, 2013 at 22:36
Sign up to request clarification or add additional context in comments.

Comments

5

As an alternative, you can make the operation more concise using array_map():

<?php
array_map('unlink', glob('female/cache/id=1*.html'));
?>

http://php.net/manual/en/function.array-map.php

Be aware that array_map may be slower than a foreach loop: Performance of foreach, array_map with lambda and array_map with static function

However, this may no longer be the case under PHP 7.x. My results for the accepted answer's benchmark on 7.04:

  • Foreach: 0.096698999404907 // accepted answer's method
  • MapClosure: 0.10490107536316
  • MapNamed: 0.073607206344604 // my alternative
answered May 17, 2016 at 14:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.