PHP + Ajax,从网络摄像头获取新鲜图像

PHP + Ajax, get fresh image from webcam

我似乎无法在 Linux 服务器上运行它。在 WAMP 上,这工作得很好。

基本上,我设置了一个网络摄像头,每 60 秒将图像上传到 FTP 服务器上的一个文件夹。然后,我创建了一个站点,我在其中调用 Ajax 以扫描此文件夹并获取最后一张图像(基于创建时间)。

当我访问该页面时,确实加载了最新的图像,CHMOD 设置正确。但是当我在页面上等待时,新的 ajax 请求被调用并且返回的图像总是相同的,尽管 FTP 上已经上传了新图像 - 这些新图像被跳过并且没有设置 CHMOD .

不知道是什么问题

这是我的:

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-获取网络摄像头-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;
?>

感谢提示!

好的,这是缓存问题,所以我修改了 ajax 调用,将 t=" + new Date().getTime() 添加到 url 参数:

function getImage() {
    var src = '';
    $.ajax({
        url: "ajax-get-webcam-image.php?t=" + new Date().getTime(),
        async: false,
        success: function(data){
          src = data;
        }
    });
    return src;
}