I have a form where I want users to be able to select an image to upload. The image gets temporarily uploaded to the wp-content/uploads folder, is attached to the e-mail and then is destroyed.

Right now, the form is submitting and I can see that the image is being processed in the response headers, but there is no image included in the e-mail and there is no image file in the uploads folder. Does anyone see any issues with this code?

Here’s the form:

<form id="shareForm" action="<?php echo get_template_directory_uri(); ?>/library/file-form.php" method="post" enctype="multipart/form-data">
    <input type="text" id="name" name="name" placeholder="Name" />
    <textarea rows="4" cols="50" name="message" id="message" placeholder="Message"></textarea>
    <input type="file" id="photo" name="photo" class="upload">
    <input type="submit" name="submit" value="Submit">

And here’s my PHP mail script:

    require( '../../../../wp-load.php' );
    $name = $_POST["name"];
    $message = $_POST["message"];
    $fName = str_replace(array(' ', ',', ''' ), '-');
    $date = new DateTime(null, new DateTimeZone('America/Chicago'));
    $myDate = $date->format("m/d/Y H:i");
    $fileDate = $date->format("m-d-Y");
    $homeUrl = home_url('/');
    if($_FILES["file"]["type"] != ""){
        $allowedExts = array("jpg", "png", "gif");
        $extension = end(explode(".", $_FILES["file"]["name"]));
        $newFileName = $fName . $fileDate."." .$extension;
        if ($_FILES["file"]["error"] > 0) {
            $myPath =  $homeUrl . 'share/?upload=error';
            wp_redirect($myPath); exit;     
        } else {
            move_uploaded_file($_FILES["file"]["tmp_name"], WP_CONTENT_DIR . "/uploads/user-submitted/" . $newFileName);
    $to = 'my@email.com';
    $subject = $fName . " submitted a photo";
    $message = "Date: " . $myDate . " EST n";
    $message .= "Message:  " .$message. "n";
    $attachments = array(WP_CONTENT_DIR . "/uploads/user-submitted/".$newFileName); 
    $headers[] = 'From: Photo Submissions <my@email.com>';
    wp_mail( $to, $subject, $message, $headers, $attachments);
    unlink(WP_CONTENT_DIR . "/uploads/user-submitted/" . $newFileName);
    $myPath =  $homeUrl . 'share/?upload=success';

Read more here: wp_mail file attachment not being placed in upload folder?


If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Related Wordpress search:

, , , ,

Wordpress related questions and answers: