dimanche 24 février 2019

how to pass a value in a foreach loop in php when there is an exit in it

It is about this situation:

For copying files in a filemanagement, i use checkboxes which can be clicked. Every checkbox has its own value; the file! Like: uploads/image1.jpg or uploads/image2.jpg

All values are bind to 1 variable, $checkboxfiles (so its an array of files). For copying the checked files to another folder, i do a check if a file with the same name already exists in that folder. If yes, i show a popup with a form to confirm for overwriting or not.

The php code:

// Multiple copy and move (checkboxes)
if( isset($_POST["checkboxes_value"]) && isset($_POST["cbdestination"]) ) {

$checkboxfiles = explode("," , $_POST["checkboxes_value"]); // contains multiple values of files

foreach($checkboxfiles as $checkboxfile) {      
    $src_file = $checkboxfile;
    $fileName = basename($src_file);
    $new_dest = $_POST['cbdestination'];

    /* New path for this file */
    $dest_file = $MainFolderName.'/'. $new_dest . '/' . $fileName;

    /* check for overwriting */
    $allow = $_POST['overwrite'];
    if($allow == '') { // if not empty, the request comes from the popup and is confirmed
        if(file_exists($dest_file)) {                   
            include('alerts/file_copy_exists.php'); // includes a form to confirm overwriting                       
            exit; // i must use this and wait for confirmation
        }       
    }

    $copy = copy( $src_file, $dest_file );
    // and so on...

} // end foreach

The problem: Lets say i check 3 files, and want to copy them to another folder. 2 of them with the same name already exists in that folder. In that case, i have to use the exit; in the overwrite loop and wait for confirmation. But when i use the exit, the foreach works not anymore. The popup for the last file only appears.

When not using the exit; , 2 popups appear to confirm. But in that case, the files are already overwritten. So these popups are useless!

How can i deal with this situation?




Aucun commentaire:

Enregistrer un commentaire