File upload from front-end form (as attachment) not working

The question:

I have a front-end form that is supposed to allow the user to upload a CV which is then sent along with the rest of the form as an attachment. To do so I have used wp_handle_upload() like so:

if ($_FILES) {

if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
    if ( $movefile ) {
        echo "File is valid, and was successfully uploaded.n";
        var_dump( $movefile);
    } else {
        echo "Possible file upload attack!n";
    } 
}

The form is then sent with wp_mail after checking for errors: ($receiver_email, $subject, $body, $headers are all fine and can be seen here

$attachments = $uploadedfile;

if (wp_mail($receiver_email, $subject, $body, $headers, $attachments)) {
        
    $jobs_email_sent = true;

} else {
    $jobs_email_sent_error = true;
}

However I am getting the following from var_dump($movefile) when I submit the form.

File is valid, and was successfully uploaded.
array(1) {
 ["error"]=>
 string(212) "File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini."
}

And natually no attachment with the email. I checked php.ini and file_uploads is indeed on and upload_max_filesize is 128M. I have tried to add a pdf and a jpg file which are both quite small.

I would greatly appreciate any insight as to what I’m doing wrong here.

UPDATE just read that for wp_mail() the file path has to be fully specified as in $attachments = array(WP_CONTENT_DIR . '/uploads/file_to_attach.zip');
which should be returned in wp_handle_upload(); as file.

When I var_dump($_FILES) I get:

array(1) {
  ["upload_file"]=>
  array(5) {
    ["name"]=>
    string(5) "3.jpg"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(14) "/tmp/php3aeSzD"
    ["error"]=>
    int(0)
    ["size"]=>
    int(53262)
  }
 }

My file is named 3.jpg.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Untested but I am pretty sure this is the issue:

You are trying to attach $uploadedfile to the email. You’ve set $uploadedfile to $_FILES['file']. That is a very temporary file/file location.

Once you use wp_handle_upload you want to be using $movefile instead. If you look at the Codex entry for that function you can see that you need (probably) $movefile['file'])


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment