Detecting files in a folder with PHP - php

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.

Related

Using PHP to Merge Multiple CSV Files

I'm new to this forum and also new to PHP, I'm building some very basic functions on a test site while I learn a little more about how to use PHP. One of the current project I'm experimenting with is combining two directories of CSV files.
I was hoping to use GLOB as sort of a *wildcard to gather up the files in each directory and then combine them. I know the way I'm using below isn't very memory efficient but this is just to learn with. The issue I'm having is setting the GLOB command to pickup all my CSV files and then getting that variable into a file_get_contents.
Here's my code..
$files = glob("http://www.website.com/1/*.csv");
foreach($files as $filepath) {
if ($handle = fopen($filepath, "r")) {
// ...
}
}
$files2 = glob("http://www.website.com/35/*.csv");
foreach($files2 as $filepath2) {
if ($handle2 = fopen($filepath2, "r")) {
// ...
}
}
file_put_contents('final_data.csv',
file_get_contents($files) .
file_get_contents($files2)
);
When you use Glob the resulting array doesn't contain the base path, so you have to add it, like this:
$basePath = '/path/to/csv';
foreach ($files = glob("$basePath/dir1/*.csv") as $filePath)
{
echo "$basePath/$filePath";
//
}
It would also make sense to read from local path instead of remote URL.

PHP - Display Content in Json with Specific File Extension & Huge Records

As a PHP developer i am stuck. My mobile app developer needs an API where my PHP code will return only imagenames from a folder with following twist
1) There are almost 15,000 images in wp-content/uploads/2015/04 folder, which times out the page.
What i have tried is following code which works great, if there are less number of images in that folder.What should i do in this case.
<?php
$dir = "wp-content/uploads/2015/04";
$return_array = array();
if(is_dir($dir)){
if($dh = opendir($dir)){
while(($file = readdir($dh)) != false){
if($file == "." or $file == ".."){
} else {
$return_array[] = $file; // Add the file to the array
}
}
}
echo json_encode($return_array);
}
?>
I would recommend setting the php time limit to be higher using set_time_limit().
Also, try caching the results in a database or file, so you don't have to do an expensive lookup every time.
An alternative to opendir which might be faster would be to use the shell's "ls" command (note that this would be OS-specific, so reduce code portability).
For example:
echo json_encode(explode("\n", trim(`ls -1 wp-content/uploads/2015/04`)));

Selecting file to be edited

i have an application that is used to edit .txt files. the application is made up of 3 parts
Displays contents of a folder with the files to be edited(each file is a link when clicked it opens on edit mode).
writing in to a file.
saving to file.
part 2 and 3 I have completed using fopen and fwrite functions that wasn't too hard. the part that i need help is part one currently I open the file by inputing its location and file name like so in the php file where i have the display function and save function:
$relPath = 'file_to_edit.txt';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath ! ");
but what i want is for the file to open in edit mode when clicked instead of typing in the files name every time.
$directory = 'folder_name';
if ($handle = opendir($directory. '/')){
echo 'Lookong inside \''.$directory.'\'<br><br>';
while ($file = readdir($handle)) {
if($file !='.' && $file!='..'){
echo '<a href="'.$directory.'/'.$file.'">'.$file.'<a><br>';
}
}
}
this is the code that ti use to display the list of files that are in a specified folder.
Can anyone give me some pointers how I can achieve this ? any help will be greatly appreciated.
To get content of file use file_get_contents();
To put content of file use file_put_contents(); with FILE_APPEND flag for editing.
To recieve list of files in directory you can use DirectoryIterator
Example:
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\n";
}
If you don't want to put filenames you can put read files once put in db assign ids to them and use links with id param. The other solution is to store files in session array and assign keys for them. When you want to get a file you just need to provide key instead of whole filename and path.
Example with $_SESSION
$file_arr = array();
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
if($fileInfo->isDot()) continue;
$file_arr[] = array("path" => $fileInfo->getPathname(), 'name' => $fileInfo->getFilename());
}
$_SESSION['files'] = $file_arr;
then in view you can use
foreach($_SESSION['files'] as $k=>$file)
{
echo "<a href='edit.php?f=".$k."'>'.$file['name'].'</a>";
}
and edit.php
$file = (int)$_GET['f'];
if(array_key_exits($file, $_SESSION['files'])
{
$fileInfo = $_SESSION[$file'];
//in file info you have now $fileInfo['path'] $fileInfo['name']
}

Scan directory with PHP and use results in JavaScript

I scan a directory with PHP which includes only folders:
$folders = scandir('gallery');
Now i want to check if a string in javascript a folder in this directory.
if(theString == allTheFolders){
alert('yay');
}
Now $folders is an array with strings in it. To get all the strings i use a foreach loop and ignore the '.' & '..' directory's. But how can i get all these folders in the if loop?
Hope you understand my question!
Echo out your array as JSON, right into your JavaScript.
echo 'var folders = ', json_encode($folders);
Then you can loop through or do whatever you need directly in JavaScript.
Edit: Now that you have posted your actual question... Do this in your JavaScript:
var wantedFolder = 'something';
var wantedFolderFound = false;
for (folderIndex in folders) {
if (folders[folderIndex] === wantedFolder) {
wantedFolderFound = true;
}
}
if (wantedFolderFound) {
alert('Folder found!');
} else {
alert('Folder not found.');
}
As an alternative, I would probably use Array.indexOf(). It isn't available in all browsers, but that problem is easily remedied. See the documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf

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

Categories