I need to change the saved name of images from "Psot-id" to number 1, 2, 3+...

$save = __DIR__ . '/images/post_image_'.$post_id.'.jpg';
if(file_exists($save)){
    unlink($save);
}

How can I do this?

1 Answers

0
Miroslav Glamuzina On

You could check the directory beforehand like:

$post_id = 0;
$dir = scandir('/home/mglamuzina/test');
$filtered = array_reduce($dir, function($acc, $file) {
    preg_match_all('/post_image_([0-9]+).jpg/', $file, $lastId);
    if(isset($lastId[1]) && $lastId[1] > $acc) {
        $acc = $lastId[1];
    }
    return $acc;
}, 0);

$post_id = isset($filtered[0]) ? $filtered[0] + 1 : $post_id;
$save = __DIR__ . "/images/post_image_{$post_id}.jpg";
print_r($save);

Or if you have the number stored in a database you could retrieve the last value from there and increment it.

Hope this helps,