Select random file using OPENDIR() - php

I have tried:
function random_pic($dir = '../myfolder') {
$files = opendir($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
This function works using glob() but not opendir.
This returns a failed to open directory error. I guess opendir cannot accept things like *.*? Is it possible to select all files in a folder and randomly choose one?

The opendir() function wont return a list of files/folders. It will only open a handle that can be used by closedir(), readdir() or rewinddir(). The correct usage here would be glob(), but as I see that you don't want that, you could also use scandir() like the following:
<?php
$path = "./";
$files = scandir($path);
shuffle($files);
for($i = 0; ($i < count($files)) && (!is_file($files[$i])); $i++);
echo $files[$i];
?>
I'd happily do the timing to see if this takes longer or if glob() takes longer after you admit that I'm not "wrong."

The following 2 methods make use of opendir to quickly read through a directory and return a random file or directory.
All Benchmarks done use CI3 and are average of 100 pulses. Using WAMP on Win10 Intel i54460 w/ 16GB RAM
Get Random File:
function getRandomFile($path, $type=NULL, $contents=TRUE) {
if (strpos($path, $_SERVER['DOCUMENT_ROOT']) === FALSE) $path = $_SERVER['DOCUMENT_ROOT'] . '/' . $path;
if (is_dir($path)) {
if ($dh = opendir($path)) {
$arr = [];
while (false !== ($file = readdir($dh))) {
// not a directory
if (!is_dir("$path/$file") && !preg_match('/^\.{1,2}$/', $file)) {
// fits file type
if(is_null($type)) $arr[] = $file;
elseif (is_string($type) && preg_match("/\.($type)$/", $file)) $arr[] = $file;
elseif (is_array($type)) {
$type = implode('|', $type);
if (preg_match("/\.($type)$/", $file)) $arr[] = $file;
}
}
}
closedir($dh);
if (!empty($arr)) {
shuffle($arr);
$file = $arr[mt_rand(0, count($arr)-1)];
return empty($contents) ? $file : ($contents == 'path' ? "$path/$file" : file_get_contents($file));
}
}
}
return NULL;
}
Use as simple as:
// Benchmark 0.0018 seconds *
$this->getRandomFile('directoryName');
// would pull random contents of file from given directory
// Benchmark 0.0017 seconds *
$this->getRandomFile('directoryName', 'php');
// |OR|
$this->getRandomFile('directoryName', ['php', 'htm']);
// one gets a random php file
// OR gets random php OR htm file contents
// Benchmark 0.0018 seconds *
$this->getRandomFile('directoryName', NULL, FALSE);
// returns random file name
// Benchmark 0.0019 seconds *
$this->getRandomFile('directoryName', NULL, 'path');
// returns random full file path
Get Random Directory:
function getRandomDir($path, $full=TRUE, $indexOf=NULL) {
if (strpos($path, $_SERVER['DOCUMENT_ROOT']) === FALSE) $path = $_SERVER['DOCUMENT_ROOT'] . '/' . $path;
if (is_dir($path)) {
if ($dh = opendir($path)) {
$arr = [];
while (false !== ($dir = readdir($dh))) {
if (is_dir("$path/$dir") && !preg_match('/^\.{1,2}$/', $dir)) {
if(is_null($indexOf)) $arr[] = $file;
if (is_string($indexOf) && strpos($dir, $indexOf) !== FALSE) $arr[] = $dir;
elseif (is_array($indexOf)) {
$indexOf = implode('|', $indexOf);
if (preg_match("/$indexOf/", $dir)) $arr[] = $dir;
}
}
}
closedir($dh);
if (!empty($arr)) {
shuffle($arr);
$dir = $arr[mt_rand(0, count($arr)-1)];
return $full ? "$path/$dir" : $dir;
}
}
}
return NULL;
}
Use as simple as:
// Benchmark 0.0013 seconds *
$this->getRandomDir('parentDirectoryName');
// returns random full directory path of dirs found in given directory
// Benchmark 0.0015 seconds *
$this->getRandomDir('parentDirectoryName', FALSE);
// returns random directory name
// Benchmark 0.0015 seconds *
$this->getRandomDir('parentDirectoryName', FALSE, 'dirNameContains');
// returns random directory name
Use in Combo Like:
$dir = $this->getRandomDir('dirName');
$file = $this->getRandomFile($dir, 'mp3', FALSE);
// returns a random mp3 file name.
// Could be used to load random song via ajax.
single line
/** getRandomFile(String)
* Simple method for retrieving a random file from a directory
**/
function getRandomFile($path, $type=NULL, $contents=TRUE) { if (strpos($path, $_SERVER['DOCUMENT_ROOT']) === FALSE) $path = $_SERVER['DOCUMENT_ROOT'] . '/' . $path; if (is_dir($path)) { if ($dh = opendir($path)) { $arr = []; while (false !== ($file = readdir($dh))) { if (!is_dir("$path/$file") && !preg_match('/^\.{1,2}$/', $file)) { if(is_null($type)) $arr[] = $file; elseif (is_string($type) && preg_match("/\.($type)$/", $file)) $arr[] = $file; elseif (is_array($type)) { $type = implode('|', $type); if (preg_match("/\.($type)$/", $file)) $arr[] = $file; } } } closedir($dh); if (!empty($arr)) { shuffle($arr); $file = $arr[mt_rand(0, count($arr)-1)]; return empty($contents) ? $file : ($contents == 'path' ? "$path/$file" : file_get_contents($file)); } } } return NULL; }
/** getRandomDir(String)
* Simple method for retrieving a random directory
**/
function getRandomDir($path, $full=TRUE, $indexOf=NULL) { if (strpos($path, $_SERVER['DOCUMENT_ROOT']) === FALSE) $path = $_SERVER['DOCUMENT_ROOT'] . '/' . $path; if (is_dir($path)) { if ($dh = opendir($path)) { $arr = []; while (false !== ($dir = readdir($dh))) { if (is_dir("$path/$dir") && !preg_match('/^\.{1,2}$/', $dir)) { if(is_null($indexOf)) $arr[] = $file; if (is_string($indexOf) && strpos($dir, $indexOf) !== FALSE) $arr[] = $dir; elseif (is_array($indexOf)) { $indexOf = implode('|', $indexOf); if (preg_match("/$indexOf/", $dir)) $arr[] = $dir; } } } closedir($dh); if (!empty($arr)) { shuffle($arr); $dir = $arr[mt_rand(0, count($arr)-1)]; return $full ? "$path/$dir" : $dir; } } } return NULL; }
/* This is only here to make copying easier. */
Just a Note about glob && scandir. I made alternate versions of the getRandomDir using each. Using scandir had very little if any difference in benchmarks (from -.001 to +.003) Using glob was quite noticeably slower! Anywhere from +.5 to +1.100 difference on each call.

Related

Creating default object from empty value in OT Scroller

I have problem with warning on my Joomla website. More precisely "Warning: Creating default object from empty value in /public_html/modules/mod_ot_scroller/helper.php on line 40"
Here is whole helper.php file:
<?php
defined('_JEXEC') or die;
class modOTScrollerHelper
{
function getImages(&$params, $folder, $type)
{
$files = array();
$images = array();
$dir = JPATH_BASE.DS.$folder;
// check if directory exists
if (is_dir($dir))
{
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && $file != 'CVS' && $file != 'index.html' && $file != 'Thumbs.db') {
$files[] = $file;
}
}
}
closedir($handle);
foreach($type as $tp){
$tp=trim($tp);
$i = 0;
foreach ($files as $img){
if (!is_dir($dir .DS. $img))
{
if (preg_match("#$tp#i", $img)) {
$images[$i]->name = $img;
$images[$i]->folder = $folder;
++$i;
}
}
}
}
}
return $images;
}
function getFolder(&$params)
{
$folder = $params->get( 'folder' );
$LiveSite = JURI::base();
// if folder includes livesite info, remove
if ( JString::strpos($folder, $LiveSite) === 0 ) {
$folder = str_replace( $LiveSite, '', $folder );
}
// if folder includes absolute path, remove
if ( JString::strpos($folder, JPATH_SITE) === 0 ) {
$folder= str_replace( JPATH_BASE, '', $folder );
}
$folder = str_replace('\\',DS,$folder);
$folder = str_replace('/',DS,$folder);
return $folder;
}
}
?>
Whole website works fine and images shown properly.
What can I do to get rid of it?
Yeah, thats a warning, because you did not specify what $images[$i] should be. If you want to, initialize it using $images[$i] = new \stdClass();

Recursivly get all files in a directory, and sub directories by extension

I was looking at RecursiveDirectoryIterator and glob to say
"return me a list of files (in an array) based on the extension (for example) .less. Oh and look in all child, grandchild and so on and so forth, excluding . and .. until you find all files matching."
But I am not sure the best approach to create a recursive function that keeps going well beyond the grand child.
What I have is a mess, its worked for two years - but now I need to refactor and change it up:
public function get_directory_of_files($path, $filename, $extension) {
if (!is_dir($path)) {
throw new AisisCore_FileHandling_FileException("Could not find said path: " . $path);
}
if (file_exists($filename)) {
$handler = opendir($path);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$this->package_files [] = $file;
$count = count($this->package_files);
for ($i = 0; $i < $count; $i++) {
if (substr(strrchr($this->package_files [$i], '.'), 1) == $extension) {
if ($this->package_files [$i] == $filename) {
$this->files_got_back = $this->package_files [$i];
}
}
}
}
}
}
return $this->_files_got_back;
}
This requires a file name to be passed in and thats not really my thing to do any more. So how can I re-write this function to do the above "pseudo code"
This function recursively finds files with a matching ending string
function getDirectoryContents($directory, $extension)
{
$extension = strtolower($extension);
$files = array();
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while($it->valid())
{
if (!$it->isDot() && endsWith(strtolower($it->key()), $extension))
{
array_push($files, $it->key());
}
$it->next();
}
return $files;
}
function endsWith($haystack, $needle)
{
return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}
Used like so
print_r(getDirectoryContents('folder/', '.php'));
It converts the extension to lowercase to compare against
Take a look at this code:
<?php
class ex{
private function get_files_array($path,$ext, &$results){ //&to ensure it's a reference... but in php obj are passed by ref.
if (!is_dir($path)) {
//throw new AisisCore_FileHandling_FileException("Could not find said path: " . $path);
}
if ($dir = opendir($path)) {
$extLength = strlen($ext);
while (false !== ($file = readdir($dir))) {
if ($file != '.' && $file != '..'){
if (is_file($path.'/'.$file) && substr($file,-$extLength) == $ext){
$results[] = $path . '/' . $file; //it's a file and the correct extension
}
elseif (is_dir($path . '/'. $file)){
$this->get_files_array($path.'/'.$file, $ext, $results); //it's a dir
}
}
}
}else{
//unable to open dir
}
}
public function get_files_deep($path,$ext){
$results = array();
$this->get_files_array($path,$ext,$results);
return $results;
}
}
$ex = new ex();
var_dump($ex->get_files_deep('_some_path','.less'));
?>
It will retrieve all the files with the matching extension in the path and it's sub directories.
I hope it's what you need.

php function to read subdir content

I would like to ask what I have to add to make this function to show not only the files on top dir but also the files in subdirs..
private function _populateFileList()
{
$dir_handle = opendir($this->_files_dir);
if (! $dir_handle)
{
return false;
}
while (($file = readdir($dir_handle)) !== false)
{
if (in_array($file, $this->_hidden_files))
{
continue;
}
if (filetype($this->_files_dir . '/' . $file) == 'file')
{
$this->_file_list[] = $file;
}
}
closedir($dir_handle);
return true;
}
Thank you in advance!
You could implement the recursion yourself, or you could use the existing iterator classes to handle the recursion and filesystem traversal for you:
$dirIterator = new RecursiveDirectoryIterator('.', FilesystemIterator::SKIP_DOTS);
$recursiveIterator = new RecursiveIteratorIterator($dirIterator);
$filterIterator = new CallbackFilterIterator($recursiveIterator, function ($file) {
// adjust as needed
static $badFiles = ['foo', 'bar', 'baz'];
return !in_array($file, $badFiles);
});
$files = iterator_to_array($filterIterator);
var_dump($files);
By this you can get all subdir content
customerdel('FolderPath');
function customerdel($dirname=null){
if($dirname!=null){
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
echo $dirname."/".$file.'<br>';
else{
echo $dirname.'/'.$file.'<br> ';
customerdel($dirname.'/'.$file);
}
}
}
closedir($dir_handle);
}
}
Here is how you can get a recursive array of all files in a directory and its subdirectories.
The returned array is like: array( [fileName] => [filePath] )
EDIT: I've included a small check if there are filenames in the subdirectories with the same name. If so, an underscore and counter is added to the key-name in the returned array:
array( [fileName]_[COUNTER] => [filePath] )
private function getFileList($directory) {
$fileList = array();
$handle = opendir($directory);
if ($handle) {
while ($entry = readdir($handle)) {
if ($entry !== '.' and $entry !== '..') {
if (is_dir($directory . $entry)) {
$fileList = array_merge($fileList, $this->getFileList($directory . $entry . '/'));
} else {
$i = 0;
$_entry = $entry;
// Check if filename is allready in use
while (array_key_exists($_entry, $fileList)) {
$i++;
$_entry = $entry . "_$i";
}
$fileList[$_entry] = $directory . $entry;
}
}
}
closedir($handle);
}
return $fileList;
}

How to scan all the .m files using php? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
php scandir --> search for files/directories
I have a folder, inside this folder, have many subfolders, but I would like to scan all the subfolders, and scan all the .m file... How can I do so??
Here is the file:
/MyFilePath/
/myPath.m
/myPath2.m
/myPath3.m
/MyClasses/
/my.m
/my1.m
/my2.m
/my3.m
/Utilities/
/u1.m
/u2.m
/External/
/a.m
/b.m
/c.m
/Internal/
/d.m
/e.m
/f.m
/Views/
/a_v.m
/b_v.m
/c_v.m
/Controllers/
/a_vc.m
/b_vc.m
/c_vc.m
/AnotherClasses/
/anmy.m
/anmy1.m
/anmy2.m
/anmy3.m
/Networking/
/net1.m
/net2.m
/net3.m
/External/
/Internal/
/Views/
/Controllers/
You could also use some of the SPL's iterators. A quick and basic example would look like:
$directories = new RecursiveDirectoryIterator('path/to/search');
$flattened = new RecursiveIteratorIterator($directories);
$filter = new RegexIterator($flattened, '/\.in$/');
foreach ($filter as $file) {
echo $file, PHP_EOL;
}
More infos (mostly incomplete):
http://php.net/recursivedirectoryiterator
http://php.net/recursiveiteratoriterator
http://php.net/regexiterator
You can use a recursive function like this:
function searchFiles($dir,$pattern,$recursive=false)
{
$matches = array();
$d = dir($dir);
while (false !== ($entry = $d->read()))
{
if (is_dir($d->path.$entry) && $recursive)
{
$subdir = $d->path.$entry;
$matches = array_merge($matches,searchFiles($dir,$pattern,$recursive));
}
elseif (is_file($d->path.$entry) && preg_match($pattern,$entry))
{
$matches[] = $d->path.$entry;
}
}
$d->close();
return $matches;
}
Usage:
$matches = searchFiles("/mypath/","'[.]m$'i",true);
function ScanForMFiles($dir){
$return = array();
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($dir.$file)){
$return = array_merge($return, ScanForMFiles($dir.$file."/"));
}
else {
if(substr($file, -2) == '.m')
$return[] = $file;
}
}
}
closedir($handle);
}
return $return;
}
var_dump(ScanForMFiles('./'));
You'll want to look to the PHP docs for details on this: http://php.net/manual/en/function.readdir.php
Here's an example that should do what you you want. It will return an array of all .m files in the sub directories. You can then loop through each file and read the contents if that is what you are interested in.
<?php
function get_m_files($root = '.'){
$files = array();
$directories = array();
$last_letter = $root[strlen($root)-1];
$root = ($last_letter == '\\' || $last_letter == '/') ? $root : $root.DIRECTORY_SEPARATOR;
$directories[] = $root;
while (sizeof($directories)) {
$dir = array_pop($directories);
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$file = $dir.$file;
if (is_dir($file)) {
$directory_path = $file.DIRECTORY_SEPARATOR;
array_push($directories, $directory_path);
} elseif (is_file($file)) {
if (substr( $file, -strlen( ".m" ) ) == ".m") {
$files[] = $file;
}
}
}
closedir($handle);
}
}
return $files;
}
?>

PHP - Code to traverse a directory and get all the files(images)

i want to write a page that will traverse a specified directory.... and get all the files in that directory...
in my case the directory will only contain images and display the images with their links...
something like this
How to Do it
p.s. the directory will not be user input.. it will be same directory always...
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
use readdir
<?php
//define directory
$dir = "images/";
//open directory
if ($opendir = opendir($dir)){
//read directory
while(($file = readdir($opendir))!= FALSE ){
if($file!="." && $file!= ".."){
echo "<img src='$dir/$file' width='80' height='90'><br />";
}
}
}
?>
source: phpacademy.org
You'll want to use the scandir function to walk the list of files in the directory.
Hi you can use DirectoryIterator
try {
$dir = './';
/* #var $Item DirectoryIterator */
foreach (new DirectoryIterator($dir) as $Item) {
if($Item->isFile()) {
echo $Item->getFilename() . "\n";
}
}
} catch (Exception $e) {
echo 'No files Found!<br />';
}
If you want to pass directories recursively:
http://php.net/manual/en/class.recursivedirectoryiterator.php
/**
* function get files
* #param $path string = path to fine files in
* #param $accept array = array of extensions to accept
* #param currentLevel = 0, stopLevel = 0
* #return array of madmanFile objects, but you can modify it to
* return whatever suits your needs.
*/
public static function getFiles( $path = '.', $accept, $currentLevel = 0, $stopLevel = 0){
$path = trim($path); //trim whitespcae if any
if(substr($path,-1)=='/'){$path = substr($path,0,-1);} //cutoff the last "/" on path if provided
$selectedFiles = array();
try{
//ignore these files/folders
$ignoreRegexp = "/\.(T|t)rash/";
$ignore = array( 'cgi-bin', '.', '..', '.svn');
$dh = #opendir( $path );
//Loop through the directory
while( false !== ( $file = readdir( $dh ) ) ){
// Check that this file is not to be ignored
if( !in_array( $file, $ignore ) and !preg_match($ignoreRegexp,$file)){
$spaces = str_repeat( ' ', ( $currentLevel * 4 ) );
// Its a directory, so we need to keep reading down...
if( is_dir( "$path/$file" ) ){
//merge current selectFiles array with recursion return which is
//another array of selectedFiles
$selectedFiles = array_merge($selectedFiles,MadmanFileManager::getFiles( "$path/$file", $accept, ($currentLe$
} else{
$info = pathinfo($file);
if(in_array($info['extension'], $accept)){
$selectedFiles[] = new MadmanFile($info['filename'], $info['extension'], MadmanFileManager::getSize($
}//end if in array
}//end if/else is_dir
}
}//end while
closedir( $dh );
// Close the directory handle
}catch (Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
return $selectedFiles;
}
You could as others have suggested check every file in the dir, or you could use glob to identify files based on extension.
I use something along the lines of:
if ($dir = dir('images'))
{
while(false !== ($file = $dir->read()))
{
if (!is_dir($file) && $file !== '.' && $file !== '..' && (substr($file, -3) === 'jpg' || substr($file, -3) === 'png' || substr($file, -3) === 'gif'))
{
// do stuff with the images
}
}
}
else { echo "Could not open directory"; }
You could also try the glob function:
$path = '/your/path/';
$pattern = '*.{gif,jpg,jpeg,png}';
$images = glob($path . $pattern, GLOB_BRACE);
print_r($images);
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
For further reference :http://php.net/manual/en/function.opendir.php
I would start off by creating a recursive function:
function recurseDir ($dir) {
// open the provided directory
if ($handle = opendir($_SERVER['DOCUMENT_ROOT'].$dir)) {
// we dont want the directory we are in or the parent directory
if ($entry !== "." && $entry !== "..") {
// recursively call the function, if we find a directory
if (is_dir($_SERVER['DOCUMENT_ROOT'].$dir.$entry)) {
recurseDir($dir.$entry);
}
else {
// else we dont find a directory, in which case we have a file
// now we can output anything we want here for each file
// in your case we want to output all the images with the path under it
echo "<img src='".$dir.$entry."'>";
echo "<div><a href='".$dir.$entry."'>".$dir.$entry."</a></div>";
}
}
}
}
The $dir param needs to be in the following format:
"/path/" or "/path/to/files/"
Basically, just don't include the server root, because i have already done that below using $_SERVER['DOCUMENT_ROOT'].
So, in the end just call the recurseDir function we just made in your code once, and it will traverse any sub folders and output the image with the link under it.

Categories