How to remove files that start with a certain prefix from php - php

I need to delete files that start with a prefix in a certain folder in my Symfony project. I have used the following code to delete for example the files start with p_ (p_example.jpeg), but do not delete them:
Php:
public function exampleAction(){
$Dir = $this->container->getParameter('kernel.root_dir').'/../web/uploads/news/';
$files=glob("'".$Dir."p_*.*'",GLOB_MARK);
foreach($files as $file){
if(is_file($file)){
unlink($file);
}
}
}
I appreciate your help.

Finally, I have resolved it with the following code:
Php:
public function exampleAction(){
$Dir = $this->container->getParameter('kernel.root_dir').'/../web/uploads/news/';
$mask = $Dir."p_*.*";
array_map( "unlink", glob( $mask ) );
}

Related

Downloading a Zip file from a Laravel Nova action

I have some files that I store at /storage/app/public/clientA/files/*.pdf. I have models that I can use to access these, and I want users to be able to download multiple files by selecting them in Nova and then using an action. Here is my code for the action:
public function handle(ActionFields $fields, Collection $models)
{
$files = array();
foreach ($models as $file) {
$path = FileHelper::getPathFromUrl($file->url);
array_push($files, $path);
}
$zip_file = 'myfiles.zip';
$zip = new \ZipArchive();
if ($zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true)
{
foreach ($files as $item) {
$zip->addFile(public_path('storage/' . $item), $item);
}
$zip->close();
}
return Action::download($zip_file, $zip_file);
}
Also, here is my code for the getPathFromUrl method:
public static function getPathFromUrl ($url)
{
$path = '';
$url_path = parse_url($url, PHP_URL_PATH);
return substr($url_path, strpos($url_path, "/") + 1);
} // returns the format storage/clientA/files/fileName.pdf
My issue at the moment is that its generating an empty zip file. I'm guessing that my paths are wrong when I try and reference the files, but I don't know how to fix it. I've also tried accessing these locations using Storage::get and found that it can't see the files at valid locations (and yes, I have done Storage:link).
Can anyone give me some insight into what I need to change to my addFile to ensure that these pdfs get added to the zip file?

Function to get files of same name from parent folder

I've created custom elements for WPBakery. In the functions.php file, I currently have the following:
add_action( 'vc_before_init', 'vc_before_init_actions' );
function vc_before_init_actions() {
require_once('vc_elements/text-image/init.php' );
require_once('vc_elements/text/init.php' );
}
However, as I build more custom elements, that list will be huge. What I'm looking to do is load all files named init.php in each vc_elements subfolder.
This is my current folder structure:
vc_elements
text-image
init.php
text
init.php
What's the cleanest way to go about this?
You need to use RecursiveDirectoryIterator to scan the folder and get all files which are named as init.php. Below is the code you can use
add_action( 'vc_before_init', 'vc_before_init_actions' );
function vc_before_init_actions() {
$dir = '/full_path_to_vc_elements';
$files = getFiles($dir, 'init.php');
foreach( $files as $file) {
require_once( $file );
}
}
function getFiles($dir, $match) {
$return = array();
$iti = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach($iti as $file){
if ($file->isDir()) {
continue;
}
if(strpos($file , $match) !== false){
$return[] = $file->getPathname();
}
}
return $return;
}
So in future if you add any init.php file inside the folder, it will automatically be picked by getFiles() and included using require.
What I'm looking to do is load all files named init.php in each
vc_elements subfolder.
Assuming you mean only immediate sub-directorys of "vc_elements" you can use GlobIterator with an "*" as a subdirectory wildcard:
$myInitFiles = new GlobIterator('/path/to/vc_elements/*/init.php');
foreach ($myInitFiles as $file) {
require_once( $myInitFiles->key() );
}
unset($myInitFiles); // release object memory for garbage collection
You can obviously convert this to a more general function if required.
Perhaps something like this would work, assuming that directory only contains sub-directories with the elements you need.
$dir = 'path/to/vc_elements';
// Scan directory for its contents and put in array. Remove possiblity of . or ..
$files = array_diff(scandir($dir), array('..', '.'));
foreach ($files as $file) {
$name = '/path/to/vc_elements/' . $file . '/init.php';
include $name;
}
Not sure what the file structor is for your theme but if you have a folder like inc or int make a file called vc-functions.php in that file do something like this.
add_action( 'vc_before_init', 'vc_before_init_actions' );
function vc_before_init_actions() {
require_once('vc_elements/text-image/init.php' );
require_once('vc_elements/text/init.php' );
}
Then in the functions.php
require get_template_directory() . '/inc/vc-functions.php';

Delete folder and files in PHP

I have a question about the little code snippet below.
At the moment I use the first code snippet and it runs perfectly.
But wouldn't the second code be a better way to delete the folder and files in it?
My variable $target is everytime a path to the folder hwo needs to delete.
function deleteFilesAndDirectory($target)
{
if(is_dir($target))
{
$files = glob($target . '*', GLOB_MARK);
foreach($files as $file)
{
deleteFilesAndDirectory($file);
}
rmdir($target);
}
elseif(is_file($target))
{
unlink($target);
}
}
Why this code shouldn't be used?
function deleteFilesAndDirectory($target)
{
$files = glob($target . '*', GLOB_MARK);
foreach($files as $file)
{
unlink($file);
}
rmdir($target);
}
The second will work fine, so long as the directory to be deleted does not contain any subdirectories. To clean out subdirectories, a recursive function is the best way, which is why in the first code sample the function deleteFilesAndDirectory() calls itself.

Deleting files matching a specific file extension recursivly?

I would like to delete all files matching a particular extension in a specified directory and all subtree. I suppose I should be using using unlink but some help would be highly appreciated... Thank you!
you need a combination of this
Recursive File Search (PHP)
And the unlink / delete
You should be able to edit the example instead of echoing the file, to delete it
To delete specific extension files from sub directories, you can use the following function. Example:
<?php
function delete_recursively_($path,$match){
static $deleted = 0,
$dsize = 0;
$dirs = glob($path."*");
$files = glob($path.$match);
foreach($files as $file){
if(is_file($file)){
$deleted_size += filesize($file);
unlink($file);
$deleted++;
}
}
foreach($dirs as $dir){
if(is_dir($dir)){
$dir = basename($dir) . "/";
delete_recursively_($path.$dir,$match);
}
}
return "$deleted files deleted with a total size of $deleted_size bytes";
}
?>
e.g. To remove all text files you can use it as follows:
<?php echo delete_recursively_('/home/username/directory/', '.txt'); ?>

php glob - scan in subfolders for a file

I have a server with a lot of files inside various folders, sub-folders, and sub-sub-folders.
I'm trying to make a search.php page that would be used to search the whole server for a specific file. If the file is found, then return the location path to display a download link.
Here's what i have so far:
$root = $_SERVER['DOCUMENT_ROOT'];
$search = "test.zip";
$found_files = glob("$root/*/test.zip");
$downloadlink = str_replace("$root/", "", $found_files[0]);
if (!empty($downloadlink)) {
echo "$search";
}
The script is working perfectly if the file is inside the root of my domain name... Now i'm trying to find a way to make it also scan sub-folders and sub-sub-folders but i'm stuck here.
There are 2 ways.
Use glob to do recursive search:
<?php
// Does not support flag GLOB_BRACE
function rglob($pattern, $flags = 0) {
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$files = array_merge(
[],
...[$files, rglob($dir . "/" . basename($pattern), $flags)]
);
}
return $files;
}
// usage: to find the test.zip file recursively
$result = rglob($_SERVER['DOCUMENT_ROOT'] . '/test.zip');
var_dump($result);
// to find the all files that names ends with test.zip
$result = rglob($_SERVER['DOCUMENT_ROOT'] . '/*test.zip');
?>
Use RecursiveDirectoryIterator
<?php
// $regPattern should be using regular expression
function rsearch($folder, $regPattern) {
$dir = new RecursiveDirectoryIterator($folder);
$ite = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($ite, $regPattern, RegexIterator::GET_MATCH);
$fileList = array();
foreach($files as $file) {
$fileList = array_merge($fileList, $file);
}
return $fileList;
}
// usage: to find the test.zip file recursively
$result = rsearch($_SERVER['DOCUMENT_ROOT'], '/.*\/test\.zip/'));
var_dump($result);
?>
RecursiveDirectoryIterator comes with PHP5 while glob is from PHP4. Both can do the job, it's up to you.
I want to provide another simple alternative for cases where you can predict a max depth. You can use a pattern with braces listing all possible subfolder depths.
This example allows 0-3 arbitrary subfolders:
glob("$root/{,*/,*/*/,*/*/*/}test_*.zip", GLOB_BRACE);
Of course the braced pattern could be procedurally generated.
This returns fullpath to the file
function rsearch($folder, $pattern) {
$iti = new RecursiveDirectoryIterator($folder);
foreach(new RecursiveIteratorIterator($iti) as $file){
if(strpos($file , $pattern) !== false){
return $file;
}
}
return false;
}
call the function:
$filepath = rsearch('/home/directory/thisdir/', "/findthisfile.jpg");
And this is returns like:
/home/directory/thisdir/subdir/findthisfile.jpg
You can improve this function to find several files like all jpeg file:
function rsearch($folder, $pattern_array) {
$return = array();
$iti = new RecursiveDirectoryIterator($folder);
foreach(new RecursiveIteratorIterator($iti) as $file){
if (in_array(strtolower(array_pop(explode('.', $file))), $pattern_array)){
$return[] = $file;
}
}
return $return;
}
This can call as:
$filepaths = rsearch('/home/directory/thisdir/', array('jpeg', 'jpg') );
Ref: https://stackoverflow.com/a/1860417/219112
As a full solution for your problem (this was also my problem):
<?php
function rsearch($folder, $pattern) {
$dir = new RecursiveDirectoryIterator($folder);
$ite = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($ite, $pattern, RegexIterator::MATCH);
foreach($files as $file) {
yield $file->getPathName();
}
}
Will get you the full path of the items that you wish to find.
Edit: Thanks to Rousseau Alexandre for pointing out , $pattern must be regular expression.

Categories