PHP absolute file - php

How do we return the absolute path of largest file in a particular directory?
I've been fishing around and haven't turned up anything concrete?
I'm thinking it has something to do with glob()?

$sz = 0;
$dir = '/tmp'; // will find largest for `/tmp`
if ($handle = opendir($dir)) { // will iterate through $dir
while (false !== ($entry = readdir($handle))) {
if(($curr = filesize($dir . '/' . $entry)) > $sz) { // found larger!
$sz = $curr;
$name = $entry;
}
}
}
echo $dir . '/' . $name; // largest

$dir = 'DIR_NAME';
$max_filesize = 0;
$path= '';
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(realpath($dir),FilesystemIterator::SKIP_DOTS)) as $file){
if ($file->getSize() >= $max_filesize){
$max_filesize = $file->getSize();
$path = $file->getRealPath(); // get absolute path
}
}
echo $path;

function getFileSize($directory) {
$files = array();
foreach (glob($directory. '*.*') as $file) {
$files[] = array('path' => $file, 'size' => filesize($file));
}
return $files;
}
function getMaxFile($files) {
$maxSize = 0;
$maxIndex = -1;
for ($i = 0; $i < count($files); $i++) {
if ($files[$i]['size'] > $maxSize) {
$maxSize = max($maxSize, $files[$i]['size']);
$maxIndex = $i;
}
}
return $maxIndex;
}
usage:
$dir = '/some/path';
$files = getFileSize($dir);
echo '<pre>';
print_r($files);
echo '</pre>';
$maxIndex = getMaxFile($files);
var_dump($files[$maxIndex]);

Related

How to get 15 random images from a folder in Wordpress?

I need to get 15 random images from a folder and show them on a page:
I tried the following code, however it did not do what I wanted:
$string =array();
$filePath='wp-content/themes/tema/img-test/';
$dir = opendir($filePath);
while ($file = readdir($dir)) {
if (eregi("\.png",$file) || eregi("\.jpg",$file) || eregi("\.gif",$file) ) {
$string[] = $file;
}
}
while (sizeof($string) != 0){
$img = array_pop($string);
echo "<img src='$filePath$img' width='100px'/>";
}
So, you have all the files in $string array, that's good.
You can either use the rand() function to get some random integer in the arrays size:
$string = ['img1.jpg','img2.jpg','img3.jpg'];
$rand = rand(0,count($string)-1);
echo $string[$rand];
You would have to loop that.
Or, you could use array_rand() which will automate all that:
$string = ['img1.jpg','img2.jpg','img3.jpg'];
$amount = 3;
$rand_arr = array_rand($string, $amount);
for($i=0;$i<$amount;$i++) {
echo $string[$rand_arr[$i]] ."<br>";
}
You could do this using the glob() function native to PHP. It will get all files in a directory. Following that you can pick one file from the retrieved list.
$randomFiles = array();
$files = glob($dir . '/*.*');
$file = array_rand($files);
for ($i = 0; $i <= 15; $i++) {
$randomFiles[] = $files[$file];
}
Use this code. Your random image will be available in $arRandomFiles.
$filePath = 'wp-content/themes/tema/img-test/';
$files = glob($filePath. '*.{jpeg,gif,png}', GLOB_BRACE);
$arKeys = array_rand($files, 15);
$arRandomFiles = array();
foreach ($arKeys as $key) {
$arRandomFiles[] = $files[$key];
}
var_dump($arRandomFiles);
Simple function that handles that
<?php
function getImg( $path ) {
$filePath= $path . '*';
$imgs = glob( $filePath );
if( $imgs ) {
$i = 1;
foreach( $imgs as $img ) {
if( $i <= 15 ) {
$ext = pathinfo( $img, PATHINFO_EXTENSION );
if( in_array( $ext, array( 'jpg', 'jpeg', 'png', 'gif' ) ) )
$r[] = $img;
}
else
break;
$i++;
}
shuffle( $r );
return $r;
}
else
return array();
}
print_r( getImg( 'wp-content/themes/tema/img-test/' ) );
You can try function like:
function getRandomFile($directory)
{
$directoryIterator = new DirectoryIterator($directory);
$count = iterator_count($directoryIterator) - 2;
foreach ($directoryIterator as $fileInfo) {
$last = $fileInfo->getRealPath();
if ($fileInfo->isFile() && (rand() % $count == 0)) {
break;
}
}
return $last;
}

endless directory list php

i have this php code to list all files in a directory and output filesize and a download link.
<?
function human_filesize($bytes, $decimals = 2) {
$size = array(' B',' kB',' MB',' GB',' TB',' PB',' EB',' ZB',' YB');
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . #$size[$factor];
}
$excludedFiles = array('.','..');
$excludedExtensions = array ('html','htm','php');
// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] = strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] = strtolower($excludedExtensions[$i]);
// Define the full path to your folder from root
$dir = "./";
// Open the folder
$dir_handle = #opendir($dir) or die("Unable to open $dir");
// Loop through the files
while ($file = readdir($dir_handle)) {
$extn = explode('.',$file);
$extn = array_pop($extn);
if (!in_array(strtolower($file),$excludedFiles) && !in_array(strtolower($extn),$excludedExtensions)){
if($file == "." || $file == ".." )
continue;
echo "<tr>
<td>
<a class='Testo' href=\"$file\" download>$file</a></td>
<td><font class='TestoPiccoloBo'>[" . human_filesize(filesize($file)) . "]</font></td>
</tr>";
}
}
// Close
closedir($dir_handle);
?>
i wanted the list to be alphabetically ordered so i added
$files = scandir($dir);
after the $dir line and
foreach ($files as $file){
after the while ($file = readdir($dir_handle)) { line
and a
}
before the closedir($dir_handle); line
now the files list in alphabetical order, but the list is endless. the list starts over and over, like a loop.
What am I doing wrong? Is this the correct way to accomplish this?
Any help would be much appreciated.
Thanks!
You can put your folder in an array and sort it with the php sort function. Then print them :
<?
function human_filesize($bytes, $decimals = 2) {
$size = array(' B',' kB',' MB',' GB',' TB',' PB',' EB',' ZB',' YB');
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . #$size[$factor];
}
$excludedFiles = array('.','..');
$arrayFiles = array();
$excludedExtensions = array ('html','htm','php');
// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] = strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] = strtolower($excludedExtensions[$i]);
// Define the full path to your folder from root
$dir = "./";
// Open the folder
$dir_handle = #opendir($dir) or die("Unable to open $dir");
// Loop through the files
while ($file = readdir($dir_handle)) {
$extn = explode('.',$file);
$extn = array_pop($extn);
if (!in_array(strtolower($file),$excludedFiles) && !in_array(strtolower($extn),$excludedExtensions)){
if($file == "." || $file == ".." )
continue;
$arrayFiles[] = $file;
}
} // dunno what are these } so i put my loop after
// Close
closedir($dir_handle);
sort($arrayFiles);
foreach ($arrayFiles as $file) {
echo "<tr>
<td>
<a class='Testo' href=\"$file\" download>$file</a></td>
<td><font class='TestoPiccoloBo'>[" . human_filesize(filesize($file)) . "]</font></td>
</tr>";
}
?>

Link list based on directory without file extension and hyphens in php

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>";
}
}

PHP – get the size of a directory

What is the best way to get the size of a directory in PHP? I'm looking for a lightweight way to do this since the directories I'll use this for are pretty huge.
There already was a question about this on SO, but it's three years old and the solutions are outdated.(Nowadays fopen is disabled for security reasons.)
Is the RecursiveDirectoryIterator available to you?
$bytes = 0;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($iterator as $i)
{
$bytes += $i->getSize();
}
You could try the execution operator with the unix command du:
$output = du -s $folder;
FROM: http://www.darian-brown.com/get-php-directory-size/
Or write a custom function to total the filesize of all the files in the directory:
function getDirectorySize($path)
{
$totalsize = 0;
$totalcount = 0;
$dircount = 0;
if($handle = opendir($path))
{
while (false !== ($file = readdir($handle)))
{
$nextpath = $path . '/' . $file;
if($file != '.' && $file != '..' && !is_link ($nextpath))
{
if(is_dir($nextpath))
{
$dircount++;
$result = getDirectorySize($nextpath);
$totalsize += $result['size'];
$totalcount += $result['count'];
$dircount += $result['dircount'];
}
else if(is_file ($nextpath))
{
$totalsize += filesize ($nextpath);
$totalcount++;
}
}
}
}
closedir($handle);
$total['size'] = $totalsize;
$total['count'] = $totalcount;
$total['dircount'] = $dircount;
return $total;
}

Load Random Images from Directory

I'd like to randomly load images from a directory and have a button somewhere that refreshes the entire page. Here's the current code I have now:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
}
?>
The problem is it loads all 400,000 images at once. I only want 30 to load. 30 random images from the directory. I tried looking up some code such as modifying the above to this:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
if (++$i == 2) break;
}
?>
But it seems to do absolutely nothing.. So if someone can help me get 30 random photos from that directory to load and have some type of reload button, that would be of great help.
Thank you in advance
Here is my solution with a cache:
<?php
define('CACHE_FILE', 'mycache.tmp');
define('CACHE_TIME', 20); // 20 seconds (for testing!)
define('IMG_COUNT', 30);
define('IMG_DIR', '../public/wp-content/uploads/2012/01');
/**
* Loads the list (an array) from the cache
* Returns FALSE if the file couldn't be opened or the cache was expired, otherwise the list (as an array) will be returned.
*/
function LoadListFromCache($cacheFile, $cacheTime)
{
if ( file_exists($cacheFile) )
{
$fileHandle = fopen($cacheFile, 'r');
if ( !$fileHandle )
return false;
// Read timestamp (separated by "\n" from the content)
$timestamp = intval( fgets($fileHandle) );
fclose($fileHandle);
// Expired?
if ( $timestamp+$cacheTime > time() )
return false;
else
{
// Unserialize the content!
$content = file_get_contents($cacheFile);
$content = substr( $content, strpos($content, "\n") );
$list = unserialize($content);
return $list;
}
}
return false;
}
/**
* Caches the passed array
* Returns FALSE if the file couldn't be opened, otherwise TRUE.
*/
function SaveListToCache($cacheFile, $list)
{
$fileHandle = fopen($cacheFile, 'w');
if ( $fileHandle === FALSE ) return false;
fwrite($fileHandle, time());
fwrite($fileHandle, "\n");
fwrite($fileHandle, serialize($list));
fclose($fileHandle);
return true;
}
/**
* Generates the list of all image files (png, jpg, jpeg) and caches it.
* Returns the list as an array.
*/
function GenerateList()
{
$a = array();
$dir = IMG_DIR;
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
SaveListToCache(CACHE_FILE, $a);
return $a;
}
function GetRandomImages($list, $count)
{
$listCount = count($list);
$randomEntries = array();
for ($i=0; $i<$count; $i++)
{
$randomEntries[] = $list[ rand(0, $listCount) ];
}
return $randomEntries;
}
// This code will execute the other functions!
$list = LoadListFromCache(CACHE_FILE, CACHE_TIME);
if ( $list === FALSE )
{
$list = GenerateList();
}
$images = GetRandomImages($list, IMG_COUNT);
foreach ($images as $image)
{
echo '<img src="', IMG_DIR.DIRECTORY_SEPARATOR.$image, '" />';
}
If you have 400,000 images then I think reading the entire directory everytime is going to be an expensive means of showing random images. I would use a database instead and store the file paths in it.
If you want to use your existing code then think of it this way. You have an array of length n containing image names. You want to generate thirty random numbers between 0 and n-1. Then display the image associated with that position in the array. I'm not a php expert, but here is some pseudocode:
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
for ( i=0; i < 30; i++) {
//generate a random number between 0 and N-1
random = rand(0, $a.length - 1);
//display that image in the array
echo "<img src='" . $dir . '/' . $a[random] . "' />";
}
You need to create a new variable for the counter instead of using $i
For example, you can do this instead
$j = 0;
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
$j++;
if ($j >= 30)
{
break;
}
}
EDIT: Perhaps for the random part you can first generate a random number between 0 and n-1 where n is the total number of the images and then just echo out the image from the array with the index number.
Instead of using foreach, I think you'll need a for loop instead.
$totalImgs = count($a);
$imgUsed = array();
for ($j = 0; $j < 30; $j++)
{
do
{
$randIndex = mt_rand(0, $totalImgs);
}
while ($imgUsed[$randIndex] === TRUE);
$imgUsed[$randIndex] = TRUE;
echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
}
You should maybe only read 30 file from your directory. Stop looking in the directory when readdir return false or your array's length is 30.
This should work
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle)) && (count($a) <= 30) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
It may not execute (I didn't try). But the idea is here
For randomize the image: shuffle($a) should do the trick
in simplest way ,
you can use
find , sort , head
commands in linux,in conjuction with PHP's built in
exec()
function to get 30 random image links easily , the folowing snippet lists how to do it
(How to get random 30 image links in an array.)
<?php
$picdir = "directory/containing/pictures"; // directory containing only pictures
exec("find " . $picdir . " | sort -R | head -30 ",$links);
while(list($index,$val) = each($links) ) {
echo "<img src =" .$val . "> <br/>"; // shows image
}
?>
Here $links array contain random 30 image names(from folder) with complete path . This is used with img tag in echo to generate images
Here $picdir has the path of the directory having images and it is assumed that dirrectory is having only image files . in other case its only matter of modifying find command to exclude non image files(such as using grep command to exclude )

Categories