Javascript slideshow from PHP array - php

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

Related

Getting direct path of directory which contain pages using PHP

Root
First_Folder
First_Folder_Pages
First_Folder_JS(js script here for ajax)
First_Folder_DB(php script that is linked from ajax request)
Second_Folder
Second_Folder_Pages
Second_Folder_JS(js script here for ajax)
Second_Folder_DB(php script that is linked from ajax request)
How can I get the direct path on the folder with names containing Pages using jQuery or PHP
Expected Output is like: ../../First_Folder/First_Folder_Pages or ../../Second_Folder/Second_Folder_Pages
This function w'd be enough for file list. Just make an ajax call to it, json_encode to output before send back to javascript
function scan($dir)
{
$output = array();
$handle = opendir($dir);
if ($handle != false) {
while ($file = readdir($handle)) {
if ($file == '.' || $file == '..')
continue;
$path = $dir . '/' . $file;
if (is_dir($path))
$output += scan($path);
else
$output[] = $path;
}
}
return $output;
}
İf you want to add folders to array too, just change the if statement like;
if (is_dir($path))
$output += scan($path);
$output[] = $path;
Also you can use RecursiveDirectoryIterator class too: stackoverflow
UPDATE
Just erase the "else" keyword if you want to add folders too in output.
If you call function like;
scan('/root/');
The output will give you results like;
'/root/First_Folder/First_Folder_file1',
'/root/Second_Folder/Second_Folder_file1',
'/root/Second_Folder/Second_Folder_file2'
But if u erase "else" keyword, you will get results like;
'/root/First_Folder',
'/root/First_Folder/First_Folder_file1',
'/root/Second_Folder',
'/root/Second_Folder/Second_Folder_file1',
'/root/Second_Folder/Second_Folder_file2'

How Can I filter dir and files inside the parent dir in PHP?

I've a function which scan through the provided dir and returns all the files and sub directory inside the parent dir.
public function show_image(){
$dir=FCPATH.'uploads/';
$files = scandir($dir);
$ret= array();
$result=array();
foreach($files as $file)
{
if($file == "." || $file == "..")
continue;
$filePath=$dir."/".$file;
$details = array();
$details['name']=$file;
$details['path']=$filePath;
$details['size']=filesize($filePath);
$ret[] = $details;
}
echo json_encode($ret);
//echo json_encode($result);
}
Basically I'm using Ajax, so what I'm doing is printing both folders and files inside that dir. But the problem here is that I really want to filter the subdir and file which this function isn't currently doing.
I want to have the folder printed out at the very beginning whereas other files after the folders.
The $ret consists the data in ascending order. In the view I've following Ajax onSucess function.
onSuccess:function(files,data,xhr,pd)
{
var src = '<?php echo base_url("uploads"); ?>'+'/'+data.file_name;
var html = '<div class="col-sm-3 text-center"><div class="mid-folder">';
html+= '<div class="folder-content"><img src="'+src+'" class="img-container" style="max-height:100%; max-width:100%;"/></div>'
html+= '<h3 class="title-folder">'+data.file_name.substr(0,10)+".."+' </h3> </div>';
$('.hello').append(html);
$('.ajax-file-upload-statusbar').fadeOut(1000, function(){
$('.ajax-file-upload-statusbar').show(1000).html('Your file successfully uploaded');
});
$('.ajax-file-upload-statusbar').hide('slow');
}
What should I be doing, so that I could display the folder and files in different way. Basically a logic/way by which I can filter which object inside the $ret should be treated as dir and which as file and display it thoroughly.
I'd go with separering files and directories on the server side, and then sending a json object with to arrays. One with directories and one with files.
$ret= array();
$result=array();
foreach($files as $file){
if($file == "." || $file == "..")
continue;
$filePath=$dir."/".$file;
$details = array();
$details['name']=$file;
$details['path']=$filePath;
$details['size']=filesize($filePath);
if(is_dir($filePath) {
$ret['directories'][] = $details;
}
else {
$ret['files'][] = $details;
}
}
Next, make two loops in the ajax success callback function. One for data.directories and one for data.files.

php array keyword counter

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"],
keyw‌​ords=>$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]++;
}
}

Javascript array doesn't notice new images in folder

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 .'";');
....
}

auto display filename in a directory and auto fill it as value

I want something (final) like this :
<?php
//named as config.php
$fn[0]["long"] = "file name"; $fn[0]["short"] = "file-name.txt";
$fn[1]["long"] = "file name 1"; $fn[1]["short"] = "file-name_1.txt";
?>
What that I want to?:
1. $fn[0], $fn[1], etc.., as auto increasing
2. "file-name.txt", "file-name_1.txt", etc.., as file name from a directory, i want it auto insert.
3. "file name", "file name 1", etc.., is auto split from "file-name.txt", "file-name_1.txt", etc..,
and config.php above needed in another file e.g.
<? //named as form.php
include "config.php";
for($tint = 0;isset($text_index[$tint]);$tint++)
{
if($allok === TRUE && $tint === $index) echo("<option VALUE=\"" . $text_index[$tint]["short"] . "\" SELECTED>" . $text_index[$tint]["long"] . "</option>\n");
else echo("<option VALUE=\"" . $text_index[$tint]["short"] . "\">" . $text_index[$tint]["long"] . "</option>\n");
} ?>
so i try to search and put php code and hope it can handling at all :
e.g.
<?php
$path = ".";
$dh = opendir($path);
//$i=0;
$i= 1;
while (($file = readdir($dh)) !== false) {
if($file != "." && $file != "..") {
echo "\$fn[$i]['short'] = '$file'; $fn[$i]['long'] = '$file(splited)';<br />"; // Test
$i++;
}
}
closedir($dh);
?>
but i'm wrong, the output is not similar to what i want, e.g.
$fn[0]['short'] = 'file-name.txt'; ['long'] = 'file-name.txt'; //<--not splitted
$fn[1]['short'] = 'file-name_1.txt'; ['long'] = 'file-name_1.txt'; //<--not splitted
because i am little known with php so i don't know how to improve code more, there are any good tips of you guys could help me, Please
New answer after OP edited his question
From your edited question, I understand you want to dynamically populate a SelectBox element on an HTML webpage with the files found in a certain directory for option value. The values are supposed to be split by dash, underscore and number to provide the option name, e.g.
Directory with Files > SelectBox Options
filename1.txt > value: filename1.txt, text: Filename 1
file_name2.txt > value: filename1.txt, text: File Name 2
file-name3.txt > value: filename1.txt, text: File Name 3
Based from the code I gave in my other answer, you could achieve this with the DirectoryIterator like this:
$config = array();
$dir = new DirectoryIterator('.');
foreach($dir as $item) {
if($item->isFile()) {
$fileName = $item->getFilename();
// turn dashes and underscores to spaces
$longFileName = str_replace(array('-', '_'), ' ', $fileName);
// prefix numbers with space
$longFileName = preg_replace('/(\d+)/', ' $1', $fileName);
// add to array
$config[] = array('short' => $filename,
'long' => $longFilename);
}
}
However, since filenames in a directory are unique, you could also use this as an array:
$config[$filename] => $longFilename;
when building the config array. The short filename will form the key of the array then and then you can build your selectbox like this:
foreach($config as $short => $long)
{
printf( '<option value="%s">%s</option>' , $short, $long);
}
Alternatively, use the Iterator to just create an array of filenames and do the conversion to long file names when creating the Selectbox options, e.g. in the foreach loop above. In fact, you could build the entire SelectBox right from the iterator instead of building the array first, e.g.
$dir = new DirectoryIterator('.');
foreach($dir as $item) {
if($item->isFile()) {
$fileName = $item->getFilename();
$longFileName = str_replace(array('-', '_'), ' ', $fileName);
$longFileName = preg_replace('/(\d+)/', ' $1', $fileName);
printf( '<option value="%s">%s</option>' , $fileName, $longFileName);
}
}
Hope that's what your're looking for. I strongly suggest having a look at the chapter titled Language Reference in the PHP Manual if you got no or very little experience with PHP so far. There is also a free online book at http://www.tuxradar.com/practicalphp
Use this as the if condition to avoid the '..' from appearing in the result.
if($file != "." && $file != "..")
Change
if($file != "." ) {
to
if($file != "." and $file !== "..") {
and you get the behaviour you want.
If you read all the files from a linux environment you always get . and .. as files, which represent the current directory (.) and the parent directory (..). In your code you only ignore '.', while you also want to ignore '..'.
Edit:
If you want to print out what you wrote change the code in the inner loop to this:
if($file != "." ) {
echo "\$fn[\$i]['long'] = '$file'<br />"; // Test
$i++;
}
If you want to fill an array called $fn:
if($file != "." ) {
$fn[]['long'] = $file;
}
(You can remove the $i, because php auto increments arrays). Make sure you initialize $fn before the while loop:
$fn = array();
Have a look at the following functions:
glob — Find pathnames matching a pattern
scandir — List files and directories inside the specified path
DirectoryIterator — provides a simple interface for viewing the contents of filesystem directories
So, with the DirectoryIterator you simply would do:
$dir = new DirectoryIterator('.');
foreach($dir as $item) {
if($item->isFile()) {
echo $file;
}
}
Notice how every $item in $dir is an SplFileInfo instance and provides access to a number of useful other functions, e.g. isFile().
Doing a recursive directory traversal is equally easy. Just use a RecursiveDirectoryIterator with a RecursiveIteratorIterator and do:
$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
foreach($dir as $item) {
echo $file;
}
NOTE I am afraid I do not understand what the following line from your question is supposed to mean:
echo "$fn[$i]['long'] = '$file'<br />"; // Test
But with the functions and example code given above, you should be able to do everything you ever wanted to do with files inside directories.
I've had the same thing happen. I've just used array_shift() to trim off the top of the array
check out the documentation. http://ca.php.net/manual/en/function.array-shift.php

Categories