Foreach loop stop after text is displayed - php

I'm generating and showing pictures in a picture of a day sort of script. I have a gallery page for that picture of the day (that pulls from a directory). So I want to pull all the files from the directory and when it hits the current date (which is also the same as the file name IE. 20120822.jpg is what's displaying today and 20120823.jpg is what will display tomorrow). I have it looping all of the directory images and displaying them in a gallery, but I want the loop to stop after the current date so we don't show or load the future images. Here is my code.. I'm sure I'm just doing something silly..
<?PHP
// filetypes to display
$imagetypes = array("image/jpeg", "image/gif");
?>
<?PHP
function getImages($dir)
{
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getImages: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
break;
}
}
}
$d->close();
return $retval;
}
?>
<?PHP
// fetch image details
$images = getImages("galleries/photo-of-the-day/images");
$today = date("Ymd") . ".jpg";
// display on page
sort($images, SORT_REGULAR);
foreach($images as $img ) {
if ($img == "20120822.jpg" ) {
break;
} else {
?>
<div style="margin-right: 10px; float: left; margin-bottom: 10px; padding-bottom: 10px; border: 1px #CCCCCC solid;">
<a href="<? echo $img['file']; ?>" rel="prettyPhoto" title="">
<img class="image-gals" src="<? echo $img['file']; ?>" style="width: 260px; margin-bottom: 0px;padding: 10px; " /></a>
Download
</div>
<?
}
}
?>

This is where you're populating your $images array:
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
But when you compare them, you're doing this:
foreach($images as $img ) {
if ($img == "20120822.jpg" ) {
$img will contain an array. You'll need to check $img['file'], and that also has the directory name in, so it won't match just the image name.

Related

which one is better for checking images? php or js

I need to check images of contents on website.
I wrote code use php that doesn't have a problem, but I found some different ways on internet(Click to see example!)
from your opinion which is more efficient?
My website template seems like this: https://imgur.com/XOdDEZu
below is my php code :
$random_img = rand(1,9); // I have saved images to folder img_1, img_2 ...
$fixed_image = "<img src='public/img/duz/img_".$random_img.".jpg' style='width: 100%; height:320px; filter: blur(.1rem);' border:2px solid red;>";
$uploaded_img_file = "public/upload/$value->content_img";
$img_url = $value->content_img;
$find_letters = array('jpg', 'jpeg', 'png','gif','svg');
$match = (str_replace($find_letters, '', substr($img_url,-4)) != substr($img_url,-4));
//true if the last 4 characters of img url match the 4 characters in the array; returns false if it does not match
if (empty($value->content_img)) {
echo $fixed_img;
echo $a;
}elseif (file_exists($uploaded_img_file)) {
echo "<img src='".$uploaded_img_file."'>";
//print_r($uploaded_img_file);
}elseif (strlen($img_url)>=3) { //If the string length of the data from the database exceeds 3 characters. (no image if less than three characters)
if (filter_var($img_url, FILTER_VALIDATE_URL) !== false && $match==true) { //url validation check
echo "<img src='".$img_url."'>";
}else{
echo $fixed_img;
$String_title = $value->content_title;
$title_limit = limit_text($String_baslik, 10);
echo $a;
}
//print_r($img_url);
}else{
echo $fixed_img;
echo '<div style="position:absolute; left:15px; bottom:5px; text-decoration: none;"><span>Merhaba</span></div>';
}

Script that gets images wont show new images past 7 without a limit

I got a script that gets images from a folder and puts them inside a lightgallery. All is working fine, except when I add more than 7 images (or any new images for that matter). There are 7 images in the folder when I add 8.jpg it shows nothing, not in the gallery and not in the source code. What could be the cause of this?
My script:
<div id="lightgallery">
<a href="<? echo $imagesmall; ?>">
<img class="fullnieuwsimg" src="<? echo $imagesmall; ?>">
</a>
<?
function scan_dir($dir) {
$ignored = array('.', '..', '.svn', '.htaccess','index.html');
$files = array();
foreach (scandir($dir) as $file) {
if (in_array($file, $ignored)) continue;
$files[$file] = filemtime($dir . '/' . $file);
}
ksort($files,SORT_NATURAL);
$files = array_keys($files);
return ($files) ? $files : false;
}
if(is_dir($_SERVER['DOCUMENT_ROOT'].'/_intern/web/cms/images/Projecten/'.$contentcr[0]['alias'].'/') != FALSE){
foreach(scan_dir($_SERVER['DOCUMENT_ROOT'].'/_intern/web/cms/images/Projecten/'.$contentcr[0]['alias'].'/') as $entry) {
$gallery .= '
<a href="/_intern/SNM/cms/images/Projecten/'.$contentcr[0]['alias'].'/'.$entry.'">
<img class="galleryimgs" title="'.$contentcr[0]['alias'].'" alt="'.$contentcr[0]['alias'].'" src="/_intern/web/cms/images/Projecten/'.$contentcr[0]['alias'].'/'.$entry.'" />
</a>';
}
}else{
echo '';
}
echo $gallery;
?>
</div>
The pictures are in the folder like this (barebone joomla cms) :
All work, except 8.jpg or any other new images I add.

get the latest excel file and convert into html using php excel reader

Can you help me with this? i don't know what to put or what to start to solve this.
i have an excel reader which is working fine, converting my excel into html and i have a code that detect the latest file in the directory
my problem is, what code should i put to display or get the latest excel file in the directory using php excel reader
here's the code that i have. Please help me
<?php
class ReportViewer
{
public $extension = array ( 'xlsx', 'xls', 'html', 'htm', 'csv' );
public function getLatestReport($report)
{
$reports_directory = preg_split("/[\-]/", $report);
//$latest_files = array();
if (!ctype_alpha($report))
$directory = $reports_directory[0].'/'.$reports_directory[1];
else
$directory = $reports_directory[0];
$dir_contents = new RecursiveDirectoryIterator($directory);
foreach (new RecursiveIteratorIterator($dir_contents) as $filename => $file)
{
if (preg_match("/\.(" . implode("|", $this->extension) . ")*$/i", $file->getFileName()/*, $filename*/))
{
$latest_files[$file->getMTime()] = array($directory, $file->getFileName(), $file->getPath());
//echo $file->getFileName() . "\n";
}
}
krsort($latest_files);
//print_r($latest_files);
// print_r($timeMod);
return $latest_files;
}
}
?>
<html>
<head>
<style type="text/css">
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 0 0.5em;
}
</style>
</head>
<body>
<?php
include 'reader.php';
$excel = new Spreadsheet_Excel_Reader();
$lastest = new ReportViewer();
?>
Sheet 1:<br/><br/>
<table>
<?php
$excel->read('battery-report.xls');
$x=1;
while($x<=$excel->sheets[0]['numRows']) {
echo "\t<tr>\n";
$y=1;
while($y<=$excel->sheets[0]['numCols']) {
$cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
echo "\t\t<td>$cell</td>\n";
$y++;
}
echo "\t</tr>\n";
$x++;
}
?>
</table><br/>
</body>
</html>
you are returning an array from getLatestReport() so use the first file in the list for your excel reader. if you can return the only required filename form getLatestReport() you can simply use $excel->read($lastest->getLatestReport('battery-report.xls'));
try this
<table>
<?php
$latestFiles=$lastest->getLatestReport('battery-report.xls');
$excel->read($latestFiles[0]);
$x=1;

Base an if else statement on what folder an image is from on server?

I've used php to open and list the files in the folder, but I'd like to somehow turn it into an if else statement so that if its from the 'dark' background folder a white logo will be displayed and if its from a 'light' background folder a black logo will be displayed.
<?php
//path to directory to open
$directory = "backgrounds/dark";
$dir_handle = #opendir($directory) or die("Unable to open folder");
while(false !== ($file = readdir($dir_handle)))
{
if($file != '.' && $file != '..')
{
echo "{image : 'http://occa-art.com/backgrounds/dark/".$file."'}, ";
}
}
closedir($dir_handle);
?>
The {image: 'http://' } format is used because the images are listed within the Supersized background script.
---EDIT---
Maybe something like this (untested) to determine which folder the background image is from:
<?php
$doc = new DOMDocument();
$doc->loadHTML($htmlAsString);
$xpath = new DOMXPath($doc);
$nodeList = $xpath->query('//img[#class="bg"]/#src');
for ($i = 0; $i < $nodeList->length; $i++) {
# Xpath query for attributes gives a NodeList containing DOMAttr objects.
# http://php.net/manual/en/class.domattr.php
echo $nodeList->item($i)->value . "<br/>\n";
}
$bg_url = $nodeList->item($i)->value; // not sure about this?
$parent = dirname("$bg_url");
if ($parent == 'dark') { ?>
<img src="<?php bloginfo('template_url'); ?>/images/OCCAIndexHeaderwhite.png" alt="OCCA logo" />
<?php } else { ?>
<img src="<?php bloginfo('template_url'); ?>/images/OCCAIndexHeaderblack.png" alt="OCCA logo" />
<?php } ?>
used code found here and here

Cannot change src of image with Javascript in some versions of Chrome

Never could have imagined that chrome would have been the browser giving me grief, but the slideshow for our new website does not function properly in some versions of Chrome.
The error occurs here:
"mainPicture.src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"
Claiming that I can't modify mainPicture, an id that doesn't exist.
Obviously, other browsers don't have a problem seeing this object.
All help is much appreciated!
.
You can find the page here.
Source code:
<?php
/********************************************************************
* GATHER IMAGES FROM IMAGE DIRECTORY *
********************************************************************/
// Define directory where images are stored
$directory = "../../images/slideshow/";
// Create blank array to store image names
$pic_array = array("");
$num_pics;
// Create number to define position of images in array
$counter = 0;
// Gather pictures from image directory
if(is_dir($directory))
{
// Open directory to view files
if($dh = opendir($directory))
{
// Continue while still files to view
while(($file = readdir($dh)) !== false)
{
// Stop if picture limit of 6 reached
if($counter == 6)
break;
// Gather if object found is file or directory
$file_check = filetype($directory.$file);
// If object is a file, add it to the slideshow
if ($file_check == "file")
{
$extension = substr($file, strpos($file, "."));
if ($extension == ".png" || $extension == ".jpg")
{
$pic_array[$counter] = $file;
$counter++;
}
}
}
}
}
// Determine number of pics gathered
$num_pics = count($pic_array);
?>
<html>
<head>
<link href="scripts/slideshow.css" rel="stylesheet" type="text/css">
<?php
/********************************************************************
* CONTROL BEHAVIORS OF SLIDESHOW *
********************************************************************/
?>
<!-- Begin script to control slideshow -->
<script type = "text/javascript">
var thumbTop = 450; // starting value of thumb.style.top (make sure multiple of increment)
var highestTop = 342; // highest point mask can be on screen ,-, (make sure multiple of increment)
var lowestTop = 450; // lowest point mask can be on screen ,_, (make sure multiple of increment)
var delay = 2; // speed in which slide up and down methods are called
var increment = 5; // value that thumbTop increments with each method call
var intervalUp; // interval for thumb upward movements
var intervalDown; // interval for thumb downward movements
function startThumbSlideUp()
{
window.clearInterval(intervalDown);
intervalUp = window.setInterval(thumbSlideUp,delay);
}
function startThumbSlideDown()
{
window.clearInterval(intervalUp);
intervalDown = window.setInterval(thumbSlideDown,delay);
}
function thumbSlideUp()
{
thumbTop -= increment;
if (thumbTop <= highestTop)
{
thumbTop = highestTop;
window.clearInterval(intervalUp);
}
else
thumbMask.style.top = thumbTop;
}
function thumbSlideDown()
{
// Added to fix issue where images would start from too large a height
if (thumbTop <= highestTop)
thumbTop = highestTop;
thumbTop += increment;
if (thumbTop >= lowestTop)
{
thumbTop = lowestTop;
window.clearInterval(intervalDown);
}
else
thumbMask.style.top = thumbTop;
}
// Move marker above image <pos>
function setMarkerPos(pos)
{
marker.style.left = 600 - (66 * (pos)) + 19;
}
</script>
</head>
<?php
/********************************************************************
* DISPLAY SLIDESHOW *
********************************************************************/
// Start body and make images unhighlightable
echo '<body onselectstart="return false" style="margin: 0px;">';
// Create base value to increment horizontal position of thumbnails
$curr_thumb_left = 595; // (ignore this comment) 660<width of image> - 66<width of thumb> - 10<space between side> // 660
// Create and display main (large) image and image thumbnails
echo '<div id="mask" onmouseout = "startThumbSlideDown()" onmouseover = "startThumbSlideUp();">
';
echo '<img src = "'.$directory.$pic_array[0].'" id = "mainPicture" height = "420" width = "660" style = "z-index: -1; position:absolute;"/>
';
echo '<div id="thumbMask" height="66" width="660" style="z-index: 1; top: 450px; position: absolute;">
';
echo '<img id="marker" src="images/marker.png" height="10" width="10" style="z-index: 2; top: 0px; position: absolute;" onload="setMarkerPos(0);"/>';
// Search through image array, then assign names to and display thumbnails
for ($i=0; $i < $num_pics; $i++)
{
// Point to pic in array
$current_pic = $pic_array[$i];
// Create and display image thumbnails
if ($current_pic !== "")
{
echo '<img src = "'.$directory.$current_pic.'" id = "thumb'.$i.'" height = "50" width = "50" style = "left:'.$curr_thumb_left.'px; top: 10px; border: 3px white solid; position: absolute;" onclick = "mainPicture.src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"/>
';
// Move left value to the left [50px width + (3px padding * 2 sides) + 10px space between = 66px]
$curr_thumb_left -= 66;
}
}
echo '</div>';
echo '</div>';
?>
</body>
</html>
Chrome doesn't make image elements available by just their "id" value; you have to use document.getElementById("mainPicture") to get a reference to the DOM element. That'll work in all browsers anyway, so it's safe to just code it that way.
You are attempting to alter the src of mainPicture as though it were a global variable:
mainPicture.src = '.....';
Try referencing mainPicture by its id instead:
document.getElementById('mainPicture').src = '......';
You're not actually setting what mainPicture is, other browsers must be guessing whereas Chrome is doing what it should. Change:
echo '<img src = "'.$directory.$current_pic.'" id = "thumb'.$i.'" height = "50" width = "50" style = "left:'.$curr_thumb_left.'px; top: 10px; border: 3px white solid; position: absolute;" onclick = "mainPicture.src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"/>
to
echo '<img src = "'.$directory.$current_pic.'" id = "thumb'.$i.'" height = "50" width = "50" style = "left:'.$curr_thumb_left.'px; top: 10px; border: 3px white solid; position: absolute;" onclick = "document.getElementById('mainPicture').src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"/>

Categories