I'm trying to include all files from a folder from another folder in php. Here is my current directory structure:
> folder1
main.php
> folder2
> folder3
someFile.php
someFile2.php
someFile3.json
I tried doing:
include "../folder2/";
and this(only includes php files):
foreach (glob("classes/*.php") as $filename)
{
include $filename;
}
From main.php, I want to include all of folder2/ including the sub folder: folder3 as well as the php and json files inside folder2/. I have looked at other stack overflow questions and know about the for loop method but haven't figured out a way to include different file types(.php, .json, etc...) and sub directories. Any help is appreciated. Thanks!
PHP's include shouldn't be used for other file types, like .json. To extract data from those files you'll want to read them using something like file_get_contents. For example:
$data = json_decode(file_get_contents('someFile3.json'));
To recursively include the PHP files in other directories you can try recursively searching through all directories:
function require_all($dir, $max_scan_depth, $depth=0) {
if ($depth > $max_scan_depth) {
return;
}
// require all php files
$scan = glob("$dir/*");
foreach ($scan as $path) {
if (preg_match('/\.php$/', $path)) {
require_once $path;
}
elseif (is_dir($path)) {
require_all($path, $max_scan_depth, $depth+1);
}
}
}
$max_depth = 255;
require_all('folder3', $max_depth);
This code is a modified version of the code found here: https://gist.github.com/pwenzel/3438784
Related
I am trying to get the names/path of the files that are included in a files with a given path . But the get_included_files() function works only for the files in which it is written.
<?
include_once('/folder1/folder2/xyz.php');
$path = '/abcd.php';
$includeFiles = get_included_files();
?>
I have tried the above code and i am getting only the included files in this file only.
I want to get the name of the included files in abcd.php i.e for the defined path.
Please HELP !!
How about something like this?
array_filter(get_included_files(), function($item) {
return strpos($item, '/path/to/files/') === 0;
});
I have been working on a project that involves a step, during which the script needs to automatically remove a certain directory in Linux ( and all its contents ).
I am currently using the following code to do that:
# Perform a recursive removal of the obsolete folder
$dir_to_erase = $_SESSION['path'];
function removeDirectory($dir_to_erase) {
$files = glob($dir_to_erase . '/*');
foreach ($files as $file) {
is_dir($file) ? removeDirectory($file) : unlink($file);
}
rmdir($dir_to_erase);
return;
}
Where $_SESSION['path'] is the folder to erase. Been working like a charm, but I recently had to add a .htaccess file to the folder, and I noticed the script stopped working correctly ( it keeps removing the rest of the files fine, but not the .htaccess files ).
Can anyone point me as to what I should add to the code include the hidden dot files in the removal process?
simply, you can rely on DirectoryIterator
The DirectoryIterator class provides a simple interface for viewing
the contents of filesystem directories.
function removeDirectory($dir_to_erase) {
$files = new DirectoryIterator($dir_to_erase);
foreach ($files as $file) {
// check if not . or ..
if (!$file->isDot()) {
$file->isDir() ? removeDirectory($file->getPathname()) : unlink($file->getPathname());
}
}
rmdir($dir_to_erase);
return;
}
there are lot of features there you may make use of them, as check the owner which is pretty useful to make sure not to remove critical file.
You can slightly modify your function to remove hidden files also:
function removeDirectory($dir)
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir."/".$object))
removeDirectory($dir."/".$object);
else
unlink($dir."/".$object);
}
}
rmdir($dir);
}
}
As per this answer:
PHP glob() doesnt find .htaccess
glob(".*") will find .htaccess
Suppose there's a directory in which there are numerous sub-directories. Now how can I scan all the subdirectories to find a file with name, say, abc.php and delete this file wherever its is found.
I tried doing something like this -
$oAllSubDirectories = scandir(getcwd());
foreach ($oAllSubDirectories as $oSubDirectory)
{
//Delete code here
}
But this code doesn't check directories inside the subdirectories. Any idea how can I do this ?
In general, you put the code inside a function and make it recursive: when it encounters a directory it calls itself in order to process its contents. Something like this:
function processDirectoryTree($path) {
foreach (scandir($path) as $file) {
$thisPath = $path.DIRECTORY_SEPARATOR.$file;
if (is_dir($thisPath) && trim($thisPath, '.') !== '') {
// it's a directory, call ourself recursively
processDirectoryTree($thisPath);
}
else {
// it's a file, do whatever you want with it
}
}
}
In this particular case you don't need to do that because PHP offers the ready-made RecursiveDirectoryIterator that does this automatically:
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(getcdw()));
while($it->valid()) {
if ($it->getFilename() == 'abc.php') {
unlink($it->getPathname());
}
$it->next();
}
Im trying to Delete ALL Text files from a directory using a php script.
Here is what I have tried.....
<?php array_map('unlink', glob("/paste/*.txt")); ?>
I dont get an Error when I run this, yet It doesnt do the job.
Is there a snippet for this? Im not sure what else to try.
Your Implementation works all you need to do is use Use full PATH
Example
$fullPath = __DIR__ . "/test/" ;
array_map('unlink', glob( "$fullPath*.log"))
I expanded the submitted answers a little bit so that you can flexibly and recursively unlink text files located underneath as it's often the case.
// #param string Target directory
// #param string Target file extension
// #return boolean True on success, False on failure
function unlink_recursive($dir_name, $ext) {
// Exit if there's no such directory
if (!file_exists($dir_name)) {
return false;
}
// Open the target directory
$dir_handle = dir($dir_name);
// Take entries in the directory one at a time
while (false !== ($entry = $dir_handle->read())) {
if ($entry == '.' || $entry == '..') {
continue;
}
$abs_name = "$dir_name/$entry";
if (is_file($abs_name) && preg_match("/^.+\.$ext$/", $entry)) {
if (unlink($abs_name)) {
continue;
}
return false;
}
// Recurse on the children if the current entry happens to be a "directory"
if (is_dir($abs_name) || is_link($abs_name)) {
unlink_recursive($abs_name, $ext);
}
}
$dir_handle->close();
return true;
}
You could modify the method below but be careful. Make sure you have permissions to delete files. If all else fails, send an exec command and let linux do it
static function getFiles($directory) {
$looper = new RecursiveDirectoryIterator($directory);
foreach (new RecursiveIteratorIterator($looper) as $filename => $cur) {
$ext = trim($cur->getExtension());
if($ext=="txt"){
// remove file:
}
}
return $out;
}
i have modified submitted answers and made my own version,
in which i have made function which will iterate recursively in current directory and its all child level directories,
and it will unlink all the files with extension of .txt or whatever .[extension] you want to remove from all the directories, sub-directories and its all child level directories.
i have used :
glob() From the php doc:
The glob() function searches for all the pathnames matching pattern
according to the rules used by the libc glob() function, which is
similar to the rules used by common shells.
i have used GLOB_ONLYDIR flag because it will iterate through only directories, so it will be easier to get only directories and unlink the desired files from that directory.
<?php
//extension of files you want to remove.
$remove_ext = 'txt';
//remove desired extension files in current directory
array_map('unlink', glob("./*.$remove_ext"));
// below function will remove desired extensions files from all the directories recursively.
function removeRecursive($directory, $ext) {
array_map('unlink', glob("$directory/*.$ext"));
foreach (glob("$directory/*",GLOB_ONLYDIR) as $dir) {
removeRecursive($dir, $ext);
}
return true;
}
//traverse through all the directories in current directory
foreach (glob('./*',GLOB_ONLYDIR) as $dir) {
removeRecursive($dir, $remove_ext);
}
?>
For anyone who wonder how to delete (for example: All PDF files under public directory) you can do this:
array_map('unlink', glob( public_path('*.pdf')));
Trying to add the ability to delete a Folder using FTP and all subfolders and files contained within that folder.
I have built a recursive function to do so, and I feel like the logic is right, but still doesnt work.
I did some testing, I am able to delete on first run if the path is just an empty folder or just a file, but can't delete if it is a folder containing one file or a folder containing one empty subfolder. So it seems to be a problem with traversing through the folder(s) and using the function to delete.
Any ideas?
function ftpDelete($directory)
{
if(empty($directory))//Validate that a directory was sent, otherwise will delete ALL files/folders
return json_encode(false);
else{
global $conn_id;
# here we attempt to delete the file/directory
if( !(#ftp_rmdir($conn_id,$directory) || #ftp_delete($conn_id,$directory)) )
{
# if the attempt to delete fails, get the file listing
$filelist = #ftp_nlist($conn_id, $directory);
# loop through the file list and recursively delete the FILE in the list
foreach($filelist as $file)
ftpDelete($file);
#if the file list is empty, delete the DIRECTORY we passed
ftpDelete($directory);
}
else
return json_encode(true);
}
};
I took some time to write my own version of a recursive delete function over ftp, this one should be fully functional (I tested it myself).
Try it out and modify it to fit your needs, if it's still not working there are other problems. Have you checked the permissions on the files you are trying to delete?
function ftp_rdel ($handle, $path) {
if (#ftp_delete ($handle, $path) === false) {
if ($children = #ftp_nlist ($handle, $path)) {
foreach ($children as $p)
ftp_rdel ($handle, $p);
}
#ftp_rmdir ($handle, $path);
}
}
Ok found my problem. Since I wasn't moving into the exact directory I was trying to delete, the path for each recursive file being called wasn't absolute:
function ftpDeleteDirectory($directory)
{
global $conn_id;
if(empty($directory))//Validate that a directory was sent, otherwise will delete ALL files/folders
return json_encode(false);
else{
# here we attempt to delete the file/directory
if( !(#ftp_rmdir($conn_id,$directory) || #ftp_delete($conn_id,$directory)) )
{
# if the attempt to delete fails, get the file listing
$filelist = #ftp_nlist($conn_id, $directory);
# loop through the file list and recursively delete the FILE in the list
foreach($filelist as $file)
{
// return json_encode($filelist);
ftpDeleteDirectory($directory.'/'.$file);/***THIS IS WHERE I MUST RESEND ABSOLUTE PATH TO FILE***/
}
#if the file list is empty, delete the DIRECTORY we passed
ftpDeleteDirectory($directory);
}
}
return json_encode(true);
};
function recursiveDelete($handle, $directory)
{ echo $handle;
# here we attempt to delete the file/directory
if( !(#ftp_rmdir($handle, $directory) || #ftp_delete($handle, $directory)) )
{
# if the attempt to delete fails, get the file listing
$filelist = #ftp_nlist($handle, $directory);
// var_dump($filelist);exit;
# loop through the file list and recursively delete the FILE in the list
foreach($filelist as $file) {
recursiveDelete($handle, $file);
}
recursiveDelete($handle, $directory);
}
}
You have to check (using ftp_chdir) for every "file" you get from ftp_nlist to check if it is a directory:
foreach($filelist as $file)
{
$inDir = #ftp_chdir($conn_id, $file);
ftpDelete($file)
if ($inDir) #ftp_cdup($conn_id);
}
This easy trick will work, because if ftp_chdir works, the current $file is actually a folder, and you've moved into it. Then you call ftpDelete recursively, to let it delete the files in that folder. Afterwards, you move back (ftp_cdup) to continue.