I just can't seem to get this working on a Linux server. On WAMP this is working nicely.
Basically, I have set up a webcam, which uploads images every 60 seconds to a folder on FTP server. Then, I've created a site, where I call Ajax in order to scan this folder and get last image (based on creation time).
When I access the page, freshest image is indeed loaded, CHMOD are set correctly. But when I wait on the page, new ajax requests are called and returned image is always the same, eventhough there are new images already uploaded on FTP - those new images are skipped and no CHMOD are set either.
I don't know what is the issue.
This is what I have:
index.php:
<img id='webcam-img' alt='Webkamera' src='' />
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script language="JavaScript" type="text/javascript">
function getImage() {
var src = '';
$.ajax({
url: "ajax-get-webcam-image.php",
async: false,
success: function(data){
src = data;
}
});
return src;
}
function updateImage() {
var src = getImage();
$("#webcam-img").attr("src", src + "?timestamp=" + new Date().getTime());
setTimeout(updateImage, 5000);
}
updateImage();
</script>
ajax-get-webcam-image.php:
<?php
$folder = "images/webcam"; // the folder with images
function getImages($dir) {
$allFiles = scandir($dir);
$files = array_diff($allFiles, array('.', '..'));
foreach ($files as $f) {
chmod($dir . '/' . $f, 0644); // uploaded images are set to 0640 and can't be read on a page. Must set CHMOD to 644
}
$ignored = array('.', '..'); // ignore this
$files = array();
foreach (scandir($dir) as $file) {
if (in_array($file, $ignored)) continue;
$files[$file] = fileatime($dir . '/' . $file);
}
$files = array_keys($files); // sort images
$files = array_reverse($files);
// foreach ($files as $k => $file) {
// if ($k > 9) { // delete old images, leave 10 freshest on server
// unlink(__DIR__ . '/' . $dir . '/' . $file);
// }
// }
return ($files[0]) ? $files[0] : false; // return freshest image
}
$img = getImages($folder);
echo $folder . '/' . $img;
?>
Thanks for tips!
Ok, so it was an issue with caching, so I've modified ajax call with adding t=" + new Date().getTime()
to url parameter:
function getImage() {
var src = '';
$.ajax({
url: "ajax-get-webcam-image.php?t=" + new Date().getTime(),
async: false,
success: function(data){
src = data;
}
});
return src;
}