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>";
}
?>
Related
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]);
I have a folder containing many PDF files. I have built a script that zip these pdf files into 100mb batches each.
#!/usr/bin/php
<?php
$pathToFiles = "../pdffakturor_test/";
$maxFileSize = 100 * 1024 * 1024;
$counter = 1;
$currentsize = 0;
$created_at_datum = date("Ymd");
$created_at_clock = date("Hi");
$zip = new ZipArchive;
if($counter <= 10)
{
$counter = sprintf("%02s", $counter);
}
$zip->open('PROD_SE_C_S_E_'.$created_at_datum.'_'.$created_at_clock.$counter.'.zip', ZipArchive::CREATE);
if ($handle = opendir($pathToFiles))
{
while (false !== ($entry = readdir($handle)))
{
if (substr($entry, -4) == ".pdf")
{
$filesize = filesize($pathToFiles.$entry);
if($currentsize >= $maxFileSize)
{
$zip->close();
$zip = null;
$zip = new ZipArchive;
$currentsize = 0;
if($counter <= 10)
{
$counter = sprintf("%02s", $counter);
}
$zip->open('PROD_SE_C_S_E_'.$created_at_datum.'_'.$created_at_clock.$counter.'.zip', ZipArchive::CREATE);
$counter++;
}
$zip->addFile($pathToFiles.$entry, $entry);
$currentsize += $filesize;
}
}
closedir($handle);
}
?>
The problem I have is that the first zip batch becomes 183mb and the others 91,6mb. I can't figure out why the first becomes 183mb?
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>";
}
}
So i have this page which lists '.txt' file contents on the website. I tried to paginate it, but it doesn't work. I'd like to have only one story per page (one story is data[0] . data[1])
The page is called to the browser via ajax.
Here is my code:
<?php
$dataArray = array();
//Number of chars for the string
$num = 500;
$dir = '../php/biralas_tortenetek/';
$willcount = readdir(opendir($dir));
$totfiles = count(readdir(opendir($dir)));
//Check if </div>DIR e</div>xists
if ($handle = opendir($dir)) {
//Loop over the directory
while (false !== ($file = readdir($handle))) {
//Strip out the . and .. files
if ($file != "." && $entry != "..") {
//Store file contents
$filecontent = file_get_contents($dir . $file);
//Split the content and store in array
$length = strlen($filecontent);
$dataArray[] = array(substr($filecontent, 0, $num), substr($filecontent, $num, $length ));
}
}
//close the dir
closedir($handle);
}
?><?php
$page = isset($_GET['page']) ? $_GET['page']-1 : 0;
echo "<br/>";
for($x=$page*1; $x < $totfiles && $x < ($page+1)*12; $x++)
{
foreach($dataArray as $data) { ?>
<div class="visible">
<?php echo $data[0] . $data[1]; ?>
</div><?php } ?>
</div>
<?php }
for($page=1; ($page-1)*12 < $totfiles; $page++)
{
echo "<div class='lapozo'><a onclick='story_changepage($page);' href='../html/blog.php#tortenetek?page=$page'>$page</a></div>";
}
?>
So again, the goal is to have only one story per page.
Thanks!
1st solution:
$willcount = readdir(opendir($dir));
$i = 0;
//Check if </div>DIR e</div>xists
if ($handle = opendir($dir)) {
//Loop over the directory
while (false !== ($file = readdir($handle))) {
//Strip out the . and .. files
if ($file != "." && $entry != "..") {
//Store file contents
$filecontent = file_get_contents($dir . $file);
//Split the content and store in array
$length = strlen($filecontent);
// store file as indexed item of array
$dataArray[$i++] = array(substr($filecontent, 0, $num), substr($filecontent, $num, $length ));
}
}
//close the dir
closedir($handle);
}
// store total files in dir
$totfiles = $i;
$page = isset($_GET['page']) ? $_GET['page']-1 : 0;
echo "<br/>";
for($x=$page*12; $x < $totfiles && $x < ($page+1)*12; $x++) {
$data = $dataArray[$x];
?>
<div class="visible">
<?php echo $data[0] . $data[1]; ?>
</div>
<?php
}
CUT 2nd Solution: // prefered It's use less memory than 1st solution
$willcount = readdir(opendir($dir));
$i = 0;
// get page
$page = isset($_GET['page']) ? $_GET['page']-1 : 0;
//Check if </div>DIR e</div>xists
if ($handle = opendir($dir)) {
//Loop over the directory
while (false !== ($file = readdir($handle))) {
//Strip out the . and .. files
if ($file != "." && $entry != "..") {
$i ++;
// if our page not first, skip add
if ($i <= $page * 12) continue;
// if we reach end of the page, break
if ($i > ($page + 1)* 12) break;
//Store file contents
$filecontent = file_get_contents($dir . $file);
//Split the content and store in array
$length = strlen($filecontent);
$dataArray[] = array(substr($filecontent, 0, $num), substr($filecontent, $num, $length ));
}
}
//close the dir
closedir($handle);
}
// store total files in dir
$totfiles = $i;
echo "<br/>";
foreach($dataArray as $data) {
?>
<div class="visible">
<?php echo $data[0] . $data[1]; ?>
</div>
<?php
}
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;
}