I am trying to create a mock up of a three-column Pinterest layout that scans a directory of images and puts 1/3 of the images in each of the columns.
But I can't figure out how to get the correct images to show up in the column.
It's not important that all the images are included, I just want the columns to be look moderately even.
Here's what I have so far, but obviously this just lists all the images in each of the columns.
<?php
$dir = 'img';
$files = scandir($dir);
$count = round((count($files)/3), 0);
?>
<div class="column">
<?php
foreach ($files as $file) { // 1/3 of the images
if ($file != "." && $file != "..") {
echo "<img src=\"img/" . $file . "\">" . "\n";
}
}
?>
</div>
<div class="column">
<?php
foreach ($files as $file) { // 1/3 of the images
if ($file != "." && $file != "..") {
echo "<img src=\"img/" . $file . "\">" . "\n";
}
}
?>
</div>
<div class="column">
<?php
foreach ($files as $file) { // 1/3 of the images
if ($file != "." && $file != "..") {
echo "<img src=\"img/" . $file . "\">" . "\n";
}
}
?>
</div>
Update:
Ultimately I used this
<?php
$dir = 'img';
$files = scandir($dir);
$count = round((count($files)/3), 0);
?>
<div class="column">
<?php
// 1/3 of the images
for ($i = 0; $i < floor(count($files) / 3); $i++) {
$file = $files[$i];
if ($file != "." && $file != "..") {
echo "<img src=\"img/" . $file . "\">" . "\n";
}
}
?>
</div>
<div class="column">
<?php
// 2/3 of the images
for ($i = floor(count($files) / 3); $i < floor(count($files) / 3) * 2; $i++) {
$file = $files[$i];
if ($file != "." && $file != "..") {
echo "<img src=\"img/" . $file . "\">" . "\n";
}
}
?>
</div>
<div class="column">
<?php
// 3/3 of the images
for ($i = floor(count($files) / 3) * 2; $i < count($files); $i++) {
$file = $files[$i];
if ($file != "." && $file != "..") {
echo "<img src=\"img/" . $file . "\">" . "\n";
}
}
?>
</div>
I would use for loops, like this:
// 1/3 of the images
for ($i = 0; $i < floor(count($files) / 3); $i++) {
$file = $files[$i];
// 2/3 of the images
for ($i = floor(count($files) / 3); $i < floor(count($files) / 3) * 2; $i++) {
$file = $files[$i];
// 3/3 of the images
for ($i = floor(count($files) / 3) * 2; $i < count($files); $i++) {
$file = $files[$i];
$num = 0;
$col = 0; // column number: 0, 1 or 2
foreach ($files as $file) { // 1/3 of the images
if ($file != "." && $file != "..") {
if ($num++ % 3 == $col) {
echo "<img src=\"img/" . $file . "\">" . "\n";
}
}
}
Related
id love a little help with the sort function here, im trying to figure it out but cant.
<?php
if ($handle = opendir('uploads')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".."){
sort ($file);
$thelist .= '<li>'.$file.'<img src="uploads/'.$file.$media.'" width="25" height="25"</li>';
}
}
closedir($handle);
}
?>
<ul><?php echo $thelist; ?></ul>
so this doesnt sort...
and the following will, but wont display some files.
im only interested in the sort function for the top code, i paid a guy to write the following half to try to understand the function sort
from what i can figure were suggesting the $file displays for a list then for a photo using the various $.. im stuck with whats stopping the $file from getting alphabeticaly arranged before being told what to display, (the best i got to was a list of the number ones displaying alphabetical (numerical yes) but its not sorting)
function showDir($dir, $i, $lar, $lon, $lin)
{
print("<style>.box { border-style: outset ; border-width: 1px ; border-color: #A3C5CC ; border-radius: 8px ; -moz-border-radius: 8px }</style>") ;
print("<script language='JavaScript'>
<!--
function MM_openBrWindow(theURL,winName,features) { //v2.0
window.open(theURL,winName,features);
}
//-->
</script>") ;
$i++;
if($checkDir = opendir($dir))
{
$cFile = 0;
while($file = readdir($checkDir))
{
if($file != "." && $file != "..")
{
if(!is_dir($dir . "/" . $file))
{
$listFile[$cFile] = $file;
$cFile++;
}
}
}
if(count(#$listFile) > 0)
{
print("<table cellspacing='1' cellpadding='0' border='0'><tr>") ;
sort($listFile);
$x = 0 ;
for($k = 0; $k < count($listFile); $k++)
{
$spacer = "";
for($l = 0; $l < $i; $l++)
$spacer .= " ";
if($x % $lin == 0)
print("</tr><tr>") ;
$img = $listFile[$k] ;
$tmp = explode(".", $img) ;
$x++ ;
if($tmp[1] == 'jpg' OR $tmp[1] == 'bmp' OR $tmp[1] == 'gif' OR $tmp[1] == 'png'
OR $tmp[1] == 'tga' OR $tmp[1] == 'tif' OR $tmp[1] == 'eps')
{
print("<td>") ;
print("<table class='box' bgcolor='#9ABBC1' cellspacing='0' cellpadding='0' border='0' width='" . ($lon+10) . "' height='" . ($lar+27) . "'><tr>") ;
print("<td align='center'><small><b>" . ($k+1) . "</b></small></td></tr><tr>") ;
print("<td align='center'>") ;
$srcimg = $dir . "/" . $spacer . $img ;
list($width, $height, $type, $attr) = getimagesize($srcimg);
print("<a href='#' onClick=\"MM_openBrWindow('display.php?img=$srcimg&lon=$width&lar=$height','','width=" . $width . ",height=" . $height . ",left=100,top=100,scrollbars=no,toolbars=no')\">") ;
print("<img src='" . $srcimg . "' width='" . $lar . "' height='" . $lon . "' alt='" . $img . "' title='" . $img . "' border='0'></a></td>");
print("</tr></table>\n") ;
print("</td>") ;
}
else
$x-- ;
}
print("</tr></table>\n") ;
print("<br><small>" . $k . " Images displayed<b></b></small>") ;
}
closedir($checkDir);
}
}
}
?>
You should use scandir function instead of readdir.
sorting_order By default, the sorted order is alphabetical in
ascending order. If the optional sorting_order is set to
SCANDIR_SORT_DESCENDING, then the sort order is alphabetical in
descending order. If it is set to SCANDIR_SORT_NONE then the result is
unsorted.
<?php
if ($handle = opendir('uploads')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".."){
$files[] = $file;
}
}
sort ($files);
$thelist = '';
foreach ($files as $file) {
$thelist .= '<li>'.$file.'<img src="uploads/'.$file.'" width="25" height="25"</li>';
}
closedir($handle);
}
?>
<ul><?php echo $thelist; ?></ul>
My code loops through a directory and displays all the files and folders where I have a index.php file that I don't want to be displayed.
<?php
$directory = 'jocuri';
$row = 0;
if ($handle = opendir($directory.'/'))
{
echo '<table border="1">';
while ($cat = readdir($handle))
{
if ($cat != '.' && $cat != '..')
{
if($row==0) echo '<tr>';
echo '<td align="center">';
echo ' <a href="'.$directory.'/'.$cat.'" style="text-decoration:none">';
echo ' <img src="'.$directory.'/'.$cat.'/image.php" style="display:block" />'.str_replace('_', ' ', $cat);
echo ' </a>';
echo '</td>';
if($row == 2)
{
echo '</tr>';
$row = -1;
}
$row++;
}
}
echo '</table>';
}
?>
How can i achieve that?
Staying quick and dirty:
if ($cat != '.'&&$cat != '..' && $cat != 'index.php'){ ... }
But I'll definitely move to some more consistent method like FilesystemIterator or glob().
while($cat = readdir($handle)) {
if (in_array($cat, array('.', '..', 'index.php')))
continue;
// display the file here
}
The following code counts the number of files inside a folder.
<?php
function folderlist(){
$directoryist = array();
$startdir = './';
//get all image files with a .jpg extension.
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
if (is_dir($startdir)){
if ($dh = opendir($startdir)){
while (($folder = readdir($dh)) !== false){
if (!(array_search($folder,$ignoredDirectory) > -1)){
if (filetype($startdir . $folder) == "dir"){
$directorylist[$startdir . $folder]['name'] = $folder;
$directorylist[$startdir . $folder]['path'] = $startdir;
}
}
}
closedir($dh);
}
}
return($directorylist);
}
$folders = folderlist();
$total_files = 0;
foreach ($folders as $folder){
$path = $folder['path'];
$name = $folder['name'];
$count = iterator_count(new DirectoryIterator($path . $name));
$total_files += $count;
echo '<li>';
echo '<a href="' .$path .'index.php?album=' .$name . '" class="style1">';
echo '<strong>' . $name . '</strong>';
echo ' (' . $count . ' files found)';
echo '</a>';
echo '</li>';
}
echo "Total Files:". $total_files;
?>
However for some reason the count is off by 2. I have a folder with 13 files but this code returns count as 15. For an empty folder, this returns a count of 2.
Can someone point to me the issue with the above snippet?
I'm doing it with DirectoryIterator
$files_in_directory = new DirectoryIterator($path_to_folder);
$c = 0;
foreach($files_in_directory as $file)
{
// We want only files
if($file->isDot()) continue;
if($file->isDir()) continue;
$c++;
}
var_dump($c);
For use as function :
function folderlist($directories = array(), $extensions = array())
{
if(empty($directories))
return false;
$result = array();
$total_count = 0;
foreach($directories as $directory)
{
$files_in_directory = new DirectoryIterator($directory);
$c = 0;
foreach($files_in_directory as $file)
{
// We want only files
if($file->isDot()) continue;
if($file->isDir()) continue;
// This is for php < 5.3.6
$file_extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION);
// If you have php >= 5.3.6 you can use following instead
// $file_extension = $fileinfo->getExtension()
if(in_array($file_extension, $extensions)){
$c++;
$result['directories'][$directory]['files'][$c]['name'] = $file->getFilename();
$result['directories'][$directory]['files'][$c]['path'] = $file->getPath();
$result['directories'][$directory]['count'] = $c;
}
}
$total_count += $c;
}
$result['total_count'] = $total_count;
return $result;
}
Displaying results based on GET superglobal:
if(isset($_GET['album']) && !empty($_GET['album']) && !isset($_GET['listfiles']))
{
// We are in directory view mode
$album = $_GET['album'];
// View all directories and their file count for specified album
$view_directory = folderlist(array($album), array('jpeg', 'jpg', 'log'));
// Loop the folders and display them with file count
foreach ($view_directory['directories'] as $folder_name => $folder_files){
$count = $folder_files['count'];
echo '<li>';
echo '<a href="files.php?album=' . $folder_name . '&listfiles=1" class="style1">';
echo '<strong>' . basename($folder_name) . '</strong>';
echo ' (' . $count . ' files found)';
echo '</a>';
echo '</li>';
}
echo "Total Files:". $get_dir_info['total_count'];
}
elseif(isset($_GET['album'], $_GET['listfiles']) && !empty($_GET['album']))
{
// We are in file view mode for folder
$album = $_GET['album'];
// View all files in directory
$view_files = folderlist(array($album), array('jpeg', 'jpg', 'log'));
echo 'Showing folder content of: <b>'.basename($album).'</b>';
foreach($view_files['directories'][$album]['files'] as $file)
{
$path = $file['path'];
$name = $file['name'];
echo '<li>';
echo '<a href="files.php?file=' . $name . '&path=' . $path . '" class="style1">';
echo '<strong>' . $name . '</strong>';
echo '</a>';
echo '</li>';
}
}
This line is still returning the '.' and '..' vars.
if (!(array_search($folder,$ignoredDirectory) > -1))
see: http://php.net/manual/en/language.types.boolean.php
Try
if (!array_search($folder,$ignoredDirectory))
EDIT:
Also change this:
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
to
$ignoredDirectory = array( '.', '..' );
I've adapted a simple paginated gallery to my needs, but it doesn't work as expected: usually it puts well the first "page" og pictures then in some cases it just skip some pictures and then go to further ones, in other cases it just do not load any other page (I'm using infinitescroll)
here is the php function:
function makeGallery($path, $directory, $seo){
$dir = $path . "/" . $directory;
$handle = opendir($dir);
while ($file = readdir($handle)){
if($file == '.' OR $file == '..' or $file == 'thumbs' or $file == '.DS_Store')
continue;
else
$result_array[]=$file;
}
$filecount = count(glob("" . $dir . "*.jpg"));
closedir($handle);
array_multisort($result_array, SORT_ASC);
$rows = 3;
$cols = 8;
if(isset($_GET['page'])){
$page = $_GET['page'];
}else{
$page = 0;
}
$num_pics = count($result_array);
$cells = $rows * $cols;
$pages = ceil($num_pics / $cells);
$num_pages = $pages - 1;
$output = array();
$slices = array();
$push = 0;
$showpage = $page + 1;
for($k=0;$k<$pages;$k++){
array_push($slices, $push);
$push = $push + $cells;
}
for($k=0;$k<$pages;$k++){
if($page == key($slices)){
$output = array_slice($result_array, current($slices), $cells);
}
next($slices);
}
reset($output);
print '<div class="container-fluid">
<div class="row">';
print "<ul id='photoswipe' class='thumbnails'>";
for($i=0;$i<$rows;$i++){
for($j=0;$j<$cols;$j++){
if(current($output) != false){
$value = current($output);
$parts = Explode('.', $value);
$title = $parts[count($parts) - 2];
$parts = Explode('-', $title);
$title = $parts[1];
if ($title == "") $title = $value;
print "<li class='box'><a title='$title' rel='group' class='thumbnails' href='$dir/$value'><img width='$width' height='inherrit' src='$dir/thumbs/$seo-$value' /></a></li>";
next($output);
}else{
print "</ul>";
}
}
}
$ref = $_SERVER['PHP_SELF'];
if($num_pages == '0'){
print " ";
print " ";
}elseif(($page == '0')||($page == '')){
$next = $page + 1;
print " ";
print "<a id='next' href='$ref?page=$next'> </a>";
}elseif($page == $num_pages){
$prev = $page - 1;
print "<a id='prev' href='$ref?page=$prev'> </a>";
print " ";
}else{
$next = $page + 1;
$prev = $page - 1;
print "<a id='prev' href='$ref?page=$prev'> </a>";
print "<a id='next' href='$ref?page=$next'> </a>";
}
echo "<nav id='page-nav'>
<a href='$ref?page=$next'></a>
</nav></div></div>";
}
I'm sure there should be some silly bug that i've not spotted and i hope that some experienced php programmer can find it very easily.
you could see the gallery (and its problem) on http://eikonabox.com/page/portrait.php
(in the portrait gallery as you can see it jumps from the number 24 directly to number 49)
Thank you all
If somone get stuck in this kind of problem I've resolved this way:
function makeGallery($path, $directory, $seo){
$dir = $path . "/" . $directory;
$filearray = array();
if ($fil = opendir($dir)) {
while (($file = readdir($fil)) !== false) {
if ($file != "." && $file != ".." && $file != "thumbs" && $file != ".DS_Store") {
$filearray[] = $file;
$page = empty($_GET['page']) ? 1 : $_GET['page'];
$num_per_page = 25;
$total_pages = ceil(count($filearray)/$num_per_page);
}
}
array_multisort($filearray, SORT_ASC);
print '<div class="container-fluid">
<div class="row">';
print "<ul id='photoswipe' class='thumbnails'>";
for($i = ($page - 1) * $num_per_page; $i < $page * $num_per_page; $i++){
$value = basename($filearray[$i]);
$parts = Explode('.', $value);
$title = $parts[count($parts) - 2];
$parts = Explode('-', $title);
$title = $parts[1];
if ($title == "") $title = $value;
if($value != "")
print "<li class='box'><a title='$title' rel='group' class='thumbnails' href='$dir/$value'><img width='$width' height='inherrit' src='$dir/thumbs/$seo-$value' /></a></li>";
}
closedir($fil);
}
print "</ul>";
$ref = $_SERVER['PHP_SELF'];
if($num_pages == '0'){
print " ";
print " ";
}elseif(($page == '0')||($page == '')){
$next = $page + 1;
print " ";
print "<a id='next' href='$ref?page=$next'> </a>";
}elseif($page == $num_pages){
$prev = $page - 1;
print "<a id='prev' href='$ref?page=$prev'> </a>";
print " ";
}else{
$next = $page + 1;
$prev = $page - 1;
print "<a id='prev' href='$ref?page=$prev'> </a>";
print "<a id='next' href='$ref?page=$next'> </a>";
}
echo "<nav id='page-nav'>
<a href='$ref?page=$next'></a>
</nav></div></div>";
}
I'm using the code here - How can I find unused functions in a PHP project (reproduced below) exactly as it is - just the path modified to my location and it behaves as follows:
root#server [/var/www]# php see_unused_code.php
T_STRING
The code used is:
<?php
$functions = array();
$path = "/path/to/my/php/project";
define_dir($path, $functions);
reference_dir($path, $functions);
echo
"<table>" .
"<tr>" .
"<th>Name</th>" .
"<th>Defined</th>" .
"<th>Referenced</th>" .
"</tr>";
foreach ($functions as $name => $value) {
echo
"<tr>" .
"<td>" . htmlentities($name) . "</td>" .
"<td>" . (isset($value[0]) ? count($value[0]) : "-") . "</td>" .
"<td>" . (isset($value[1]) ? count($value[1]) : "-") . "</td>" .
"</tr>";
}
echo "</table>";
function define_dir($path, &$functions) {
if ($dir = opendir($path)) {
while (($file = readdir($dir)) !== false) {
if (substr($file, 0, 1) == ".") continue;
if (is_dir($path . "/" . $file)) {
define_dir($path . "/" . $file, $functions);
} else {
if (substr($file, - 4, 4) != ".php") continue;
define_file($path . "/" . $file, $functions);
}
}
}
}
function define_file($path, &$functions) {
$tokens = token_get_all(file_get_contents($path));
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
if (is_array($token)) {
if ($token[0] != T_FUNCTION) continue;
$i++;
$token = $tokens[$i];
if ($token[0] != T_WHITESPACE) die("T_WHITESPACE");
$i++;
$token = $tokens[$i];
if ($token[0] != T_STRING) die("T_STRING");
$functions[$token[1]][0][] = array($path, $token[2]);
}
}
}
function reference_dir($path, &$functions) {
if ($dir = opendir($path)) {
while (($file = readdir($dir)) !== false) {
if (substr($file, 0, 1) == ".") continue;
if (is_dir($path . "/" . $file)) {
reference_dir($path . "/" . $file, $functions);
} else {
if (substr($file, - 4, 4) != ".php") continue;
reference_file($path . "/" . $file, $functions);
}
}
}
}
function reference_file($path, &$functions) {
$tokens = token_get_all(file_get_contents($path));
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
if (is_array($token)) {
if ($token[0] != T_STRING) continue;
if ($tokens[$i + 1] != "(") continue;
$functions[$token[1]][1][] = array($path, $token[2]);
}
}
}
?>
PHP version is:
PHP 5.3.3 (cli) (built: Aug 7 2010 14:49:50)
You should look at the source code, read it, understand it. Not just coopy-paste-run. Look at the define_file() function definition: if ($token[0] != T_STRING) die("T_STRING");
You can debug it by displaying the file-path where that condition occurs.
if ($token[0] != T_STRING) die("T_STRING: " . $path . " : " . $token[0]);
Then you'll know what the real problem is.