PHP Delete all files containing the given string.

I have a basic configuration of a caching system that saves a file based on the parameters in the URL, so if this page is viewed again, it accesses a static file. for example if my url

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

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

 female/cache/id=1.html 

this is being cached for a while now, but I want it to always use the cached file if the page is not refreshing.

So, I applied the below PHP code.

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

this works great, but sometimes there are additional options in my url. So currently I have the following files in the 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 the woman / cache / id = 1.html is deleted.

How can I delete any file in this folder with id = 1

+4
source share
2 answers

You can use glob :

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

If the asterisk * matches all variants of the file name.

+17
source

Alternatively, you can make the operation shorter using array_map() :

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

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

Remember that array_map can be slower than the foreach loop: Foreach performance, array_map with lambda and array_map with static function

However, this may not be the case with PHP 7.x. My results for the accepted answer test 7.04:

  • Foreach: 0.096698999404907 // accepted response method
  • MapClosure: 0.10490107536316
  • MapNamed: 0.073607206344604 // my alternative
+3
source

Source: https://habr.com/ru/post/1497511/


All Articles