-3

i know this question is asked before but i cant figure out how to get this to work. I have a function that triggers whenever i delete a post. It will then move the file to a existing folder on the server. what i would like for it to do is to check if there is already a file with the same name in this folder. if this file exist it should append a number to this file. for example if file 1234.jpg exist it should rename the file that i want to move to 1234-1.jpg.

The code i have so far is:

add_action('before_delete_post', function ($id) {

    $rs_image_path = "/var/www/html/wp-content/uploads/hexon/";
    $rs_image_dest_path = "/var/www/html/wp-content/uploads/wpallimport/files/images/";
    // $rs_image_filenames="30946280-1.JPG,30946280-2.JPG,30946280-3.JPG,30946280-4.JPG";
    // $rs_image_klantnummer = "1232";
    $rs_image_filenames = get_field('afbeeldingen_bestandsnamen', $id);
    $rs_image_klantnummer = get_field('hexon_klantnummer', $id);

    $variableAry = explode(", ", $rs_image_filenames);
    foreach ($variableAry as $rs_image_url) {
        /* Store the path of source file */
        $filePath = $rs_image_path . "" . $rs_image_klantnummer . "/" . $rs_image_url;

        /* Store the path of destination file */
        $destinationFilePath = $rs_image_dest_path . "" . $rs_image_klantnummer . "/" . $rs_image_url;

        /* Move Files */
        if (!file_exists($filePath) || !is_readable($filePath)) {

            // some error handling here
        } else {
            $b = !rename($filePath, $destinationFilePath);
        }
    }
}
);

  • Have you tried coding what you are asking for? There we have no trace of an attempt. – Juan Nov 04 '22 at 15:39
  • HI Juan, yes ofcourse, i just shared the source code that was working before i started tweaking and messing stuff up ;). At the moment im still trying some stuff. I will update the code as soon as i have an update. – user2958073 Nov 04 '22 at 16:00

1 Answers1

-1

How about this?

$n = '';
while (file_exists($destinationFilePath.$n) || !rename($filePath, $destinationFilePath.$n)) {
  $n++;
  // escape loop
  if ($n > 100) {
    throw new Exception('Error saving');
  }
}
$destinationFilePath .= $n;
Rob Eyre
  • 717
  • 7
  • The suffix (-1, -2, -3) is not at the end of the file, but in the middle (i.e. before the file extension), right ? – Ken Lee Nov 04 '22 at 15:54