How to get filename of the latest file?

Hi.

I am trying to create a simple web page that shows a picture sended by IP camera and updated every 10 seconds.
IP camera sends those .jpg pictures to certain folder but every picture has unique filename.
I have found javascript code that updates picture every 10 seconds but it uses same filename.

how i can get the filename of the latest .jpg image (with or without the file extension) in certain folder and pass it to that javascript? or replace also the picture showing part with php?

Ok.
After some googling around i found a php code that does the trick for me:

[php]<?php
$path = “your/dir/here”;

$latest_ctime = 0;
$latest_filename = ‘’;

$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = “{$path}/{$entry}”;
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
// now $latest_filename contains the filename of the newest file
?>[/php]

I plan to use this code to show pictures, but how i can combine this so it will show the picture saved in $latest_filename variable?

[code]

Title of your page

[/code]

Well, PHP is SERVER-SIDE only. Nothing runs in the browser.

SO, either you can “refresh” the page and let the PHP load the latest filename into the picture field
(annoying because the the constant “refresh” of the entire page!)

OR, just have the Javascript load the picture into the image field after it locates the latest value.

So, let’s say you display it this way:
If pictures from camera are in a folder called “images”…
Note, I started with the first picture

In Javascript you can load values into fields this way: (image version)
document.getElementById(“camerapix”).setAttribute(“src”, “images/” + lastest_filename)
Of course, this is if you used Javascript to take the picture…

If you are talking about just displaying the picture using PHP, you would normally use HTML like this:

So, you would replace that to do this:

Either way would work, JS or PHP… Good luck!

Thank you.

I tried running my php script and then using

to show picture.

It worked, but the picture is not updated unless the php script is run again and $lastest_filename variable changed. And it is not changing unless i refresh the page manually from browser.
Can i somehow set the php script to run in infinite loop in background and maybe delay it 10 seconds aswell?

or is there a javascript way to find the latest filename in ./images folder and make it as variable (and updated), so i could abandon php altogether?

Yes, that is what I was explaining… PHP is SERVER-SIDE only ! ! ! It can NOT change anything once it is in the browser. You can have Javascript refresh the page which means the PHP will reload the image…

Also, I did some tests… You can NOT read an image into a page with standard Javascript. The picture must already be available to the script. So, that would not work either.

But, you can use JQuery/Ajax to load the picture into a

and display. Basically, you would create a simple PHP page that pulls the latest picture as you did before and displays it. This page would be called by JQuery and loaded into an area on the page. Then, the page would not appear to reload or refresh, but, the picture itself would. Should work nicely for you!

Now, on to that code… Basically you can use the code you have. Just a couple changes.

First, create a small

tag at the bottom of your page:
     <DIV id='lastestfilename'></DIV>

This is just a place to store the hidden output from the PHP page…

Create a small PHP program that loads the last file into a text field. Use the same as you last PHP code, but, just add a display for the field like this: (Let’s call it “getfilename.php”)
[php]
echo “”;
[/php]
This will just display one line which will be a hidden field containing the address of the latest image.

Then, you have to change the Javascript to use this routine on your timer. Basically, leave the timer as is, just add this code. It will “dynamically” load the getfilename.php file into the hidden field. Then, you just use the filename in the code you have now. Should work…

For this part, replace " var currentPath=document.campic.src;" with this:


 if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }
    else
   {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

 xmlhttp.onreadystatechange=function()
   {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
     document.getElementById("latestfilename").innerHTML=xmlhttp.responseText;
     }
   }

 xmlhttp.open("GET","getfilename.php",true);
 xmlhttp.send();
 var currentPath=document.getElementById('filenameaddress').value;

(not sure if that last one is .value or .text for hidden input fields…)

So, every time the clock cycle hits, it will call the the PHP file, locate the latest file, stuff it into a hidden field, load it into the current page and show the new pix… Should work, it not let us know. I did not test it yet!

that sounds great. I will try to work with that after i get some sleep :slight_smile:

Hi

i tried to modify the code with these instructions. Basically what i changed was replaced all “lastest” parts with “latest”

Since the filename IS changing every time, i tried to skip the part in javascript that adds random numbers to filename to fool the browser not use cache.

But i can not get this working, please Ernie or someone can you validate my code, im sure it’s something small i have missed?

my index.php file:

[code]

Title of your page

[/code]

getfilename.php :

[php]<?php
$path = “./pictures”;

$latest_ctime = 0;
$latest_filename = ‘’;

$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = “{$path}/{$entry}”;
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
// now $latest_filename contains the filename of the newest file
echo “”;
?>[/php]

Okay, let’s debug your code. First, look in your pictures folder and find the last picture.
(So we know what we need to locate.)

Then, at the end of your PHP code:
// now $latest_filename contains the filename of the newest file
echo “”;
?>
Change and add a debug line to show the file that it actually gets:
// now $latest_filename contains the filename of the newest file
echo “”;
die(’$path/$latest_filename’);
?>

In this way we can see if the path and latest_filename are matching your correct folder and picture.
If they are not, then the problem is in your PHP and it is not locating the filename correctly.
If they are the same, then the problem is either the hidden field is not correctly going into the display HTML or the Javascript is not getting to the hidden field. Either way we will narrow down where the issue is.
Let us know…

PS: Sorry for the incorrect spelling of latest… I was typing fast helping many others… LOL…

Thanks for the reply. It looks like getfilename.php is working. It returns value ./pictures/webcam.jpg that is the only file in that folder atm. I also tried to change format to “text” in index.php and in getfilename.php but it did not work any better.

Okay, first, you must place another picture, or 3 more on your server’s picture folder.
If you are testing getting the latest picture, you must have a few samples so the code can be tested.

Next, you should just get the actual display working without all of the JS stuff and dynamic displays.

Just create a new test page with HTML and a PHP routine. Have the routine locate the latest filename
and display it. If it picks the latest of the 3 or 4 pictures you have uploaded, then, we will guess that
part is complete. Then, change the filename display to an image tag display and see if it shows that pix.

This will prove that the last-picture code is working and that you can display the file after finding it.

When, all that works well. (Test a second time by deleting the picture file that it finds the first time!)
You can then get it to work with the dynamically loaded version. This will tell you if it is something in the
get-last-filename section or the displaying of the picture. If all that works, then it is just your Javascript!

Good luck, and let us know where the problem lies…

Correction: if add

die(’$path/$latest_filename’);
to getfilename.php i see $path/$latest_filename

if i just remove type=“hidden” from echo command i see

./pictures/webcam.jpg inside box.

Okay, sorry, this: die(’$path/$latest_filename’);

Should be: die($path . “/” . $latest_filename); so it shows the path + / + filename…

So, it sounds like the hidden works. So, try putting another line after the hidden line:

[php]
echo “”;
echo “”;
[/php]
Then, you should see the picture, if this works, try it with a newer picture added to the pictures folder.
If that displays the newer folder, then the error is in your Javascript. I can test that tonight, leaving soon.

Let us know if the picture display part works…

Yep, it is working and if i let my IPcamera load newer picture to that folder and i update browser windows manually it will update to the latest picure.

i also made basic index.html file:

[code]<?xml version="1.0" encoding="UTF-8"?>

[/code]

and removed those test lines from getfilename.php

[php]<?php
$path = “./pictures”;

$latest_ctime = 0;
$latest_filename = ‘’;

$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = “{$path}/{$entry}”;
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
// now $latest_filename contains the filename of the newest file
echo “”;
?>[/php]

if i load index.html i get blank screen, or in fact white :slight_smile:

Hmm, i now got it working, so far that routine gets a filename from getfilename.php. But it still only
shows one picture, it does not update it unless i update browser manually…
what is wrong with the loop?

[code]<?xml version="1.0" encoding="UTF-8"?>

[/code]

Hmmm! I think we are close on this one!

I went out and checked with my buddy, my friend, Google! LOL…

And, found the routine for “freshpic()”. It was not the same version you have. Here is the version I found:
(I altered the version I found to fit your code. Try it and let us know if it works!)

[php]
function freshPic()
{
// Get the source value for the picture
var newicture = new Image();
newpicture.src = ‘button_up.gif’;

// Load the pictuer into the img tag…
document[‘latestfilename’].src = button1_over.src

// Go back and wait again.
holdUp();
}
[/php]

BUT, this code used a standard IMG tag display…
So, you may have to change from a DIV to an IMG… Not sure, I will test it tonight… Good luck!

Thanks again Ernie. I will try. In fact i tried another approach of that i tought was simpler. Instead of getting the filename i changed the php file so that after it finds last filename it simply renames it “webcam.jpg”. That way i thought that i could use almost exact format of the original “ajaxcam” just add line where it will execute that php. But i simply cant get it to execute inside that “freshpic” function…

Well, that brings us back to the original comments…

PHP is SERVER-SIDE. Javascript is CLIENT-SIDE. So, when the file is changed on the server, you can use PHP to save it or whatever. BUT, the altering of it on the screen is all CLIENT-SIDE. Unless you want to refresh the page and reload the PHP-code from the server which can change the picture.
You must do the refresh either by loading a new copy of the PHP file in a DIV or by using the refresh code you now have. The code you have now is the better way to go. But, you the older version does not REFRESH the IMG tag. The code I gave you last does that. It takes the hidden value of the filename and then displays it.

If you can’t get it to work, I will create a working version for you tonight as I am working online then…

at first i tought that some file rights prevent renaming, but if run getfilename.php or rename.php as i now call it it works and renames latest picture to webcam.jpg. But both solutions work for me if it is possible to get that loop working.

yep. I begin to understand what you mean by SERVER SIDE ONLY! :slight_smile:
Anyway thanks again it is amzing that someone is willing to give this kind of help for free…

No problem that is what we are here for… Hence, the name PHP-help.com… LOL
You can always Karma up your buddies if the go out of their way… Not asking that for me, just mentioning it as you have had others helping you out…

Anyway, the problem with the renaming is that you are having a picture created every so many seconds.
It is fast to just find the last picture and display it then, rename it every few seconds. Reading is much faster than rename or rewriting…

If you are only interested in the live picture, just write over it and be done with it. Another way is to save it to the folder that has ALL of the pictures in it and save just the lastest as the camera.jpg. Then, you will have the archives AND the latest without going thru the issue of looking for the latest. That would be the fastest way.

Anyway, your Javacript routine is nearly correct. It just is NOT set up to replace the live picture on the page.
The code I sent should work. If it doesn’t post back here with your current code and I will have time a bit later to test it for you and fix it. (I have another hour or so on this job…) Later…

Sponsor our Newsletter | Privacy Policy | Terms of Service