Skip to content
Advertisement

PHP – Can’t move file

I’m looking for sending attachment by using PHPMailer. To send the mail I need to store it so I create a folder automatically during the process, and I want to save those uploaded files inside this folder.

The folder is created correctly but the file is not moved inside the folder. I’ve tried by using move_uploaded_fileand copy but this not work.

if some could tell me what’s wrong here…

if (!empty($_POST['uploaded_file']) & isset($_POST['uploaded_file'])){
                // Creatinf folder ploads if not exist
                $path_upload = "uploads";
                createFolderIfNotExist($path_upload);
                // create folder with company name if not exist
                $path_file = $path_upload . '/mail_upload';
                createFolderIfNotExist($path_file);
                // create folder with date + id_user
                $path_file .= "/".date("Ymd").$user->getId();
                createFolderIfNotExist($path_file);
                foreach ($_POST['uploaded_file'] as $attachment2) {

                    move_uploaded_file($attachment2, "../".$path_file."/".$attachment2);
                    $pj = "/".$path_file."/".$attachment2;
                    // Attachments
                    $mail->addAttachment($pj);    // Optional name
                }
            }

Thank you for you help

Advertisement

Answer

The first problem is that you’re handling uploaded files with $_POST. It should be $_FILES.

The second problem is that you should use tmp_name index in your move_uploaded_file function.

The third problem is that your foreach loop is not correct if you’re uploading multiple files.

And it seems like you’re uploading files outside of $path_file directory. So, try this:

if (!empty($_FILES) & isset($_FILES['uploaded_file']['tmp_name'])) {
    // Create folder uploads if not exists
    $path_upload = 'uploads';
    createFolderIfNotExist($path_upload);
    // create folder with company name if not exists
    $path_file = $path_upload . '/mail_upload';
    createFolderIfNotExist($path_file);
    // create folder with date + id_user
    $path_file .= '/' . date('Ymd') . $user->getId();
    createFolderIfNotExist($path_file);
    foreach ($_FILES['uploaded_file']['name'] as $key => $attachment2) {
        move_uploaded_file($_FILES['uploaded_file']['tmp_name'][$key], $path_file . '/' . $attachment2);
        $pj = '/' . $path_file . '/' . $attachment2;
        // Attachments
        $mail->addAttachment($pj);    // Optional name
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement