if folder exists with PHP - php

I'd love some help....i'm not sure where to start in creating a script that searches for a folder in a directory and if it doesnt exist then it will simply move up one level (not keep going up till it finds one)
I am using this code to get a list of images. But if this folder didn't exist i would want it to move up to its parent.
$iterator = new DirectoryIterator("/home/domain.co.uk/public_html/assets/images/bg-images/{last_segment}"); foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile() && !preg_match('/-c\.jpg$/', $fileinfo->getFilename())) {
$bgimagearray[] = "'" . $fileinfo->getFilename() . "'";
} }

Put your directory name in a variable.
$directory = "/home/domain.co.uk/public_html/assets/images/bg-images/{last_segment}";
// if directory does not exist, set it to directory above.
if(!is_dir($directory)){
$directory = dirname($directory)
}
$iterator = new DirectoryIterator($directory);

It works: file_exists($pathToDir)

To test if a directory exists, use is_dir()
http://php.net/function.is-dir
To move up to the parent directory would be by chdir('..');
http://php.net/function.chdir

Related

I would like To Delete All Directories That are Older Than 5 Minutes?

So here comes the tricky part. There are specifically two Sub directories (the sub-directories also some contain file) in every Directory named lib and vendor. So when I used to have specific Dir name I used to use this
<?php
$dir = $_GET['fname'];
array_map('unlink', glob("$dir/lib/*.*"));
rmdir("$dir/lib");
array_map('unlink', glob("$dir/vendor/*.*"));
rmdir("$dir/vendor");
array_map('unlink', glob("$dir/*.*"));
rmdir($dir);`
So I used to have a specific directory name. but now i want to change this.
So whenever a user is redirected to my script
It should delete all the directories that are older that 5 min. Only
directories.
All the directories contain only and only 2 sub-directories named
lib and vendor.They Should be deleted too.
These Three Directories Shouldn't be deleted project , images and
assets.Except these all the directories should be deleted. Now
Please someone Help me out.
You can do this. First create a function to delete a directory
function deldirectory($dir){
$tfile = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($tfile,
RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
if ($file->isDir()){
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
return rmdir($dir);
}
Call that function in foreach loop to check and delete the folder that are more then 5 minutes
foreach ($folders as $f){
$lastmodified = filemtime($f);
$farray = array("project","images","assets");//These folders are ignored
$file_life = 300;
if((time() - $lastmodified >= $file_life) && !in_array($f, $farray)){
deldirectory($f);
}
}

Loop through series of folders and check how old the folder

I am making a Cron that will delete a folder older than 15days. I already made a function to delete the folder and it's content, what I don't have is to loop inside a folder then check each folder's age then if that is 15days old or above I will executue my delete function.
I want to loop inside public/uploads
in my uploads directory I store folders with content ex.
public/
uploads/
Test/
Test2/
I want to check how old those folder then delete it by calling
function Delete($path)
{
if (is_dir($path) === true)
{
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file)
{
Delete(realpath($path) . '/' . $file);
}
return rmdir($path);
}
else if (is_file($path) === true)
{
return unlink($path);
}
return false;
}
How do I do that? Thanks
The function you are looking for is filemtime(). This lets you determine the last modified date of a file (or directory). That in combination with the various directory functions will allow you to loop through them and check their dates.
This is something mocked up off the top of my head to give you a rough idea of how you may go about this:
$dir = '/path/to/my/folders';
$folders = scandir($dir);
foreach ($folders as $folder) {
$lastModified = filemtime($folder);
// Do a date comparison here and call your delete if necessary
}

PHP - Deleting folder/files only if there are no more in there

$value can = a folder structure to the language file. Example: languages/english.php
$value can also = the files name. Example: english.php
So I need to get the current folder that $value is in and delete the folder ONLY if there are no other files/folders within that directory (after deleting the actual file as I am doing already, ofcourse).
foreach($module['languages'] as $lang => $langFile)
{
foreach ($langFile as $type => $value)
{
#unlink($module_path . '/' . $value);
// Now I need to delete the folder ONLY if there are no other directories inside the folder where it is currently at.
// And ONLY if there are NO OTHER files within that folder also.
}
}
How can I do this?? And wondering if this can be done without using a while loop, since a while loop within a foreach loop could take some time, and need this to be as quick as possible.
And just FYI, the $module_path should never be deleted. So if $value = english.php, it should never delete the $module_path. Ofcourse, there will always be another file in there, so checking for this is not necessary, but won't hurt either way.
Thanks guys :)
EDIT
Ok, now I'm using this code here and it is NOT working, it is not removing the folders or the files, and I don't get any errors either... so not sure what the problem is here:
foreach($module['languages'] as $lang => $langFile)
{
foreach ($langFile as $type => $value)
{
if (#unlink($module_path . '/' . $value))
#rmdir(dirname($module_path . '/' . $value));
}
}
NEVERMIND, this works a CHARM!!! Cheers Everyone!!
The easyest way is try to use rmdir. This don't delete folder if it is not empty
rmdir($module_path);
also you can check is folder empty by
if(count(glob($module_path.'*'))<3)//delete
2 for . and ..
UPD: as I reviewed maybe you should replace $module_path by dirname($module_path.'.'.$value);
Since the directory you care about might be part of the $value, you need to use dirname to figure out what the parent directory is, you can't just assume that it's $module_path.
$file_path = $module_path . '/' . $value;
if (#unlink($file_path)) {
#rmdir(dirname($file_path));
}
if (is_file($value)) {
unlink($value);
} else if (is_dir($value)) {
if (count(scandir($value)) == 2) }
unlink($value)
}
}
http://php.net/manual/en/function.is-dir.php
http://www.php.net/manual/en/function.scandir.php
The code below will take a path, check if it is a file (i.e. not a directory). If it is a file, it will extract the directory name, then delete the file, then iterate over the dir and count the files in it, if the files are zero it'll delete the dir.
Code is as an example and should work, however privileges and environment setup may result in it not working.
<?php
if(!is_dir ( string $filename )){ //if it is a file
$fileDir = dirname ( $filename );
if ($handle = opendir($fileDir)) {
echo "Directory handle: $handle\n";
echo "Files:\n";
$numFiles=0;
//delete the file
unlink($myFile);
//Loop the dir and count the file in it
while (false !== ($file = readdir($handle))) {
$numFiles = $numFiles + 1;
}
if($numFiles == 0) {
//delete the dir
rmdir($fileDir);
}
closedir($handle);
}
}
?>

PHP incomplete code - scan dir, include only if name starts or end with x

I posted a question before but I am yet limited to mix the code without getting errors.. I'm rather new to php :(
( the dirs are named in series like this "id_1_1" , "id_1_2", "id_1_3" and "id_2_1" , "id_2_2", "id_2_3" etc.)
I have this code, that will scan a directory for all the files and then include a same known named file for each of the existing folders.. the problem is I want to modify a bit the code to only include certain directories which their names:
ends with "_1"
starts with "id_1_"
I want to create a page that will load only the dirs that ends with "_1" and another file that will load only dirs that starts with "id_1_"..
<?php
include_once "$root/content/common/header.php";
include_once "$root/content/common/header_bc.php";
include_once "$root/content/" . $page_file . "/content.php";
$page_path = ("$root/content/" . $page_file);
$includes = array();
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($page_path),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $file) {
if($file->isDir()) {
$includes[] = strtoupper($file . '/template.php');
}
}
$includes = array_reverse($includes);
foreach($includes as $file){
include $file;
}
include_once "$root/content/common/footer.php";
?>
Many Thanks!
foreach($iterator as $file) {
if($file->isDir()) {
// getFilename() actually gives the directory name, when it's um, a directory.
$dirName = $file->->getFilename();
if (substr($dirName, 0, 5) === 'id_1_') {
$includes[] = strtoupper($file . '/template.php');
}
}
}
There's other ways to do this, but I tried to only add simple functions and logic, in hopes you will understand it.
Ends with would look like
if (substr($dirName, -2) === '_1')

Check directory exists and if it doesnt choose an image

I have this code so far which perfectly but relies on there being a directory in place:
$path = '/home/sites/therealbeercompany.co.uk/public_html/public/themes/trbc/images/backgrounds/'.$this->slug;
$bgimagearray = array();
$iterator = new DirectoryIterator($path);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile() && !preg_match('\.jpg$/', $fileinfo->getFilename())) {
$bgimagearray[] = "'" . $fileinfo->getFilename() . "'";
}
}
I need to work in a bit at the top so that if the directory doesnt exist it defaults to the images sat in the root of the background directory...
Any help would be appreciated.
You want is_dir. Test your slug directory, and if it doesn't exist, use the root background directory instead.
Use is_dir to see if the dir is there, and if not, set $path to the current path (where the script is running from)
if (!is_dir($path)) {
$path = $_SERVER["PATH_TRANSLATED"];
}
I very much dangerously assumed that $path is not going to be used anywhere else :)
(is_dir is better, thanks!)
DirectoryIterator will throw an UnexpectedValueException when the path cannot be opened, so you can wrap the call into a try/catch block and then fallback to the root path. In a function:
function getBackgroundImages($path, $rootPath = NULL)
{
$bgImages = array();
try {
$iterator = new DirectoryIterator($path);
// foreach code
} catch(UnexpectedValueException $e) {
if($rootPath === NULL) {
throw $e;
}
$bgImages = getBackgroundImages($rootPath);
}
return $bgImages;
}
But of course file_exists or is_dir are a valid options too.
You could also use the file_exists function to check for the directory.

Categories