PHP random folder - php

Let's say I have the following directory tree
tmp
---cat
---dog
---mouse
My index.php is in the same directory as tmp folder. How would I use PHP to save a random folder name as a variable? I've tried the following code but it didn't work.
<?php
function listFolderFiles(){
$dir = './tmp';
$ffs = scandir($dir);
$randomFolder = '';
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
$randomFolder = $randomFolder + $ff;
}
}
echo $randomFolder;
echo '</ol>';
}
listFolderFiles();
?>

Another solution can be the built in DirectoryIterator object for iterating through file systems. Just have a look at the following example.
$results = [];
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot() && $fileinfo->isDir()) {
$results[] = $fileinfo->getFilename();
}
}
The given code iterates through a given directory and gives back all directories included in the given directory except the dots.

By create, do you mean return/echo?
I don't think your function will produce a random folder. It will return the last folder.
function listFolderFiles(){
$dir = './tmp';
$Ignore = array('.','..'); // build an ignore array
$Results = array();
$ffs = scandir($dir);
foreach($ffs as $ff){
if(!in_array($ff,$Ignore) && is_dir("./tmp/".$ff)){ // if filename is folder and not in ignore array
$Results[] = $ff; // add filename to results
}
}
shuffle($Results); // shuffle/randomize the results
echo $Results[0];
}
listFolderFiles();

Related

Renaming all files within different sub directories

I m trying to rename files to lowercase within a directory, however the problem I'm having is being able to scan the sub-directories for the files.
So in this case $app_dir is the main directory and the files I need to change exist within multiple sub-folders.
Heres my code so far:
$files = scandir($app_dir);
foreach($files as $key=>$name){
$oldName = $name;
$newName = strtolower($name);
rename("$app_dir/$oldName","$app_dir/$newName");
}
Thanks for your help.
If you are trying to lowercase all file names you can try this:
Using this filesystem:
Josh#laptop:~$ find josh
josh
josh/A
josh/B
josh/f1
josh/f2
josh/is
josh/is/awesome
josh/is/awesome/e
josh/is/awesome/t
Code:
<?php
$app_dir = 'josh';
$dir = new RecursiveDirectoryIterator($app_dir, FilesystemIterator::SKIP_DOTS);
$iter = new RecursiveIteratorIterator($dir);
foreach ($iter as $file) {
if ($file != strtolower($file)) {
rename($file, strtolower($file));
}
}
Results:
Josh#laptop:~$ find josh
josh
josh/a
josh/b
josh/f1
josh/f2
josh/is
josh/is/awesome
josh/is/awesome/e
josh/is/awesome/t
This code does not take into account uppercase letters in directories but that exercise is up to you.
You could do this with a recursive function.
function renameFiles($dir){
$files = scandir($dir);
foreach($files as $key=>$name){
if($name == '..' || $name == '.') continue;
if(is_dir("$dir/$name"))
renameFiles("$dir/$name");
else{
$oldName = $name;
$newName = strtolower($name);
rename("$dir/$oldName", "$dir/$newName");
}
}
}
This basically loops through a directory, if something is a file it renames it, if something is a directory it runs itself on that directory.
Try like that
public function renameFiles($dir)
{
$files = scandir($dir);
foreach ($files as $key => $name) {
if (is_dir("$dir/$name")) {
if ($name == '.' || $name == '..') {
continue;
}
$this->renameFiles("$dir/$name");
} else {
$oldName = $name;
$newName = strtoupper($name);
rename("$dir/$oldName", "$dir/$newName");
}
}
}

Find all .php files in folder recursively

Using PHP, how can I find all .php files in a folder or its subfolders (of any depth)?
You can use RecursiveDirectoryIterator and RecursiveIteratorIterator:
$di = new RecursiveDirectoryIterator(__DIR__,RecursiveDirectoryIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($di);
foreach($it as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) == "php") {
echo $file, PHP_EOL;
}
}
just add something like:
function listFolderFiles($dir){
$ffs = scandir($dir);
$i = 0;
$list = array();
foreach ( $ffs as $ff ){
if ( $ff != '.' && $ff != '..' ){
if ( strlen($ff)>=5 ) {
if ( substr($ff, -4) == '.php' ) {
$list[] = $ff;
//echo dirname($ff) . $ff . "<br/>";
echo $dir.'/'.$ff.'<br/>';
}
}
if( is_dir($dir.'/'.$ff) )
listFolderFiles($dir.'/'.$ff);
}
}
return $list;
}
$files = array();
$files = listFolderFiles(dirname(__FILE__));
I modified the code a bit created by supajason
Because the code provided did not return a consistent result:
Mainly due to the nomenclature used.
I also added some functionality.
<?php
define('ROOT', str_replace('\\', '/', getcwd()).'/');
///########-------------------------------------------------------------
///########-------------------------------------------------------------
///######## FUNCTION TO LIST ALL FILES AND FOLDERS WITHIN A CERTAIN PATH
///########-------------------------------------------------------------
///########-------------------------------------------------------------
function list_folderfiles(
$dir, // *** TARGET DIRECTORY TO SCAN
$return_flat = true, // *** DEFAULT FLAT ARRAY TO BE RETURNED
$iteration = 0 // *** INTERNAL PARAM TO COUNT THE FUNCTIONS OWN ITERATIONS
){
///######## PREPARE ALL VARIABLES
$dir = rtrim($dir, '/'); // *** REMOVE TRAILING SLASH (* just for being pretty *)
$files_folders = scandir($dir); // *** SCAN FOR ALL FILES AND FOLDERS
$nested_folders = []; // *** THE NESTED FOLDERS BUILD ARRAY
static $total_files = []; // *** THE TOTAL FILES ARRAY
///######## MAKE SURE THAT THE STATIC $fileS ARE WILL BE CLEARED AFTER THE FIRST ITERATION, RESET AS EMPTY ARRAY
if($iteration === 0) $total_$files = [];
///######## RUN THROUGH ALL $fileS AND FOLDERS
foreach($files_folders as $file){
///######### IF THE CURRENT ``file`` IS A DIRECTORY UP
if($file === '.' || $file === '..') continue;
///######### IF IT CONCERNS A $file
if(is_dir($dir.'/'.$file)){
$iteration++; // *** RAISE THE ITERATION
$nested_folders[] = list_folderfiles($dir.'/'.$file, false, $iteration); // *** EXECUTE THE FUNCTION ITSELF
}
///######### IF IT CONCERNS A $file
else{
$total_files[] = $dir.'/'.$file; // *** ADD THE $file TO THE TOTAL $fileS ARRAY
$nested_folders[] = $file; // *** ADD THE $file TO THE NESTED FOLDERS ARRAY
}
}
///########==================================================
///######## IF A FLAT LIST SHOULD BE RETURNED
///########==================================================
if($return_flat) return $total_files;
///######## IF A NESTED LIST SHOULD BE RETURNED
else return $nested_folders;
///########==================================================
}
$files = list_folderfiles(ROOT, true); // *** FLAT ARRAY
///$files = list_folderfiles(ROOT, false); // *** NESTED ARRAY
echo print_r($files, true);
This is similar to another answer here, but removes SKIP_DOTS as it's not needed, and and works with strict_types:
<?php
$o_dir = new RecursiveDirectoryIterator('.');
$o_iter = new RecursiveIteratorIterator($o_dir);
foreach ($o_iter as $o_info) {
if ($o_info->getExtension() == 'php') {
echo $o_info->getPathname(), "\n";
}
}
https://php.net/splfileinfo.getextension

How to read the files and directories inside the directory

Can any one please let me know how to read the directory and find what are the files and directories inside that directory.
I've tried with checking the directories by using the is_dir() function as follows
$main = "path to the directory";//Directory which is having some files and one directory
readDir($main);
function readDir($main) {
$dirHandle = opendir($main);
while ($file = readdir($dirHandle)) {
if ($file != "." && $file != "..") {
if (is_dir($file)) {
//nothing is coming here
}
}
}
}
But it is not checking the directories.
Thanks
The most easy way in PHP 5 is with RecursiveDirectoryIterator and RecursiveIteratorIterator:
$dir = '/path/to/dir';
$directoryIterator = new RecursiveDirectoryIterator($dir);
$iterator = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $path) {
if ($path->isDir()) {
// ...
}
}
You don't need to recurse by yourself as these fine iterators handle it by themselves.
For more information about these powerful iterators see the linked documentation articles.
You have to use full path to subdirectory:
if(is_dir($main.'/'.$file)) { ... }
Use scandir
Then parse the result and eliminate '.' and '..' and is_file()
$le_map_to_search = $main;
$data_to_use_maps[] = array();
$data_to_use_maps = read_dir($le_map_to_search, 'dir');
$aantal_mappen = count($data_to_use_maps);
$counter_mappen = 1;
while($counter_mappen < $aantal_mappen){
echo $data_to_use_maps[$counter_mappen];
$counter_mappen++;
}
$data_to_use_files[] = array();
$data_to_use_files = read_dir($le_map_to_search, 'files');
$aantal_bestanden = count($data_to_use_files);
$counter_files = 1;
while($counter_files < $aantal_files){
echo $data_to_use_files [$counter_files ];
$counter_files ++;
}
Look at the reference here:
http://php.net/manual/en/function.scandir.php
Try this
$handle = opendir($directory); //Open the directory
while (false !== ($file = readdir($handle))) {
$filepath = $directory.DS.$file; //Get all files/directories in the directory
}

PHP Array Blocklist

I've created this code to cycle through the folders in the current directory and echo out a link to the folder, it all works fine. How would I go about using the $blacklist array as an array to hold the directory names of directories I dont want to show?
$blacklist = array('dropdown');
$results = array();
$dir = opendir("./");
while($file = readdir($dir)) {
if($file != "." && $file != "..") {
$results[] = $file;
}
}
closedir($dir);
foreach($results as $file) {
if($blocked != true) {
$fileUrl = $file;
$fileExplodedName = explode("_", $file);
$fileName = "";
$fileNameCount = count($fileExplodedName);
echo "<a href='".$fileUrl."'>";
$i = 1;
foreach($fileExplodedName as $name) {
$fileName .= $name." ";
}
echo trim($fileName);
echo "</a><br/>";
}
}
array_diff is the best tool for this job -- it's the shortest to write, very clear to read, and I would expect also the fastest.
$filesToShow = array_diff($results, $blacklist);
foreach($filesToShow as $file) {
// display the file
}
Use in_array for this.
$blocked = in_array($file, $blacklist);
Note that this is rather expensive. The runtime complexity of in_array is O(n) so don't make a large blacklist. This is actually faster, but with more "clumsy" code:
$blacklist = array('dropdown' => true);
/* ... */
$blocked = isset($blacklist[$file]);
The runtime complexity of the block check is then reduced to O(1) since the array (hashmap) is constant time on key lookup.

List content of directory (php)

I have a folder. I want to put every file in this folder into an array and afterwards I want to echo them all in an foreach loop.
What's the best way to do this?
Thanks!
Scandir is what you're looking for
http://php.net/manual/en/function.scandir.php
<?php
$dir = '/tmp';
$files1 = scandir($dir);
print_r($files1);
?>
Or use combination of opendir and readdir
http://php.net/manual/en/function.readdir.php
Doesn't get much easier than this
http://ca3.php.net/manual/en/function.scandir.php
Don't forget to filter out hidden and parent directories (they start with a dot) on linux.
An Alternative:
define('PATH', 'files/');
$filesArray = array();
$filesArray = glob(PATH . '*', GLOB_ONLYDIR);
This method allow you to specify/filter a by file type. E.G.,
define('PATH', 'files/');
define('FILE_TYPE', '.jpg');
$filesArray = array();
$filesArray = glob(PATH . '*' . FILE_TYPE, GLOB_ONLYDIR);
You can also get the FULL path name to the file by removing the parameter 'GLOB_ONLYDIR'
This works for files and folders in subfolders too. Return list of folders and list of files with their path.
$dir = __DIR__; //work only for this current dir
function listFolderContent($dir,$path=''){
$r = array();
$list = scandir($dir);
foreach ($list as $item) {
if($item!='.' && $item!='..'){
if(is_file($path.$item)){
$r['files'][] = $path.$item;
}elseif(is_dir($path.$item)){
$r['folders'][] = $path.$item;
$sub = listFolderContent($path.$item,$path.$item.'/');
if(isset($sub['files']) && count($sub['files'])>0)
$r['files'] = isset ($r['files'])?array_merge ($r['files'], $sub['files']):$sub['files'];
if(isset($sub['folders']) && count($sub['folders'])>0)
$r['folders'] = array_merge ($r['folders'], $sub['folders']);
}
}
}
return $r;
}
$list = listFolderContent($dir);
var_dump($list['files']);
var_dump($list['folders']);
Edit: dwich answer is better. I will leave this just for information.
readdir.
<?php
if ($handle = opendir('/path/to/dir')) {
echo "Directory handle: $handle\n";
echo "Files:\n";
while (false !== ($file = readdir($handle))) {
echo "$file\n";
}
closedir($handle);
}
?>
Hope this helps.
—Alberto

Categories