marengokid75 February 2016

Forms to Send Attachment in Email

I'm new here, but after surfing through many pages, I've came up with a form that actually works and sends an attachment to my email. However, when an attachment is not attached at the time the form is filled out, I get this instead of the Thank You Page.

Warning: file_get_contents(): Filename cannot be empty in /home/advem/public_html/careers.php on line 21

Warning: Cannot modify header information - headers already sent by (output started at /home/advem/public_html/careers.php:21) in /home/advem/public_html/careers.php on line 61

However, the email still gets sent to me when an attachment is not used. Any help is greatly appreciated.

<?php

if(!isset($_POST['submit']))
{
    //This page should not be accessed directly. Need to submit the form.
    echo "error; you need to submit the form!";
}

    if(isset($_POST['submit']))
    {

        //Deal with the email
        $to = 'email@testdesign.net';
        $subject = 'New Proof Request';
        $visitor_email = $_POST['email'];

        $message = strip_tags($_POST['message']);
        $sku = $_POST['sku'];
        $phone = $_POST['phone'];
        $name = $_POST['name'];
        $attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
        $filename = $_FILES['file']['name'];

        $boundary =md5(date('r', time())); 

        //Validate first
if(empty($name)||empty($visitor_email)) 
{
    echo "Name and email are mandatory!";
    exit;
}

        $headers = "From: email@testdesign.net\r\nReply-To: $visitor_email";
        $headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";

        $message="This is a multi-part message in MIME format.

--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"

--_2_$boundary
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit

$name
$sku
$message
$phone

--_2_$boundary-        

Answers


user1742653 February 2016

I think you should change your code on line 21 to:

    $attachment = '';
    $filename = '';
    if($_FILES["file"]["error"] != 4 && file_exists($_FILES['file']['tmp_name'])){ 
        $attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
        $filename = $_FILES['file']['name'];
    }

And on line 51 :

    if(!empty($filename)){
        --_1_$boundary
        Content-Type: application/octet-stream; name=\"$filename\" 
        Content-Transfer-Encoding: base64 
        Content-Disposition: attachment 

        $attachment
        --_1_$boundary--";
    }

I suggest you to use a library for sending email like PHPMailer, it has a lot of stuff that can be used and its easy to used.

Post Status

Asked in February 2016
Viewed 3,595 times
Voted 12
Answered 1 times

Search




Leave an answer