Php Array (few) foreach get values - php

Doing simple ftp viewer in php:
i've got a function that returns arrays with file_name.
I do (in the end of my function) print_r($files); and this is out put
Array ( [0] => task_manager.zip [1] => 1086237 [2] => zip ) Array ( [0] => asd.zip [1] => 1086237 [2] => zip [3] => fonts/some_file.zip [4] => 959224 [5] => zip )
As you can see i get arrays, and this is perfect but then i want to get file_name, file_size & file_extension and I get fail:
p.s - ListFiles - is my function name, ('fonts/') - folder where i find files
foreach (ListFiles('fonts/') as $key=>$file){
echo 'file_name = '.$file."<br/>";
}
and I get:
file_name = task_manager.zip
file_name = 1086237
file_name = zip
file_name = fonts/some_file.zip
file_name = 959224
file_name = zip
which actually is wrong, because i want do it in one line, something like this:
WHAT I WANT (NEAR THE PERFECT WAY) TO DO SOMETHING LIKE THIS:
in php:
foreach (ListFiles('fonts/') as $key=>$file){
echo 'file_name = '.$file[0].'file_size = '.$file[1].'file_ext = '.$file[2].'<br/>';
}
in html:
file_name = task_manager.zip, file_size = 1086237, file_ext = zip
file_name = some_file.zip, file_size = 959224, file_ext = zip
UPDATE: MY ListFiles function
function ListFiles($dir) {
if($dh = opendir($dir)) {
//This data I get from form
$allowedExts = array();
if(isset($_POST['exts'])){
for ( $i=0; $i < count($_POST['exts']); $i++ ){
array_push($allowedExts, $_POST['exts'][$i]);
}
} // end of this data
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "" . $file);
if(is_array($inner_files))
$files = array_merge($files, $inner_files);
} else {
if(in_array(end(explode('.', $file)), $allowedExts)){
$filesize = filesize('./'.$dir.$file);
$userfile_extn = substr($file, strrpos($file, '.')+1);
array_push($files, $dir . "/" . $file, $filesize, $userfile_extn);
}
}
}
}
closedir($dh);
return $files;
}
}

Simplest way:
$files = ListFiles('fonts/');
for ($i = 0; $i < count($files); $i += 3){
echo 'file_name = '.$files[$i].'file_size = '.$files[$i+1].'file_ext = '.$files[$i+2].'<br/>';
}
Better way:
http://pastie.org/4567820

Related

PHP/HTML form upload multiple images

I have this in my form:
<input type="file" name="images[]" multiple="multiple" />
then this PHP on the action page for the form:
$files = array();
$fdata = $_FILES["images"];
if(is_array($fdata["name"]))
{
//This is the problem
for ($i = 0; $i < count($fdata['name']); ++$i)
{
$files[] = array(
'name' => $fdata['name'][$i],
'tmp_name' => $fdata['tmp_name'][$i],
);
}
}
else
{
$files[] = $fdata;
}
foreach ($files as $file)
{
move_uploaded_file ( "$pic1_name","$image1") or die("image 1 did not copy<br>");
}
but i know i have the move_uploaded_file line wrong. what do i need to put in here instead?
UPDATE:
my latest code is as follows:
$files = array();
$fdata = $_FILES["images"];
if(is_array($fdata["name"]))
{
//This is the problem
for ($i = 0; $i < count($fdata['name']); ++$i)
{
$files[] = array(
'name' => $fdata['name'][$i],
'tmp_name' => $fdata['tmp_name'][$i],
);
}
}
else
{
$files[] = $fdata;
}
foreach($_FILES['images'] as $file)
{
echo $file['tmp_name'];
move_uploaded_file($file['tmp_name'], $_SERVER["DOCUMENT_ROOT"].'/img/project-gallery/test');
}
I would try something like this...of course add in some validation to make sure users are uploading only file-types which you expect
$currentDate = microtime();
$storeFolder = $_SERVER["DOCUMENT_ROOT"] . "/yourSavePath/";
$fileNames = array();
foreach ($_FILES['images']['name'] as $key => $value) {
if (!empty($_FILES['images'])) {
//tempfile is the file which has actually been stored on your server
$tempFile = $_FILES['images']['tmp_name'][$key];
//prepend the time so to make filenames unique...the filename here is the one the user sees and the temp filename above is one generated by the server
$targetFile1 = $currentDate . $_FILES['images']['name'][$key];
//get rid of spaces in the name since they can cause issues
$targetFile1 = str_replace(' ', '_', $targetFile1);
$res = move_uploaded_file($tempFile, $storeFolder . $targetFile1);
$fileNames[] = $targetFile1;
}
}

how to make this find specific extensions and show only the file name

1) how can i make this read only ".txt" files
2) how can i make it show only the file name so i can design it how i'd i like..
(<h1>$file</h1> for example)
$dir = "includes/news";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh)))
{
if ($filename != "." && $filename != ".." && strtolower(substr($filename, strrpos($filename, '.') + 1)) == 'txt')
{
$files[] = $filename;
}
}
sort($files);
echo $files;
what it shows right now is:
Array ( [0] => . [1] => .. [2] => [23.7] Hey.txt [3] => [24.7] New
Website.txt [4] => [25.7] Example.txt )
Now, this is another way i could do it, i like it bit better:
if( $handle = opendir( 'includes/news' ))
{
while( $file = readdir( $handle ))
{
if( strstr( $file, "txt" ) )
{
$addr = strtr($file, array('.txt' => ''));
echo '<h1>» ' . $addr . "</h1>";
}
}
closedir($handle);
}
but the my issue with this one is that there is no Sorting between the files.
everything is ok with the output, just the order of them. so if one of you can figure out how to sort them right, that would be perfect
Okay, try this:
$files = array();
if($handle = opendir( 'includes/news' )) {
while( $file = readdir( $handle )) {
if ($file != '.' && $file != '..') {
// let's check for txt extension
$extension = substr($file, -3);
// filename without '.txt'
$filename = substr($file, 0, -4);
if ($extension == 'txt')
$files[] = $file; // or $filename
}
}
closedir($handle);
}
sort($files);
foreach ($files as $file)
echo '<h1><a href="?module=news&read=' . $file
. '">» ' . $file . "</a></h1>";
I think this should accomplish what you want to do. It uses explode and a negative limit to find only .txt files and returns only the name.
$dir = "includes/news";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))){
$fileName = explode('.txt', $node, -1)[0];
if(count($fileName) )
$files[] = '<h1>'.$fileName.'</h1>';
}
try to make it as simple as possible
try this
function check_txt($file){
$array = explode(".","$file");
if(count($array)!=1 && $array[count($array)-1]=="txt"){return true;}
return false;
}
if($handle = opendir( 'includes/news' )) {
while( $file = readdir( $handle ))
{
if( check_txt($file) )
{
echo '<h1>» ' . $file . "</h1>";
}
}
closedir($handle);
}

PHP: sort folder first and then files

$dir = '/master/files';
$files = scandir($dir);
foreach($files as $file){
if(($file != '.') && ($file != '..')){
if(is_dir($dir.'/'.$file)){
echo '<li class="folder">'.$file.'</li>';
}else{
echo '<li class="file">'.$file.'</li>';
}
}
}
From the script above, I get result:
images (folder)
index.html
javascript (folder)
style.css
How to sort the folder first and then files?
Try this :
$dir = '/master/files';
$directories = array();
$files_list = array();
$files = scandir($dir);
foreach($files as $file){
if(($file != '.') && ($file != '..')){
if(is_dir($dir.'/'.$file)){
$directories[] = $file;
}else{
$files_list[] = $file;
}
}
}
foreach($directories as $directory){
echo '<li class="folder">'.$directory.'</li>';
}
foreach($files_list as $file_list){
echo '<li class="file">'.$file_list.'</li>';
}
You don't need to make 2 loops, you can do the job with this piece of code:
<?php
function scandirSorted($path) {
$sortedData = array();
foreach(scandir($path) as $file) {
// Skip the . and .. folder
if($file == '.' || $file == '..')
continue;
if(is_file($path . $file)) {
// Add entry at the end of the array
array_push($sortedData, '<li class="folder">' . $file . '</li>');
} else {
// Add entry at the begin of the array
array_unshift($sortedData, '<li class="file">' . $file . '</li>');
}
}
return $sortedData;
}
?>
This function will return the list of entries of your path, folders first, then files.
Modifying your code as little as possible:
$folder_list = "";
$file_list = "";
$dir = '/master/files';
$files = scandir($dir);
foreach($files as $file){
if(($file != '.') && ($file != '..')){
if(is_dir($dir.'/'.$file)){
$folder_list .= '<li class="folder">'.$file.'</li>';
}else{
$file_list .= '<li class="file">'.$file.'</li>';
}
}
}
print $folder_list;
print $file_list;
This only loops through everything once, rather than requiring multiple passes.
I have a solution for N deep recursive directory scan:
function scanRecursively($dir = "/") {
$scan = array_diff(scandir($dir), array('.', '..'));
$tree = array();
$queue = array();
foreach ( $scan as $item )
if ( is_file($item) ) $queue[] = $item;
else $tree[] = scanRecursively($dir . '/' . $item);
return array_merge($tree, $queue);
}
Store the output in 2 arrays, then iterate through the arrays to output them in the right order.
$dir = '/master/files';
$contents = scandir($dir);
// create blank arrays to store folders and files
$folders = $files = array();
foreach ($contents as $file) {
if (($file != '.') && ($file != '..')) {
if (is_dir($dir.'/'.$file)) {
// add to folders array
$folders[] = $file;
} else {
// add to files array
$files[] = $file;
}
}
}
// output folders
foreach ($folders as $folder) {
echo '<li class="folder">' . $folder . '</li>';
}
// output files
foreach ($files as $file) {
echo '<li class="file">' . $file . '</li>';
}
Being a CodeIgniter lover, I have in fact modified the core directory_helper from that to include the ability to have certain files exempt from the scanning in addition to setting the depth and choosing if hidden files should be included.
All credit goes to the original authors of CI. I simply added to it
with the exempt array and building in the sorting.
It uses ksort to order the folders, as the folder name is set as the key and natsort to order the files inside each folder.
The only thing you may need to do is define what the DIRECTORY_SEPARATOR is for your environment but I don't think you will need to modify much else.
function directory_map($source_dir, $directory_depth = 0, $hidden = FALSE, $exempt = array())
{
if ($fp = #opendir($source_dir))
{
$folddata = array();
$filedata = array();
$new_depth = $directory_depth - 1;
$source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
while (FALSE !== ($file = readdir($fp)))
{
// Remove '.', '..', and hidden files [optional]
if ($file === '.' OR $file === '..' OR ($hidden === FALSE && $file[0] === '.'))
{
continue;
}
is_dir($source_dir.$file) && $file .= DIRECTORY_SEPARATOR;
if (($directory_depth < 1 OR $new_depth > 0) && is_dir($source_dir.$file))
{
$folddata[$file] = directory_map($source_dir.$file, $new_depth, $hidden, $exempt);
}
elseif(empty($exempt) || !empty($exempt) && !in_array($file, $exempt))
{
$filedata[] = $file;
}
}
!empty($folddata) ? ksort($folddata) : false;
!empty($filedata) ? natsort($filedata) : false;
closedir($fp);
return array_merge($folddata, $filedata);
}
return FALSE;
}
Usage example would be:
$filelist = directory_map('full_server_path');
As mentioned above, it will set the folder name as the key for the child array, so you can expect something along the lines of the following:
Array(
[documents/] => Array(
[0] => 'document_a.pdf',
[1] => 'document_b.pdf'
),
[images/] => Array(
[tn/] = Array(
[0] => 'picture_a.jpg',
[1] => 'picture_b.jpg'
),
[0] => 'picture_a.jpg',
[1] => 'picture_b.jpg'
),
[0] => 'file_a.jpg',
[1] => 'file_b.jpg'
);
Just keep in mind that the exempt will be applied to all folders. This is handy if you want to skip out a index.html file or other file that is used in the directories you don't want included.
Try
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
chdir ($path);
$dir = array_diff (scandir ('.'), array ('.', '..', '.DS_Store', 'Thumbs.db'));
usort ($dir, create_function ('$a,$b', '
return is_dir ($a)
? (is_dir ($b) ? strnatcasecmp ($a, $b) : -1)
: (is_dir ($b) ? 1 : (
strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION)) == 0
? strnatcasecmp ($a, $b)
: strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION))
))
;
'));
header ('content-type: text/plain');
print_r ($dir);
?>
public function sortedScanDir($dir) {
// scan the current folder
$content = scandir($dir);
// create arrays
$folders = [];
$files = [];
// loop through
foreach ($content as $file) {
$fileName = $dir . '/' . $file;
if (is_dir($fileName)) {
$folders[] = $file;
} else {
$files[] = $file;
}
}
// combine
return array_merge($folders, $files);
}

Scandir Array display without file extensions

I'm using the following to create a list of my files in the 'html/' and link path.
When I view the array it shows, for example, my_file_name.php
How do I make it so the array only shows the filename and not the extension?
$path = array("./html/","./link/");
$path2= array("http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/html/","http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/link/");
$start="";
$Fnm = "./html.php";
$inF = fopen($Fnm,"w");
fwrite($inF,$start."\n");
$folder = opendir($path[0]);
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')) {
$folder2 = opendir($path[1]);
$imagename ='';
while( $file2 = readdir($folder2) ) {
if (substr($file2,0,strpos($file2,'.')) == substr($file,0,strpos($file,'.'))){
$imagename = $file2;
}
}
closedir($folder2);
$result="<li class=\"ui-state-default ui-corner-top ui-tabs-selected ui-state-active\">\n\n$file2\n<span class=\"glow\"><br></span>
</li>\n";
fwrite($inF,$result);
}
}
fwrite($inF,"");
closedir($folder);
fclose($inF);
pathinfo() is good, but I think in this case you can get away with strrpos(). I'm not sure what you're trying to do with $imagename, but I'll leave that to you. Here is what you can do with your code to compare just the base filenames:
// ...
$folder = opendir($path[0]);
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')) {
$folder2 = opendir($path[1]);
$imagename ='';
$fileBaseName = substr($file,0,strrpos($file,'.'));
while( $file2 = readdir($folder2) ) {
$file2BaseName = substr($file2,0,strrpos($file2,'.'));
if ($file2BaseName == $fileBaseName){
$imagename = $file2;
}
}
closedir($folder2);
$result="<li class=\"ui-state-default ui-corner-top ui-tabs-selected ui-state-active\">\n\n$file2\n<span class=\"glow\"><br></span>
</li>\n";
fwrite($inF,$result);
}
}
I hope that helps!

How to get X newest files from a directory in PHP?

The code below is part of a function for grabbing 5 image files from a given directory.
At the moment readdir returns the images 'in the order in which they are stored by the filesystem' as per the spec.
My question is, how can I modify it to get the latest 5 images? Either based on the last_modified date or the filename (which look like 0000009-16-5-2009.png, 0000012-17-5-2009.png, etc.).
if ( $handle = opendir($absolute_dir) )
{
$i = 0;
$image_array = array();
while ( count($image_array) < 5 && ( ($file = readdir($handle)) !== false) )
{
if ( $file != "." && $file != ".." && $file != ".svn" && $file != 'img' )
{
$image_array[$i]['url'] = $relative_dir . $file;
$image_array[$i]['last_modified'] = date ("F d Y H:i:s", filemtime($absolute_dir . '/' . $file));
}
$i++;
}
closedir($handle);
}
If you want to do this entirely in PHP, you must find all the files and their last modification times:
$images = array();
foreach (scandir($folder) as $node) {
$nodePath = $folder . DIRECTORY_SEPARATOR . $node;
if (is_dir($nodePath)) continue;
$images[$nodePath] = filemtime($nodePath);
}
arsort($images);
$newest = array_slice($images, 0, 5);
If you are really only interested in pictures you could use glob() instead of soulmerge's scandir:
$images = array();
foreach (glob("*.{png,jpg,jpeg}", GLOB_BRACE) as $filename) {
$images[$filename] = filemtime($filename);
}
arsort($images);
$newest = array_slice($images, 0, 5);
Or you can create function for the latest 5 files in specified folder.
private function getlatestfivefiles() {
$files = array();
foreach (glob("application/reports/*.*", GLOB_BRACE) as $filename) {
$files[$filename] = filemtime($filename);
}
arsort($files);
$newest = array_slice($files, 0, 5);
return $newest;
}
btw im using CI framework. cheers!

Categories