opening two folders and displaying images php - php

I've got the problem of trying to display two albums of photos from a db using php. Currently the following code works but for just one album. Basically I need it to display photos from 'mount-everest-part-2' aswell.
<?php
$path = "images/galleries/";
$album = 'mount-everest-part-1';
if ($handle = opendir($path.$album.'/thumbs/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && substr($file, 0, 2) != '._') {
$files[] = $file;
}
}
closedir($handle);
}
asort($files);
foreach($files as $file) {
echo '<li><img src="../' . $path . $album . '/thumbs/' . $file . '" /></li>';
}
?>
How can I use this code to open two files and spit the files out using the same foreach loop?

This sounds like one of those things that OOP would suit nicely. Here's an example:
<?php
class Album_Picture_File {
private $fileName;
private $path;
private $album;
public function __construct($fileName, $path, $album) {
$this->fileName = $fileName;
$this->path = $path;
$this->album = $album;
}
private function getAlbumPath() {
return '../' . $this->path . $this->album;
}
public function getPicturePath() {
return $this->getAlbumPath() . '/images/' . $this->fileName;
}
public function getThumbnailPath() {
return $this->getAlbumPath() . '/thumbs/' . $this->fileName;
}
}
function fetchFiles($path, $album) {
$files = array();
if ($handle = opendir($path.$album.'/thumbs/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && substr($file, 0, 2) != '._') {
$fullPath = $path . $album . '/thumbs/' . $file;
$files[$fullPath] = new Album_Picture_File($file, $path, $album);
}
}
closedir($handle);
}
ksort($files); //sort after key (out file path)
return $files;
}
$files = array_merge(
fetchFiles('images/galleries/', 'mount-everest-part-1'),
fetchFiles('images/galleries/', 'mount-everest-part-2')
);
foreach($files as $file) {
echo '<li><img src="' . $file->getThumbnailPath() . '" /></li>';
}
?>
Note that instead of pushing $files with strings, we push it with Album_Picture_File objects.

Create a global array :
$all = array();
Then, make 2 loops and push the global array (create a function that reads the directory for example)
$files_dir_one = getFiles("your_dir");
$files_dir_two = getFiles("your_dir2");
$all = array_merge($files_dir_one, $files_dir_two);
function getFiles($directory) {
$files = array();
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && substr($file, 0, 2) != '._') {
$files[] = $file;
}
}
closedir($handle);
}
//asort($files);
return $files;
}
And then, the last step : populate the view

How can I use this code to open two files and spit the files out using the same foreach loop?
Taking your question literally it works like this. First of all extract a function with the two input variables:
/**
* #param string $path
* #param string $album
*/
function list_images($path, $album) {
$files = [];
if ($handle = opendir($path . $album . '/thumbs/'))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && substr($file, 0, 2) != '._')
{
$files[] = $file;
}
}
closedir($handle);
}
asort($files);
foreach ($files as $file)
{
echo '<li><img src="../' . $path . $album . '/thumbs/' . $file . '" /></li>';
}
}
Then you can just iterate over your two albums and output both:
$path = "images/galleries/";
$albums = ['mount-everest-part-1', 'mount-everest-part-2'];
foreach ($albums as $album)
{
list_images($path, $album);
}

Related

Creating default object from empty value in OT Scroller

I have problem with warning on my Joomla website. More precisely "Warning: Creating default object from empty value in /public_html/modules/mod_ot_scroller/helper.php on line 40"
Here is whole helper.php file:
<?php
defined('_JEXEC') or die;
class modOTScrollerHelper
{
function getImages(&$params, $folder, $type)
{
$files = array();
$images = array();
$dir = JPATH_BASE.DS.$folder;
// check if directory exists
if (is_dir($dir))
{
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && $file != 'CVS' && $file != 'index.html' && $file != 'Thumbs.db') {
$files[] = $file;
}
}
}
closedir($handle);
foreach($type as $tp){
$tp=trim($tp);
$i = 0;
foreach ($files as $img){
if (!is_dir($dir .DS. $img))
{
if (preg_match("#$tp#i", $img)) {
$images[$i]->name = $img;
$images[$i]->folder = $folder;
++$i;
}
}
}
}
}
return $images;
}
function getFolder(&$params)
{
$folder = $params->get( 'folder' );
$LiveSite = JURI::base();
// if folder includes livesite info, remove
if ( JString::strpos($folder, $LiveSite) === 0 ) {
$folder = str_replace( $LiveSite, '', $folder );
}
// if folder includes absolute path, remove
if ( JString::strpos($folder, JPATH_SITE) === 0 ) {
$folder= str_replace( JPATH_BASE, '', $folder );
}
$folder = str_replace('\\',DS,$folder);
$folder = str_replace('/',DS,$folder);
return $folder;
}
}
?>
Whole website works fine and images shown properly.
What can I do to get rid of it?
Yeah, thats a warning, because you did not specify what $images[$i] should be. If you want to, initialize it using $images[$i] = new \stdClass();

PHP - Remove '.' and '..' from values fetched from directory files

I am using this code in order to get a list files from directory:
$dir = '/restosnapp_cms/images/';
if ($dp = opendir($_SERVER['DOCUMENT_ROOT'] . $dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
} else {
exit('Directory not opened.');
}
I want to get rid of the values '.' and '..'.
Is it possible to do this? Thank you. :)
Just check for them first:
while ($file = readdir($p)) {
if ($file == '.' || $file == '..') {
continue;
}
// rest of your code
}
DirectoryIterator is much more fun than *dir functions:
$dir = new DirectoryIterator($_SERVER['DOCUMENT_ROOT'] . $dir);
foreach($dir as $file) {
if (!$file->isDir() && !$file->isDot()) {
$files[] = $file->getPathname();
}
}
But the bottomline is regardless of which way you do it, you need to use a conditional.

list directory in PHP hide extension

I have been searching for a way to hide an extension which appears from the directory list. I am showing these directory in a website menu but I would like all files to appear with their extension next to the file name. For example file.pdf and file.png.
I need to hide the extension from these files to appear as ( file , file , img , etc..).
php code:
<?php
$path = "./outgoing/";
function createDir($path = '.')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file) && $file != '.' && $file !='..')
printSubDir($file, $path, $queue);
else if ($file != '.' && $file !='..')
$queue[] = $file;
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path)
{
foreach ($queue as $file)
{
printFile($file, $path);
}
}
function printFile($file, $path)
{
echo "<li>$file</li>";
}
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/",".pdf");
echo "</li>";
}
createDir($path);
?>
Use something like this to remove ext
$temp = explode(".", $file);
$par = $temp[0];

php function to read subdir content

I would like to ask what I have to add to make this function to show not only the files on top dir but also the files in subdirs..
private function _populateFileList()
{
$dir_handle = opendir($this->_files_dir);
if (! $dir_handle)
{
return false;
}
while (($file = readdir($dir_handle)) !== false)
{
if (in_array($file, $this->_hidden_files))
{
continue;
}
if (filetype($this->_files_dir . '/' . $file) == 'file')
{
$this->_file_list[] = $file;
}
}
closedir($dir_handle);
return true;
}
Thank you in advance!
You could implement the recursion yourself, or you could use the existing iterator classes to handle the recursion and filesystem traversal for you:
$dirIterator = new RecursiveDirectoryIterator('.', FilesystemIterator::SKIP_DOTS);
$recursiveIterator = new RecursiveIteratorIterator($dirIterator);
$filterIterator = new CallbackFilterIterator($recursiveIterator, function ($file) {
// adjust as needed
static $badFiles = ['foo', 'bar', 'baz'];
return !in_array($file, $badFiles);
});
$files = iterator_to_array($filterIterator);
var_dump($files);
By this you can get all subdir content
customerdel('FolderPath');
function customerdel($dirname=null){
if($dirname!=null){
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
echo $dirname."/".$file.'<br>';
else{
echo $dirname.'/'.$file.'<br> ';
customerdel($dirname.'/'.$file);
}
}
}
closedir($dir_handle);
}
}
Here is how you can get a recursive array of all files in a directory and its subdirectories.
The returned array is like: array( [fileName] => [filePath] )
EDIT: I've included a small check if there are filenames in the subdirectories with the same name. If so, an underscore and counter is added to the key-name in the returned array:
array( [fileName]_[COUNTER] => [filePath] )
private function getFileList($directory) {
$fileList = array();
$handle = opendir($directory);
if ($handle) {
while ($entry = readdir($handle)) {
if ($entry !== '.' and $entry !== '..') {
if (is_dir($directory . $entry)) {
$fileList = array_merge($fileList, $this->getFileList($directory . $entry . '/'));
} else {
$i = 0;
$_entry = $entry;
// Check if filename is allready in use
while (array_key_exists($_entry, $fileList)) {
$i++;
$_entry = $entry . "_$i";
}
$fileList[$_entry] = $directory . $entry;
}
}
}
closedir($handle);
}
return $fileList;
}

Readdir images from subdirectories and SORT alphabetically?

i found this code (https://stackoverflow.com/a/9628457/1510766) for show all images from directories and sub-directories, and works fine, but im trying to implement the sort() function of php but doesnt work:
function ListFiles($dir) {
if($dh = opendir($dir)) {
$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 {
array_push($files, $dir . "/" . $file);
}
}
}
closedir($dh);
// -- SORTING the FILES --
sort($files);
return $files;
}
}
foreach (ListFiles('works/'.$service_get_var.'/') as $key=>$file){
echo "<li><img src=\"$file\"/></li>";
}
When I test this, I cant see any images, is the correct use for sort()?. Thank you very much.
Sort after read all, not in recursive steps
function ListFiles($dir) {
if($dh = opendir($dir)) {
$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 {
array_push($files, $dir . "/" . $file);
}
}
}
closedir($dh);
// -- SORTING the FILES --
//sort($files);
return $files;
}
}
$list = ListFiles('works/'.$service_get_var.'/');
sort($list);
foreach ($list as $key=>$file){
echo "<li><img src=\"$file\"/></li>";
}

Categories