How to make directory within directory by php loop?
Example: http://site_name/a/b/c/d
First create a then b within a then c within b then ....
Problem is here a,b,c,d all the folders created in root directory not one within one.
Here is my code -
<?php
$url = "http://site_name/a/b/c/d";
$details1 = parse_url(dirname($url));
$base_url = $details1['scheme'] . "//" . $details1['host'] . "/";
if ($details1['host'] == 'localhost') {
$path_init = 2;
}else {
$path_init = 1;
}
$paths = explode("/", $details1['path']);
for ($i = $path_init; $i < count($paths); $i++) {
$new_dir = '';
$base_url = $base_url . $paths[$i] . "/";
$new_dir = $base_url;
if (FALSE === ($new_dir = folder_exist($paths[$i]))) {
umask(0777);
mkdir($new_dir . $paths[$i], 0777, TRUE);
}
}
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
return ($path !== false AND is_dir($path)) ? $path : false;
}
?>
please check this code. it will create nested folder if not exit
<?php
$your_path = "Bashar/abc/def/ghi/dfsdfds/get_dir.php";
$array_folder = explode('/', $your_path);
$mkyourfolder = "";
foreach ($array_folder as $folder) {
$mkyourfolder = $mkyourfolder . $folder . "/";
if (!is_dir($mkyourfolder)) {
mkdir($mkyourfolder, 0777);
}
}
hope it will help you
You can actually create nested folders with the mkdir PHP function
mkdir($path, 0777, true); // the true value here = recursively
Dear friends the following answer is tested and used in my script -
<?php
$url = "http://localhost/Bashar/abc/def/ghi/dfsdfds/get_dir.php";
$details = parse_url(dirname($url));
//$base_url = $details['scheme'] . "//" . $details['host'] . "/";
$paths = explode("/", $details['path']);
$full_dir = '';
$init = ($details['host'] == 'localhost') ? '2' : '1';
for ($i = $init; $i < count($paths); $i++) {
$full_dir = $full_dir . $paths[$i] . "/";
if (!is_dir($full_dir)) {
mkdir($full_dir, 0777);
}
}
?>
Related
i'm working on a Joomla 3.x component, I'm trying to build an array with folders, files and filenames, I can get the Folders and Files , including paths, which I want, but have been unable to get it to return the names using "basename()" to get just the name.ext . I get an error regarding passing an array to "basename()" in lieu of a string, I've tried "foreach" but it only returns the last item in the array.
Below is the code
function getPathContents() {
$this->directory = 'some/directory';
$recursive = '1';
$this->recursive = ($recursive == 'true' || $recursive == 'recursive' || $recursive == '1');
$this->exclude_folders = '';
$this->exclude_files = '';
$options = array();
$filenames = array();
$filename = basename($filenames);
$path = $this->directory;
if (!is_dir($path))
{
if (is_dir(JPATH_ROOT . '/' . $path))
{
$path = JPATH_ROOT . '/' . $path;
}
else
{
return;
}
}
$path = JPath::clean($path);
$folders = JFolder::folders($path, $this->filter, $this->recursive, true);
// Build the options list from the list of folders.
if (is_array($folders))
{
foreach ($folders as $folder)
{
$options['folders'] = $folders;
$files = JFolder::files($folder, $this->filter, $this->recursive, true);
if (is_array($files))
{
foreach ($files as $file)
{
$options['files'] = $files;
}
$filenames = JFolder::files($folder, $this->filter, $this->recursive, true);
if (is_array($filenames))
{
foreach ($files as $filename)
{
$options['filenames'] = $filename;
}
}
}
}
return $options;
}
any help would be great
UPDATE: Below Code will provide list of Folders and additional arrays of files located in each folder. Each file array is labeled with the Folders name.
Code
function getFolersfiles() {
$this->directory = 'yourpath';
$recursive = '1';
$this->recursive = ($recursive == 'true' || $recursive == 'recursive' || $recursive == '1');
$this->exclude_folders = '';
$this->exclude_files = '';
$path = $this->directory;
if (!is_dir($path))
{
if (is_dir(JPATH_ROOT . '/' . $path))
{
$path = JPATH_ROOT . '/' . $path;
}
else
{
return;
}
}
$path = JPath::clean($path);
$options2['folders'] = JFolder::folders($path, $this->filter, $this->recursive, true);
// Build the options list from the list of folders.
if (is_array($options2))
{
foreach ($options2['folders'] as $option2)
{
$optionname = basename($option2);
$options2[$optionname] = JFolder::files($option2, $this->filter, $this->recursive, true);
//$options2['filepath'] = JFolder::files($option2, $this->filter, $this->recursive, true);
}
return $options2;
}
Thank you for the help
Here is a code to search and return the existing files from the given directories:
<?php
function getDirContents($directories, &$results = array()) {
$length = count($directories);
for ($i = 0; $i < $length; $i++) {
if(is_file($directories[$i])) {
if(file_exists($directories[$i])) {
$path = $directories[$i];
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
} else {
$files = array_diff(scandir($directories[$i]), array('..', '.'));
foreach($files as $key => $value) {
$path = $directories[$i].DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents([$path], $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
}
}
}
return $results;
}
echo json_encode(getDirContents($_POST['directories']));
So you can pass an array of file addresses and directories and get what ever files inside those directories, Note if you pass a file address instead of a directory address the function checks if there is such a file and if there is it returns its address in the result .
The issue is for the directories it works fine but the files repeat twice in the result and for each file the function double checks this if statement in the code:
if(is_file($directories[$i]))
Here is a result of the function note that contemporary.mp3 and Japanese.mp3
has been re checked and added to the result.
How can I solve this?
If $directories contains both a directory and a file within that directory, you'll add the file to the result for the filename and also when scanning the directory.
A simple fix is to check whether the filename is already in the result before adding it.
<?php
function getDirContents($directories, &$results = array()) {
foreach ($directories as $name) {
if(is_file($name)) {
$path = $name;
$directory_path = basename($_SERVER['REQUEST_URI']);
$new_path = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
if (!in_array($new_path, $results)) {
$results[] = $new_path;
}
} elseif (is_dir($name)) {
$files = array_diff(scandir($name), array('..', '.'));
foreach($files as $key => $value) {
$path = $name.DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents([$path], $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$new_path = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
if (!in_array($new_path, $results)) {
$results[] = $new_path;
}
}
}
}
}
return $results;
}
i would like to create a PHP script that delete files from multiple folders/paths.
I managed something but I would like to adapt this code for more specific folders.
This is the code:
<?php
function deleteOlderFiles($path,$days) {
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
$filelastmodified = filemtime($path . $file);
if((time() - $filelastmodified) > $days*24*3600)
{
if(is_file($path . $file)) {
unlink($path . $file);
}
}
}
closedir($handle);
}
}
$path = 'C:/Users/Legion/AppData/Local/Temp';
$days = 7;
deleteOlderFiles($path,$days);
?>
I would like to make something like to add more paths and this function to run for every path.
I tried to add multiple path locations but it didn't work because it always takes the last $ path variable.
For exemple:
$path = 'C:/Users/Legion/AppData/Local/Temp';
$path = 'C:/Users/Legion/AppData/Local/Temp/bla';
$path = 'C:/Users/Legion/AppData/Local/Temp/blabla';
$path = 'C:/Users/Legion/AppData/Local/Temp/blalbalba';
$days = 7;
deleteOlderFiles($path,$days);
Thank you for you help!
The simple solution, call the function after setting the parameter not after setting all the possible parameters into a scalar variable.
$days = 7;
$path = 'C:/Users/Legion/AppData/Local/Temp';
deleteOlderFiles($path,$days);
$path = 'C:/Users/Legion/AppData/Local/Temp/bla';
deleteOlderFiles($path,$days);
$path = 'C:/Users/Legion/AppData/Local/Temp/blabla';
deleteOlderFiles($path,$days);
$path = 'C:/Users/Legion/AppData/Local/Temp/blalbalba';
deleteOlderFiles($path,$days);
Alternatively, place the directories in an array and then call the funtion from within a foreach loop.
$paths = [];
$paths[] = 'C:/Users/Legion/AppData/Local/Temp';
$paths[] = 'C:/Users/Legion/AppData/Local/Temp/bla';
$paths[] = 'C:/Users/Legion/AppData/Local/Temp/blabla';
$paths[] = 'C:/Users/Legion/AppData/Local/Temp/blalbalba';
$days = 7;
foreach ( $paths as $path){
deleteOlderFiles($path,$days);
}
It seems that you need a recursive function, i.e. a function that calls itself. In this case it calls itself when it finds a subdirectory to scan/traverse.
function delete_files($current_path, $days) {
$files_in_current_path = scandir($current_path);
foreach($files_in_current_path as $file) {
if (!in_array($release_file, [".", ".."])) {
if (is_dir($current_path . "/" . $file)) {
// Scan found subdirectory
delete_files($current_path . "/" . $file, $days);
} else {
// Here you add your code for checking date and deletion of the $file
$filelastmodified = filemtime($current_path . "/" . $file);
if((time() - $filelastmodified) > $days*24*3600) {
if(is_file($current_path . "/" . $file)) {
unlink($current_path . "/". $file);
}
}
}
}
}
}
delete_files("your/startpath/here", 7);
This code starts in your specified start path. It scans all files in that directory. If a sub directory is found, there will be a new call to delete_files, but with that sub directory as a start.
I am using the following script for listing the files in a particular directory as a hyperlink list.
$dir = '.';
$dh = opendir($dir);
$file_count = 0;
while (false !== ($file = readdir($dh))) {
$files[] = $file;
$file_count += 1;
echo $file;
}
for ($x = 0; $x < $file_count; $x += 1) {
echo "<li><a href='$files[$x]'>$files[$x]</a></li>";
}
Please tell us whether the following is possible
1. The file extension should not be displayed
2. I need " " instead of "-" in the file names
If possible how to incorporate it.
Update 2:
Thanks for your kindly help. I followed,
The files names which i have mentioned must not be displayed (like dont display index.php), How do i change the code for this?
<?php
$directory = '';
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
$name = preg_replace("/-/", " ", $parts['filename']);
echo "<li>{$name}</li>";
}
?>
Try the following using glob in a loop.
$directory = 'folder/';
foreach (glob($directory . "*.*") as $file) {
$parts = pathinfo($file);
$name = preg_replace("/-/", "", $parts['filename']);
echo "{$name}";
}
Example with your provided code, two lines added pathinfo and a preg_replace.
$dir = '.';
$dh = opendir($dir);
$file_count = 0;
while (false !== ($file = readdir($dh))) {
$files[] = $file;
$file_count += 1;
echo $file;
}
for ($x = 0; $x < $file_count; $x += 1) {
$parts = pathinfo($files[$x]);
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li><a href='$files[$x]'>$name</a></li>";
}
Updated:
The following doesn't show the files called index.php, wtf.php, and hide.php
$directory = 'folder/';
$blacklist = array(
'index',
'wtf',
'hide'
);
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
if (!in_array($parts['filename'], $blacklist)) {
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li>{$name}</li>";
}
}
Hi
i am trying to build simple directory browser to browse folders and sub-folders uing php RecursiveDirectoryIterator .. i need help of how to create this. i have started with the following code.
$dir = dirname(__FILE__); //path of the directory to read
$iterator = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
if (!$file->isFile()) { //create hyperlink if this is a folder
echo "" . $file->getFilename() . "\";
}else{ //do not link if this is a file
$file->getFilename()
}
}
Allow me to code that for you....
<?php
$root = __DIR__;
function is_in_dir($file, $directory, $recursive = true, $limit = 1000) {
$directory = realpath($directory);
$parent = realpath($file);
$i = 0;
while ($parent) {
if ($directory == $parent) return true;
if ($parent == dirname($parent) || !$recursive) break;
$parent = dirname($parent);
}
return false;
}
$path = null;
if (isset($_GET['file'])) {
$path = $_GET['file'];
if (!is_in_dir($_GET['file'], $root)) {
$path = null;
} else {
$path = '/'.$path;
}
}
if (is_file($root.$path)) {
readfile($root.$path);
return;
}
if ($path) echo '..<br />';
foreach (glob($root.$path.'/*') as $file) {
$file = realpath($file);
$link = substr($file, strlen($root) + 1);
echo ''.basename($file).'<br />';
}