PHP复制+每个文件覆盖对话框


PHP copy + overwrite dialog per file

我正在用PHP+AAJAX开发一个系统,可以将文件从服务器上的一个文件夹复制到服务器上的另一个文件夹。

我的问题是,当我试图将一个文件夹复制到另一个已经有一些同名文件的文件夹时。

在这种情况下,我想向用户显示一个弹出窗口,以确认他是否想覆盖每个文件。

我怎么能那样做?启动复制后,如何等待用户对每个对话框的响应?

顺便问一下,是使用linux的cp命令更好,还是使用PHP的unlinkrmdir更好?

我认为您应该将流程分为几个部分:

  1. 检查是否存在冲突文件
  2. 如果存在一些冲突文件,请将它们列出给用户,并要求确认(对话框)
  3. 如果没有碰撞,或者用户确认同意覆盖目标文件,复制文件

如果您想询问每个文件,请询问每个文件(一个带有复选框的对话框或多个对话框)的确认信息。一旦用户确认(或不确认)每次覆盖,请复制文件。

您可以使用copy()函数将文件从一个文件夹复制到另一个

$sourceFilePath = '/path/to/source/file.jpg';
$destinationFilePath = '/path/to/destination/file.jpg';
if (copy($sourceFilePath, $destinationFilePath)) {
    // File copied successfully
} else {
    // Error occurred during file copy
}

接下来,您可以添加一个AJAX确认对话框,提示用户输入目标文件夹中已经存在的每个文件。

function copyFile(source, destination) {
    // Send an AJAX request to copy the file
    $.ajax({
        url: 'copy_file.php',
        type: 'POST',
        data: {
            source: source,
            destination: destination
        },
        success: function(response) {
            if (response === 'overwrite') {
                // Display a confirmation dialog
                if (confirm('A file with the same name already exists. Do you want to overwrite it?')) {
                    // User confirmed, proceed with the copy
                    copyFile(source, destination + '&overwrite=true');
                } else {
                    // User canceled, do not overwrite
                    // Handle accordingly
                }
            } else {
                // File copied successfully or other response handling
                // Handle accordingly
            }
        },
        error: function() {
            // Error handling
            // Handle accordingly
        }
    });
}

在您的PHP脚本(copy_file.PHP)中,您可以处理复制过程,检查目标文件是否已经存在,并发回响应。

$sourceFilePath = $_POST['source'];
$destinationFilePath = $_POST['destination'];
if (file_exists($destinationFilePath)) {
    // File already exists, send overwrite response
    echo 'overwrite';
} else {
    // Copy the file
    if (copy($sourceFilePath, $destinationFilePath)) {
        // File copied successfully
        echo 'success';
    } else {
        // Error occurred during file copy
        echo 'error';
    }
}