PHP List Images In Folder - php

I have the following code
// Define the full path to your folder from root
$path = "../galleries/".$album;
// Open the folder
$dir_handle = #opendir($path) or die("Unable to open $path");
// Loop through the files
while ($file = readdir($dir_handle)) {
if(strlen($file)>1){echo "<a href='http://minification.com/?page_id=32&dir=$album&img=$file'><img src='http://minification.com/galleries/$album/$file'></a>";}
}
// Close
closedir($dir_handle);
What i want to do is pull in all the images from a folder and display them using PHP. So far its working up to the point where it only displays one image out of the folder. Anyone know how to fix this?

Your second file probably evaulates to false, see readdir(), you should do:
while (false !== ($file = readdir($dir_handle))) {

Hint: If this is PHP 5, you can reduce the hassle a bit by using scandir instead.

try this:
while(false !== ($file = readdir($handle))) {
A lot of different values evaluate to false in php so you may be getting a false positive.

Related

Use opendir one time instead of using it in for loop

I have below code to get content from remote directory.
$dirHandle = opendir("ssh2.sftp://$sftp/".PATH_OUT);
while (false !== ($file = readdir($dirHandle))) {
// something...
}
Now, the thing is, above code is in forloop. when I put $dirHandle = opendir("ssh2.sftp://$sftp/".PNB_PATH_OUT); outside of forloop then it gives me required result only for first record. So, obviously it's readdir is not working for second record in forloop.
How can I do this in such a way that I need to use opendir only once and use that connection more than 1 time?
Required Solution
$dirHandle = opendir("ssh2.sftp://$sftp/".PATH_OUT);
for(...){
while (false !== ($file = readdir($dirHandle))) {
// something...
}
}
Your while loop is traversing the entire directory until there are no more files, in which case readdir returns false. Therefore any time readdir is called after the first traversal, it will just return false because it is already at the end of the directory.
You could use rewinddir() in the for loop to reset the pointer of the directory handle to the beginning.
$dirHandle = opendir("ssh2.sftp://$sftp/".PATH_OUT);
for(...){
rewinddir($dirHandle);
while (false !== ($file = readdir($dirHandle))) {
// something...
}
}
Since the sftp stream appears to not support seeking, you should just store the results you need and do the for loop after the while loop. You are, after all, traversing the same directory multiple times.
$dirHandle = opendir("ssh2.sftp://$sftp/".PATH_OUT);
while (false !== ($file = readdir($dirHandle))) {
$files[] = $file;
}
for(...){
// use $files array
}

get image files from directory on server for further processing

I have folders on the server that contain image files. I'm trying to get those files and then upload them further, but I think I'm using the wrong function.
My code:
$dir = "../uploads/".$folderimage."/";
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
$handle = fopen($entry,"wb");
$mug->images_upload(array( "AlbumID" => "#####", "File" => $handle));
}
}
closedir($handle);
}
Not sure what I am doing, all I need to do is pass the file to the class function $mug->images->upload. It works from a $_POST request but I need to move the files already uploaded to the folder.
It's a bit tricky to emulate a file upload POST request for your $mug object. You would be better off if you could refactor the code in $mug as follows:
$mug fetches the uploaded file and puts it to its destination place.
You create a new function that implements the processing you wish to use here and in $mug.
Call this function from here, and from $mug with the appropriate filename.
If $mug->images_upload is expecting the file path then pass $dir.$entry to it
<?php
$dir = "../uploads/".$folderimage."/";
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo $entry.PHP_EOL;
$mug->images_upload(array( "AlbumID"=>"#####", "File"=>$dir.$entry));
}
}
closedir($handle);
}
//Or simpler way but slightly slower
foreach (glob($dir."*.{png,jpg,gif}", GLOB_BRACE) as $file) {
echo $file.PHP_EOL;
$mug->images_upload(array( "AlbumID"=>"#####", "File" =>$dir.$file));
}
?>
There are a number of apparent issues with the code that you have posted.
$dir = "../uploads/".$folderimage."/";
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
$handle = fopen($entry,"wb");
$mug->images_upload(array( "AlbumID" => "#####", "File" => $handle));
}
}
closedir($handle);
}
Clashing variables.
You have used the $handle vairable to store the directory handle, only to later overwrite it with a file resource inside the loop. As soon as you overwrite it inside the loop, the next call to readdir($handle) does not make any sense are you are calling the function on a file resource. This could very easily lead to an infinite loop since when readdir() is given rubbish, it might return NULL.
Incorrect path for fopen()
Given $folderimage = "images" and $entry = "photo.jpg", then the fopen() line will try to open the image at photo.jpg rather than ../uploads/images/photo.jpg. You likely wanted to use something like $dir . $entry, but read on as you shouldn't be using fopen() at all.
Incorrect usage of the phpSmug library
The File argument must be a string containing "the path to the local file that is being uploaded" (source). You instead try to pass a file resource from fopen() to it.
opendir()/readdir() for directory iteration is ancient
There are better ways to traverse directory contents in PHP. As mentioned in Lawrence's answer, glob() might be useful.
I would also advocate using the filesystem iterator from the SPL.
$dir = "../uploads/$folderimage/";
foreach (new FilesystemIterator($dir) as $fileinfo) {
$image_pathname = $fileinfo->getPathname();
$mug->images_upload("AlbumID=#####", "File=$image_pathname");
}

PHP Zend Framework S3 - PutFile not putting

I'm simply trying to loop through a folder of images and put them in an Amazon S3 bucket. I just can't figure out why it doesn't like the DATA part of the PUTFILE function.
If I try:
$res = $s3 -> putFile("test-bucket/".$entry);
It creates a blank file (0 bytes) in the bucket, so I know it's connecting OK, and the filenames are correct also. I've also tried looping through the folders files and echoing the filenames to the screen, without using the Zend S3 function, which proved this page can access the files behind root.
The documentation regarding this function says:
putFile($path, $object, $meta) puts the content of the file in $path
into the object named $object.
The optional $meta argument is the same as for putObject. If the
content type is omitted, it will be guessed basing on the source file
name.
This is what I've tried:
if ($handle = opendir('d:/web-library-photos/temp-previews')) {
$loopCounter = 0;
while (false !== ($entry = readdir($handle))) {
///
$loopCounter = $loopCounter + 1;
if ($loopCounter < 3) { // for test purposes only
$localPath = "d:/web-library-photos/temp-previews/".$entry;
$s3 = new Zend_Service_Amazon_S3($aws_access_key_id, $aws_s3_secret);
$res = $s3 -> putFile($localPath, "test-bucket/".$entry);
echo "Success for ".$entry.": " . ($res ? 'Yes' : 'No') . "<br>";
}
///
}
closedir($handle);
}
This particular "try" yields the error:
Cannot read file d:/web-library-photos/temp-previews/.' in C:\Inetpub\vhosts\.....thispage.php
So I thought I would try file_get_contents() and readfile() but still no luck!
Please, please, put me straight on this one - it's driving me round the bend.
UPDATE
Right, I have a clue what's wrong but not how to solve it.
If I simply do this:
if ($handle = opendir('d:/web-library-photos/temp-previews')) {
while (false !== ($entry = readdir($handle))) {
echo $entry."<BR>";
}
closedir($handle);
}
I get a . and a .. at the beginning of my results, which obviously can't be read as filenames!! What is going on here, how do I get around it?
Try to append this in while (false !== ($entry = readdir($handle)))
while (false !== ($entry = readdir($handle))) {
if($entry == "." || $entry == "..") continue;
/* other codes */
}

get all file names from a directory in php

(Well what I gone through a lot of posts here on stackoverflow and other sites. I need a simple task, )
I want to provide my user facility to click on upload file from his account, then select a directory and get the list of all the files names inside that directory.
According to the posts here what I got is I have to pre-define the directory name, which I want to avoid.
Is there a simple way to click a directory and get all the files names in an array in PHP? many thanks in advance!
$dir = isset($_POST['uploadFile']) ? _SERVER['DOCUMENT_ROOT'].'/'.$_POST['uploadFile'] : null;
if ($_POST['uploadFile'] == true)
{
foreach (glob($dir."/*.mp3") as $filename) {
echo $filename;
}
}
I will go ahead and post a sample of code I am currently using, with a few changes, although I would normally tell you to look it up on google and try it first.
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo $file;
}
closedir($handle);
}
This will display the entire contents of a directory... including: ".", "..", any sub-directories, and any hidden files. I am sure you can figure out a way to hide those if it is not desirable.
<?php
$files=glob("somefolder/*.*");
print_r($files);
?>
Take a look at the Directory class (here) and readdir()
I'm confused what do you want, all files or only some files?
But if you want array of folders and files, do this
$folders = array();
$files = array();
$dir = opendir("path");
for($i=0;false !== ($file = readdir($dir));$i++){
if($file != "." and $file != ".."){
if(is_file($file)
$files[] = $file;
else
$folders[] = $file;
}
}
And if only some folders you want, later you can delete them from array
I always use this amazing code to get file lists:
$THE_PATTERN=$_SERVER["DOCUMENT_ROOT"]."/foldername/*.jpg";
$TheFilesList = #glob($THE_PATTERN);
$TheFilesTotal = #count($TheFilesList);
$TheFilesTotal = $TheFilesTotal - 1;
$TheFileTemp = "";
for ($TheFilex=0; $TheFilex<=$TheFilesTotal; $TheFilex++)
{
$TheFileTemp = $TheFilesList[$TheFilex];
echo $TheFileTemp . "<br>"; // here you can get full address of files (one by one)
}

copy file from one folder to other

I want to move all files from one folder to other. my code is as following. in this I made a folder in which i want to copy all file from templats folder
$doit = str_replace(" ", "", $slt['user_compeny_name']);
mkdir("$doit");
$source = "templat/";
$target = $doit . "/";
$dir = opendir($source);
while (($file = readdir($dir)) !== false) {
copy($source . $file, $target . $file);
}
It working fine . copy all files but give warning that The first argument to copy() function cannot be a directory
can any one help me asap
Readdir will read all children in a directory, including other dirs, and 'virtual' dirs like . and .. (link to root and parent dir, resp.) You'll have to check for these and prevent the copy() function for these instances.
while (($file = readdir($dir)) !== false)
{
if(!is_dir($file))
{
copy($source.$file, $target.$file);
}
}
You are not accounting for the . and the .. files at the top of the directory. This means that the first thing it tries to copy is "\template." which would be the same as trying to copy the directory.
Just add something like:
if ($file !== "." && $file !== "..")
...
opendir() will include items . and .. as per the documentation.
You will need to exclude these by using the code in the other comments.
if ($file != "." && $file != "..") {
// copy
}
I know, this question is pretty old, but also are the answers. I feel the need to show some new methods, which can be used to execute the requested task.
In the mean time Objects were introduced with a lot more features and possibilities. Needless to say, the other answers will still work aswell.
But here we go, using the DirectoryIterator:
$szSrcFolder = 'source_folder';
$szTgtFolder = 'target_folder';
foreach (new DirectoryIterator($szSrcFolder) as $oInfo)
if ($oInfo->isFile())
copy($oInfo->getPathname(), $szTgtFolder . DIRECTORY_SEPARATOR . $oInfo->getBasename());
Remember, within this script, all paths are relative to the working directory of the script itself.
I think it is self explaining, but we will take a look. This few lines will iterate over the whole content of the source folder and check if it is a file and will copy it to the target folder, keeping the original file name.

Categories