PHP - Upload file to different folders

Asked

Viewed 742 times

3

I have to make a PHP script that sends a single upaged file to several folders (listed in the server root dynamically). The problem is that the first upload is done smoothly, then I can’t send to the other folders.

EXEMPLO:

$dir = $_SERVER["DOCUMENT_ROOT"];
$scandir = scandir($dir);

$pastas = array();
foreach ($scandir as $pasta) {
    if($pasta == "." || $pasta == ".." || $pasta == ".htaccess" || $pasta == "default.htmlx" || $pasta == "error_log") {

    } else {
        $pastas[] = $pasta;
    }
}

if(isset($_POST['upload'])) {
    foreach ($pastas as $key => $pasta) {
        $arquivo = $_FILES['file']['name'];
        $file_tmp =$_FILES['file']['tmp_name'];

        $desired_dir = $dir."/".$pasta."/sistema/engine/";
        $caminho = $desired_dir.$arquivo;       

        $upload = move_uploaded_file($file_tmp, $caminho);
        if(!$upload) {
            echo "Erro ao realizar upload em: ".$caminho;
            exit(0);      
        }
    }

    echo "Deu certo.";
    exit(0);
}

Does anyone know where I might be missing or if there are any upload restrictions on foreach?

1 answer

4


When you use move_uploaded_file() you take the file that was saved temporarily and move it to another place, if you use it again, it will move the file again but always a single file. To create another file use copy, however, use move_upload_file() first to have the checks it does. Example:

move_uploaded_file($arquivo_temp, $destino1);
copy($destino1, $destino2);

I hope it helps.

  • Excellent, Lucas! Gave straight. Thanks for the help and clarification.

  • Guy 4 years later and his answer saved me!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.