phpwordpressuploadcustom-wordpress-pagesfine-uploader

Failed to upload a file in wordpress


I've got trouble uploading a file, this code below should echo something in any case right ? but after submitting the form i don't get any message echoed, though the mail is sent. Can anyone help me with this problem ?

if(!empty($_FILES['file'])){

    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";
                        }
                    wp_mail($emailTo, $subject, $body, $headers, $attachments);
            #$hasError = true;
    }   

UPDATE
i've changed the code a little bit, how it goes as follow:

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

but i get this error instead

File is valid, and was successfully uploaded. exception 'phpmailerException' with message 'Could not access file: 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.'

What i've tried to solve this issue


Solution

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

    $attachments returned is an array containing file, url and type. You need the file only for attachment.