Yesterday I got a question about a slideshow with lightbox fixed on stackoverflow but now I came to another problem.. I create an Javascript array trough php and in JS I make the slideshow work + lightbox work. Now when I add a new image to the images folder it does include it in the src"" attribute but does not show the image and instead shows the error picture when an image doesn't work (couldn't include an image because I don't have enough rep if you would like the image of the problem, I can send it)
This is the php code part:
//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname ="/Applications/MAMP/htdocs/slidepluslight/slideshows/minpunten/images/") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
print_r ('galleryarray['.$curimage.']="'.$file .'";');
$curimage++;
}
}
closedir($handle);
}
return($files);
}
print 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
And this is the Javascript code that makes the slideshow + lightbox work.
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/"+galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 500);
}
window.onload = function(){
setInterval("rotateimages()", 2500);
document.getElementById("slideshow").onclick = function () {
var imageSrc = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", imageSrc);
document.getElementById('lightbox').style.display = 'block';
document.getElementById('fade').style.display = 'block';
}
}
It all runs fine but when I add a new image to the images folder it doesn't show it..
Regards Koen.
UPDATE, everything worked but we tried to do it dynamically but now the src"" gives me undefined.. Does somebody see where I code it wrong?
The php part:
function returnimages($relPath = "/slidepluslight/slideshows/minpunten/images/") {
$dirname = $_SERVER['DOCUMENT_ROOT'] + $relPath;
$files = array();
$curimage = 0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if (preg_match('/\.(jpg|jpeg|gif|png)$/', $file)){ //if this file is a valid image
//Output it as a JavaScript array element
print_r ('galleryarray['.$curimage.']="'. $relPath + $file .'";');
$curimage++;
}
}
closedir($handle);
}
return($files);
}
print 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
And the Javascript part:
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
Kinds regards,
Koen.
The reason you were having trouble is you weren't properly refering to the location of the images. I'll find some links to have you look it in a min.
If you change
document.getElementById("slideshow").setAttribute("src", "images/"+galleryarray[curimg]);
to
document.getElementById("slideshow").setAttribute("src", "/slidepluslight/slideshows/minpunten/images/"+galleryarray[curimg]);
the browser will know to look in the /slidepluslight/slideshows/minpunten/images directory for the images.
The remander of this answer applies to the dynamic URL issue so this solution could be used in other applications.
As far as making the links to the images dynamic it seems to me like it needs to be addressed in the returnimages function.
Use $_SERVER['DOCUMENT_ROOT'] to get the root directory of website. Here that is /Applications/MAMP/htdocs and then have the rest specified as a parameter to returnimages.
function returnimages($relPath = "/slidepluslight/slideshows/minpunten/images/") {
$dirName = $_SERVER['DOCUMENT_ROOT'] . $relPath;
...
/* Where you are outputting the JS array */
print_r ('galleryarray['.$curimage.']="'. $relPath + $file .'";');
....
}
Related
This question already has answers here:
How to prevent Browser cache for php site
(7 answers)
Closed 3 years ago.
I am trying to give my wordpress site a randomly pulled "About the Author" image in my footer.
My first solution was to create an array, name them each aboutAuthor[x].jpg and generate a random number for x.
That works just fine, but I was looking for a solution that didn't involve me having to rename files and adding a line of code every time I decide to add a new image to the folder.
I found a solution on this site: http://photomatt.net/scripts/randomimage
He provides some php code
<?php
$folder = '';
$exts = 'jpg jpeg png gif';
$files = array();
$i = -1;
if ('' == $folder)
$folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach ($exts as $ext) {
if (preg_match('/\.' . $ext . '$/i', $file, $test)) {
$files[] = $file;
++$i;
}
}
}
closedir($handle);
mt_srand((double) microtime() * 1000000);
$rand = mt_rand(0, $i);
header('Location: ' . $folder . $files[$rand]);
?>
Then I simply place that php file in the directory in question and call it in place of an image
<img src="/imgDirectory/rotate.php">
The only problem with this is that my browser is caching the resulting random image.
With a normal reload or clicking a link to a new page, I get the same image.
With a hard reload, I get a new one, like I want.
Oddly, in the sample on his website, it works as expected with a normal reload.
So what is the best way to achieve what I'm looking for?
Here is the solution
1) Create new div:
<div class="randomAuthor" id="randomAuthor"> </div>
2) Move image source
<img src="/imgDirectory/rotate.php">
to a separate PHP or html file, example author.php:
3) Load author.php into div "randomAuthor" using
ajax code:
$(document).ready(function(){
$('#randomAuthor').load("author.php");
});
This way on each refresh the $(document).ready(function(){..... will get triggerd which in turn will trigger rotate.php file thus you will get new image each time you open your page or refresh it.
I haven't seen this asked yet, so if it is, can someone re-direct me?
I'm having an issue creating a full screen background for my WordPress theme that uses random images from the image library. I want to write a PHP function that can be used on multiple sites, so I can't simply use the direct path in the code. It also needs to work on MultiSite in such a way that it only pulls images that are uploaded to that site. Here's the code I'm working with:
HTML for my Background Div
<div id="background" class="background" style="background-image:url(<?php displayBackground();?>);">
</div>
PHP to randomize my image folder
<? php
function displayBackground()
{
$uploads = wp_upload_dir();
$img_dir = ( $uploads['baseurl'] . $uploads['subdir'] );
$cnt = 0;
$bgArray= array();
/*if we can load the directory*/
if ($handle = opendir($img_dir)) {
/* Loop through the directory here */
while (false !== ($entry = readdir($handle))) {
$pathToFile = $img_dir.$entry;
if(is_file($pathToFile)) //if the files exists
{
//make sure the file is an image...there might be a better way to do this
if(getimagesize($pathToFile)!=FALSE)
{
//add it to the array
$bgArray[$cnt]= $pathToFile;
$cnt = $cnt+1;
}
}
}
//create a random number, then use the image whos key matches the number
$myRand = rand(0,($cnt-1));
$val = $bgArray[$myRand];
}
closedir($handle);
echo('"'.$val.'"');
}
I know that my CSS markup is correct because if I give the DIV a fixed image location, I get a fullscreen image. Can anyone tell me what to do to fix it?
My goal is to pull the images from a file into a PHP array, then convert that array to a Javascript array that I could then use for my slideshow. That way I don't have to manually update my code when I add a new image to a file.
I am struggling with the Javascript part. I know that I can somehow use JSON function to convert the PHP array to Javascript array but I don't know how to use that function properly.
This is my PHP code that displays all pictures from a file called "slike":
<?php
$dir = 'slike';
$file_display = array('jpg','jpeg','png');
if (file_exists($dir) === false){
echo "Directory ".$dir." doesn't exist!";
}
else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file){
$file_typeExplode = explode('.', $file);
$file_type = strtolower(end($file_typeExplode));
if($file !== '.' && $file !== '..' && in_array($file_type, $file_display) === true){
echo '<img src = "', $dir, '/', $file, '" alt ="', $file, '" />';
}
}
}
?>
Not sure what that "converting to javascript array" part really means but I think you want to construct an array in javascript starting from what you have in the html page (DOM).
First of allyou have to identify the element of your page containing all the images, say it is an id of name foo :
<div id="foo">
<img src....>
</div>
then in javascript you iterate on all the child elements of your div (that are your images) and construct an array with them.
var arry = [];
var images = document.getElementById('foo').childNodes;
for(i=0; i<nodes.length; i++) {
arry.push(nodes[i]);
}
You could also give a class to all your images and iterate on all document.getElementsByClassName
I am pushing image file information into an array.
It is pretty simple except the keywords are sometimes an array also.
This works great for what I am doing now.
Here is a sample of my array
$list[]=array(filename=>$file,width=>$w,height=>$h,caption=>$iptc["2#120"],keywords=>$iptc["2#025"]);
I can use this array to output the html needed for a javascript slideshow.
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){
//if this file is a valid image
$path = $dirname . "" . $file ;
$path2 = $dirname ."JPEG/" . $file ;
$size = getimagesize($path, $info);
$w = $size[0]; $h = $size[1];
$iptc = iptcparse($info['APP13']);
if(in_array($key,$iptc["2#025"])){
$list[]=array(
filename=>$file,
width=>$w,
height=>$h,
caption=>$iptc["2#120"],
keywords=>$iptc["2#025"]
);
}
}
}
closedir($handle); }
I would like to be able to have another variable in the array which would count up one number as each unique keyword is added. This will allow me to go directly to the middle of a slideshow as the js plugin I am using a js slideshow only have direct links if referenced by a number
I imagine I would need to create a unique array of all the keywords and then have some type of complicated if statement to count for each of the unique variables.....
however I have no Idea how to do this
Help Please
thanks
Jeremy
Im not sure if I understand what you're looking for but it sounds like:
while(loop_conditions){
$list[]=array(filename=>$file,width=>$w,height=>$h,caption=>$iptc["2#120"],keywords=>$iptc["2#025"]);
foreach($iptc["2#025"] as $keyword){
$list_map[$keyword]++;
}
}
I am trying to make an HTML5 slideshow system that implements PHP. My idea begins with making a system that detects the images in a folder, and puts them in an array, which the jquery will then be able to access for implementation in the slideshow. Firstly I have a php file that will detect the names of every file in the folder, and output them as plain text.
How, instead of outputting as plain text, can i make the PHP transfer the file names to a numerical array, which can be used with the jquery that will then accompany it?
I intend to use jquery to access the numerical array that is then made. How is this done? Unless it is not possible to do, and so how else can it be done?
The goal is to be able to put files in a folder, and for the scripting to dynamically recognize the presence of files, and incorporate them in a slideshow. This slideshow will then be output to a screen display which will be used in a waiting area, showcasing our school with a slideshow of images about the school.
Here is the code that I have so far:
<?php
//Open images directory
$dir = opendir("images");
//List files in images directory
while (($file = readdir($dir)) !== false)
{
echo "filename: " . $file . "<br />";
}
closedir($dir);
?>
At this point I do not know how to make PHP "talk" with Javascript. I hope that there is some simple method for this, what I think I'm going for is AJAX, but I have no idea how this works.
The answer here is to use JSON, a subset of Javascript supported by many languages that allows you to (amongst many other things) very easily pass structured data into Javascript from external sources. PHP has a function json_encode() which allows you convert PHP data structures - usually arrays or objects - into a format the Javascript can easily read. jQuery also has built-in support for JSON.
<?php
// An array of the image file names
$images = array();
//Open images directory
$dir = opendir("images");
//List files in images directory
while (($file = readdir($dir)) !== false)
{
$images[] = $file;
}
closedir($dir);
echo json_encode($images);
?>
Now, in jQuery you can do this:
$.getJSON('http://url/of/your/script.php', function(images) {
// In here the variable "images" is an array identical to the one you constructed with PHP
});
Yes you can use ajax to fetch the image filenames as an array by changing you php code like follows
<?php
//Open images directory
$dir = opendir("images");
$images = array();
//List files in images directory
while (($file = readdir($dir)) !== false)
{
//echo "filename: " . $file . "<br />";
$images[] = $files;
}
closedir($dir);
echo json_encode($images);
?>
then use $.getJSON o fetch that list
$.getJSON('path_to_above_php_file', function(images) {
//all your files are in images array, you can loop through it to find individual files
});
You could have an array with all your pictures then convert this array to JSON.
There are a few ways to do this, a quick and easy way is to do:
your php:
$dir = opendir("images");
$store = array();
while (($file = readdir($dir)) !== false)
{
$store[] = $file;
}
closedir($dir);
Now you have an array of all files (i might add that you may want to validate the file is an image!). I like to just dump them into JS as a json string as it saves me messing around. so:
echo "<script> var allimages = jQuery.parseJSON('".addslashes(json_encode($store))."'); </script>";
Now if you console.log() the allimages variable you will see you have all your images within that so you can use "$.each" or similar if you wish.
Rather than simply storing the name of the images, why not write the images themselves to your document? So something like:
<?php
//Open images directory
$dir = opendir("images");
//List files in images directory
while (($file = readdir($dir)) !== false)
{
$files[] = YOUR_URL_PATH.$file;
}
closedir($dir);
?>
...
<div id="slideshow">
<?php
foreach($files as $img)
echo '<img class="slide" src="'.$img.'" />';
?>
</div>
...
<script type="text/javascript">
$(document).ready(function()
{
alert($(".slide").length+" slides detected");
});
</script>
That way, instead of relying on PHP to define your jQuery, you're using PHP to define the elements jQuery needs in order to function properly.
UPDATE:
If your PHP and Javascript exist on the same page, and you still want to be able to set a Javascript array using PHP, then I think this is what you're looking for:
<?php
//Open images directory
$dir = opendir("images");
//List files in images directory
while (($file = readdir($dir)) !== false)
{
$files[] = YOUR_URL_PATH.$file;
}
closedir($dir);
?>
...
<script type="text/javascript">
$(document).ready(function()
{
var fileArr = [<?php echo implode(',',$files); ?>];
});
</script>
This requires that your Javascript resides on the same page as your PHP that defines the file array. If your Javascript is intended to be referenced externally, then your best bet is to use JSON array as mentioned by many of the other answers here.
I would say JSON suits your situation well. Just create PHP file that prints (echo) the JSON object containing the list of your files. You can use json_encode() to create the JSON object. On your browser side you can make an AJAX request (or simply use jQuery.getJSON()) and set the data type to JSON and you should be good to go:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
Here you can read about using JSON in PHP.
SPL library has function to handler directories
From PHP site:
Usage example:
To see all the files:
<?php
$ite=new RecursiveDirectoryIterator($_POST['path']);
$files = array();
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
array_push($files, $filename);
}
echo json_encode($files);
?>
Now with jquery.post() you can retrieve the list of files in folder.