Help with php script for IP-webcam uploads

My IP camera will create and upload files to my webhost. The problem is the filename uses a time stamp naming convention. To be able to have pwsdashboard to work I need a file with a standard name.

My thought was to use php and a cron. For example, my camera would upload an image every 8 minutes. Then I could execute a cron every 9 minutes to scan that directory find the most recent file and rename it to something standard. After the script has run a few times, I will need to overwrite the standardized name I created. Can anyone take a look at my script and tell me what you think? I used AI to write my script since I do not know much about php writing.

<?php
function getMostRecentFile($dir) {
    $files = scandir($dir, SCANDIR_SORT_DESCENDING);
    foreach ($files as $file) {
        if ($file !== '.' && $file !== '..') {
            return $file;
        }
    }
    return null;
}

function getUniqueFileName($dir, $fileName) {
    $filePath = $dir . '/' . $fileName;
    if (!file_exists($filePath)) {
        return $fileName;
    }

    $fileInfo = pathinfo($fileName);
    $baseName = $fileInfo['filename'];
    $extension = isset($fileInfo['extension']) ? '.' . $fileInfo['extension'] : '';
    $counter = 1;

    while (file_exists($dir . '/' . $baseName . '_' . $counter . $extension)) {
        $counter++;
    }

    return $baseName . '_' . $counter . $extension;
}

$directory = '/path/to/your/directory';
$recentFile = getMostRecentFile($directory);

if ($recentFile) {
    $newName = 'new_filename.txt'; // Change this to your desired new name
    $uniqueName = getUniqueFileName($directory, $newName);
    $oldPath = $directory . '/' . $recentFile;
    $newPath = $directory . '/' . $uniqueName;

    if (rename($oldPath, $newPath)) {
        echo "The file has been renamed to: " . $uniqueName;
    } else {
        echo "Error renaming the file.";
    }
} else {
    echo "No files found in the directory.";
}
?>

I also don’t know much about php but I have tried running the script on my computer which can execute php files.

The script apparently finds the newest file in the directory specified in line 30 and renames it to the name specified in line 34.
It seems fine.

A small problem is that if the file with the name e.g.
newfile.jpg
exists, the newest file is next renamed to
newfile_1.jpg etc.
We just want it to be given the same name every time, i.e. that the file newfile.jpg must be overwritten.

I’ve only looked at the script on my phone screen which isn’t the best way to view it. It looks like it should work, although I see a potential problem. If the newest file in the directory isn’t the webcam image then I think it might break, or more exactly you might find you’re displaying something other than you wanted to.

I’ll have another look later this morning when I’m on my laptop to see if I can suggest how to improve it.

A couple more issues that I can see:

  • scandir() sorts by filename so you’re not necessarily finding the latest uploaded file. It depends on how the filenames are constructed and whether the filenames will always sort alphabetically to leave the newest one listed first.
  • If you upload every 8 minutes and run the cron job every 9 minutes then you’re eventually going to have two uploads between cron jobs. The problem there is that you’ll eventually build up a lot of uploads that aren’t renamed that will sit there forever, or until you manually delete them. You probably need to add a tidy up function to remove older files that will never be used.

PHP rename() overwrites an existing file with the same name so this isn’t a problem.

The first time I run the script, the response looks like this

The second time I run the script the response looks like this

I don’t understand why that’s happening. The official PHP manual says it overwrites - PHP: rename - Manual

1 Like

Thanks everyone for helping me. It looks like maybe the overwrite function is not working as I had hoped?

I don’t understand either, but here is a script that finds the newest .jpg file in a folder and renames it to ny.jpg (Danish for new.jpg).
If ny.jpg already exists, it will be overwritten.

It must be usable if a camera uploads an image with the time as name, but you must use a specific name.

To me it seems fine

<?php
function find_and_rename_newest_jpg($directory) {
    // Sørg for at stien slutter med et backslash
    $directory = rtrim($directory, '/') . '/';

    // Find alle .jpg-filer i mappen = find all .jpg files
    $files = glob($directory . '*.jpg');

    // Hvis der er mindst Ă©n .jpg-fil = if there is a .jpg
    if (!empty($files)) {
        // Sortér filerne efter oprettelsestid (nyest først)
        usort($files, function($a, $b) {
            return filemtime($b) - filemtime($a);
        });

        // Hent navnet pĂĄ den nyeste fil = find the name of the newest file
        $newest_file = $files[0];

        // Omdøb filen til "ny.jpg" i samme mappe Omdøb = rename
        $new_file = $directory . 'ny.jpg';
        rename($newest_file, $new_file);

        // Slet den originale fil = delete the original file
      #  unlink($newest_file); # set by MOGENS file do not exist
    }
}

// Eksempel pĂĄ brug:
$mappe = 'testbilleder/'; // Erstat med den ønskede mappe
find_and_rename_newest_jpg($mappe);
?>

Another version (man made this time) with added debug code.

Please test it and if sufficient I will add it with a pdf to the current updates folder.

rename_image.php.zip (1.8 KB)

The scripts checks the webcam-images for old files overwriting the last renamed file.


The “problems” as discussed above:

Linux:
The folder settings need to allow renaming if the same file already exists.

On windows systems:
The renaming will not work if the same file already exists.

Wim

Thanks for the code Wim. I was going to try to create something this evening so you’ve saved me some work :smiley:

OK so questions I plan to place this script on my godaddy host which I believe is linux.

Can you explain $check_filename more?

My camera creates a file like this T24092418593100.jpg so what that means is
T I don’t know
24 year
0924 month/day
18593100
six pm, fifty-nine minutes and thirty-one seconds zero one hundreds of a second.

So at this point, I need to have that script run thru a cron somehow, either thru my host or if possible Weather display?

What kind of camera are you using? My FOSCAM FTP’s in the same manner, but i found i can send it cgi commands to retrieve a picture. I have WD’s moviemaker executing that command to pull to a standardized filename (yard.jpg). Moviemaker then creates the timestamped files and builds the time lapse movie. WD’s FTP functions uploads the still snapshots and the daily movie into PWSwd without the need for solving the problem you have.

Maybe your camera has some external commands that will operate in a similar fashion.

Either way, good luck to achieve your goal.

Regards,

Jim

1 Like

OK this is interesting. I am very novice at this. So please be patient with me.

I ended up going with this solution since the tools were built into the software I already own, and I was probably in over my head playing with php. Thank you everyone.