function read_comments() {
if (!is_dir(COMMENT_DIR) || !is_readable(COMMENT_DIR))
return false;
$file_list = glob(COMMENT_DIR . '*20130721T161046-1262521337.txt');
$comments = array();
foreach ($file_list as $file_name) {
if (($data = file($file_name)) !== false) {
$comments[] = unserialize_comment($data);
}
}
return $comments;}
How would i be able to put a random file name in the glob()? The foreach() keeps giving me trouble.
This function returns a random file from a given folder. It also allows extension filtering.
function RandomFile($folder='COMMENT_DIR', $extensions='.txt'){
// fix path:
$folder = trim($folder);
$folder = ($folder == '') ? './' : $folder;
// check folder:
if (!is_dir($folder)){ die('invalid folder given!'); }
// create files array
$files = array();
// open directory
if ($dir = #opendir($folder)){
// go trough all files:
while($file = readdir($dir)){
if (!preg_match('/^\.+$/', $file) and
preg_match('/\.('.$extensions.')$/', $file)){
// feed the array:
$files[] = $file;
}
}
// close directory
closedir($dir);
}
else {
die('Could not open the folder "'.$folder.'"');
}
if (count($files) == 0){
die('No files where found :-(');
}
// seed random function:
mt_srand((double)microtime()*1000000);
// get an random index:
$rand = mt_rand(0, count($files)-1);
// check again:
if (!isset($files[$rand])){
die('Array index was not found! very strange!');
}
}
And use
$file_list = glob($folder . $rand_file);
Related
I want to keep only 10 newest files in a folder and delete others.
I created a script that deletes only the oldest ones if a file number is larger than 10.
How can I adapt this script to my needs?
$directory = "/home/dir";
// Returns array of files
$files = scandir($directory);
// Count number of files and store them to variable..
$num_files = count($files)-2;
if($num_files>10){
$smallest_time=INF;
$oldest_file='';
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
$time=filemtime($directory.'/'.$file);
if (is_file($directory.'/'.$file)) {
if ($time < $smallest_time) {
$oldest_file = $file;
$smallest_time = $time;
}
}
}
closedir($handle);
}
echo $oldest_file;
unlink($oldest_file);
}
Basic script to give you the idea. Push all the files with their times into an array, sort it by descending time order and walk trough. if($count > 10) says when the deletion should start, i.e. currently it keeps the newest 10.
<?php
$directory = ".";
$files = array();
foreach(scandir($directory) as $file){
if(is_file($file)) {
//get all the files
$files[$file] = filemtime($file);
}
}
//sort descending by filemtime;
arsort($files);
$count = 1;
foreach ($files as $file => $time){
if($count > 10){
unlink($file);
}
$count++;
}
You could simply sort the result of scandir by the returned files' modification dates:
/**
* #return string[]
*/
function getOldestFiles(string $folderPath, int $count): array
{
// Grab all the filenames
$filenames = #scandir($folderPath);
if ($filenames === false) {
throw new InvalidArgumentException("{$folderPath} is not a valid folder.");
}
// Ignore folders (remove from array)
$filenames = array_filter($filenames, static function (string $filename) use ($folderPath) {
return is_file($folderPath . DIRECTORY_SEPARATOR . $filename);
});
// Sort by ascending last modification date (older first)
usort($filenames, static function (string $file1Name, string $file2Name) use ($folderPath) {
return filemtime($folderPath . DIRECTORY_SEPARATOR . $file1Name) <=> filemtime($folderPath . DIRECTORY_SEPARATOR . $file2Name);
});
// Return the first $count
return array_slice($filenames, 0, $count);
}
Usage:
$folder = '/some/folder';
$oldestFiles = getOldestFiles($folder, 10);
foreach ($oldestFiles as $file) {
unlink($folder . '/' . $file);
}
Note: this is obviously over-commented for the purpose of this answer.
i want to list all directory, sub-directory and files using php.
i have tried following code. it returns all the directory, sub directory and files but it's not showing in correct order.
for ex:default order is 1dir, 2dir, 7dir, 8dir while in browser it shows 1dir, 8dir, 7dir, 2dir which is not correct.
code:
function createDir($path = '.')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file) && $file != '.' && $file !='..') {
printSubDir($file, $path);
}
else if ($file != '.' && $file !='..'){
$allowed = array('pdf','doc','docx','xls','xlsx','jpg','png','gif','mp4','avi','3gp','flv','mov','PDF','DOC','DOCX','XLS','XLSX','JPG','PNG','GIF','MP4','AVI','3GP','FLV','MOV','html','HTML','css','CSS','js','JS');
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($ext,$allowed) ) {
$queue[] = $file;
}
}
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path)
{
sort($queue);
foreach ($queue as $file)
{
//printFile($file, $path);
}
}
function printFile($file, $path) {
echo "<li><a href=\"".$path.$file."\" target='_blank'>$file</a></li>";
}
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/");
echo "</li>";
}
createDir($path);
?>
need help to fix the code and display the direcotry , subdirectory and files in correct order.
I'm having the same problem during listing a directory files. But I have used DirectoryLister
This code is very useful. You can list out your files easily.
You can implement it by following steps.
Download and extract Directory Lister
Copy resources/default.config.php to resources/config.php
Upload index.php and the resources folder to the folder you want listed
Upload additional files to the same directory as index.php
I hope this might help you
You can start by looping the array and printing each directory:
public function dirtree($dir, $regex='', $ignoreEmpty=false) {
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string)$dir);
}
$dirs = array();
$files = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
// print_r($node);
$tree = dirtree($node->getPathname(), $ignoreEmpty);
// print"<pre>";print_r($tree);
if (!$ignoreEmpty || count($tree)) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
//if ('' == $regex || preg_match($regex, $name)) {
$files[] = $name;
}
}
asort($dirs);
sort($files);
return array_merge($files, $dirs);
}
Use like this:
$fileslist = dirtree('root');
echo "<pre style='font-size:15px'>";
print_r($fileslist);
<?
if ($directory = opendir('data/')) { // Open dir
while (false !== ($files = readdir($directory))) { //Read directory
if ($files != "." && $files != "..") { //Strip . and ..
$files = str_replace("122.","",$files); // Remove 122.
$files = str_replace("234.","",$files); // Remove 234.
echo "$files<br />"; // Get results
}
}
closedir($directory); // close directory
}
?>
files in directory is: 122.256879, 234.4263, 122.4263, 234.256879
I get results:
256879
4263
4263
256879
But i need unique results:
256879
4263
How to get this results?
<?
$aFiles = array();
if ($directory = opendir('data/')) { // Open dir
while (false !== ($files = readdir($directory))) { //Read directory
if ($files != "." && $files != "..") { //Strip . and ..
$files = str_replace("122.","",$files); // Remove 122
$files = str_replace("234.","",$files); // Remove 234
if(in_array($files, $aFiles) == false){
echo "$files<br />"; // Get results
$aFiles[] = $files;
}
}
}
closedir($directory); // close directory
}
?>
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.
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.