Using a wildcard in php unlink

吃可爱长大的小学妹 提交于 2020-08-27 22:29:28

问题


I am currently making a php script to graph a bunch of data from a DB, arrange it into text files and then run a GNUPlot script to generate graphs. I have all of this working , now all I need to do is delete the text files I don't need anymore.

What I have been trying was gotten from another thread on a different forum:

foreach( glob('US_A.2.6.*') as $file )
    {
        unlink($file);
    }

The problem, however, is that it doesn't work. The files have complex end names:

  • US_A.2.6.1.1a.txt
  • US_A.2.6.1.2a.txt
  • US_A.2.6.1.3a.txt
  • US_A.2.6.1.4a.txt
  • US_A.2.6.1.5a.txt
  • US_A.2.6.1.6a.txt

And more.


回答1:


Check your working directory with getcwd(). If you are not in the same directory as your text files, you will need to specify the path.

Also, try echoing the output of the glob() statement to see if it is finding any files:

echo $file . PHP_EOL;
unlink($file);

You are not checking the unlink() return value, so it could be failing silently (depending on your error_reporting level) if the files are unwritable.




回答2:


Depending on your constraints, you may be able to generate more concise code at the cost of it being less cross-platform portable, by using the exec() call. I prefer giving absolute paths, which I usually hard-code in variables in a configuration file included in all scripts, so:

define (FULL_DIRECTORY_PATH,'/whatever/your/path/is/');

...

exec('rm ' . FULL_DIRECTORY_PATH . 'US_A.2.6.*');

Or

define (BASE_PATH,'/base/path/');

...

exec('rm ' . BASE_PATH . 'additional/path/US_A.2.6.*');

This solution would work on linux and other UNIX systems. Although it's uncommon to use PHP on Windows, you could adapt it to work on Windows servers.

There are some critical security risks associated with using exec() if there is any user-submitted input; with the code as-is, it will be fine as the paths and filenames are all hardcoded. But if you include any custom input, make sure to use the escapeshellarg function.

As George Cummins notes, this solution doesn't include error handling. I find his solution is better if you need error handling on a file-by-file basis. However, I commonly use setups like the one here, with no error handling, for cleanup of automatically generated files, and I have never run into any problems in 10+ years of using such constructs. For such uses, error handling is often only needed during setup and testing, and it usually comes down to setting directory permissions correctly.



来源:https://stackoverflow.com/questions/6471989/using-a-wildcard-in-php-unlink

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!