Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Help adding attachment option to contact form

Hi all,

I'm currently trying to add an attachment option to a php contact form. The form itself works fine so was hoping someone would be able to help me with the required code to add the attachment option to it.


HTML:
<form id="contactForm" role="form" method="post" action="php/contact.php">

                  <div class="form-group">

                    <label class="sr-only" for="name">Name</label>

                    <input class="form-control" type="text" id="name" name="name" placeholder="Your Name*" required="required" data-validation-required-message="Please enter your name."/>

                    <p class="help-block text-danger"></p>

                  </div>

                  <div class="form-group">

                    <label class="sr-only" for="email">Email</label>

                    <input class="form-control" type="email" id="email" name="email" placeholder="Your Email*" required="required" data-validation-required-message="Please enter your email address."/>

                    <p class="help-block text-danger"></p>

                  </div>

                  <div class="form-group">

                    <textarea class="form-control" rows="7" id="message" name="message" placeholder="Your Message*" required="required" data-validation-required-message="Please enter your message."></textarea>

                    <p class="help-block text-danger"></p>

                  </div>

                

                  <div class="text-center">

                    <button class="btn btn-block btn-round btn-d" id="cfsubmit" type="submit">Submit</button>

                  </div>

                </form>

--


PHP:
<?php



    $errors = array();



    // Check if name has been entered

    if (!isset($_POST['name'])) {

        $errors['name'] = 'Please enter your name';

    }



    // Check if email has been entered and is valid

    if (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {

        $errors['email'] = 'Please enter a valid email address';

    }



    //Check if message has been entered

    if (!isset($_POST['message'])) {

        $errors['message'] = 'Please enter your message';

    }



    $errorOutput = '';



    if(!empty($errors)){



        $errorOutput .= '<div class="alert alert-danger alert-dismissible" role="alert">';

         $errorOutput .= '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';



        $errorOutput  .= '<ul>';



        foreach ($errors as $key => $value) {

            $errorOutput .= '<li>'.$value.'</li>';

        }



        $errorOutput .= '</ul>';

        $errorOutput .= '</div>';



        echo $errorOutput;

        die();

    }







    $name = $_POST['name'];

    $email = $_POST['email'];

    $message = $_POST['message'];

    $from = $email;

    $to = 'MY EMAIL ADDRESS';

    $subject = 'Subject';



    $body = "From: $name\n E-Mail: $email\n Message:\n $message";



    $headers = "From: ".$from;





    //send the email

    $result = '';

    if (mail ($to, $subject, $body, $headers)) {

        $result .= '<div class="alert alert-success alert-dismissible" role="alert">';

         $result .= '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';

        $result .= 'Thank You! I will be in touch';

        $result .= '</div>';



        echo $result;

        die();

    }



    $result = '';

    $result .= '<div class="alert alert-danger alert-dismissible" role="alert">';

    $result .= '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';

    $result .= 'Something bad happened during sending this message. Please try again later';

    $result .= '</div>';



    echo $result;

If you need anything else please let me know. I'll be very grateful for any help.

Thanks
Stuart
 
Last edited by a moderator:
Hi all,

I'm currently trying to add an attachment option to a php contact form. The form itself works fine so was hoping someone would be able to help me with the required code to add the attachment option to it.


HTML:
<form id="contactForm" role="form" method="post" action="php/contact.php">

                  <div class="form-group">

                    <label class="sr-only" for="name">Name</label>

                    <input class="form-control" type="text" id="name" name="name" placeholder="Your Name*" required="required" data-validation-required-message="Please enter your name."/>

                    <p class="help-block text-danger"></p>

                  </div>

                  <div class="form-group">

                    <label class="sr-only" for="email">Email</label>

                    <input class="form-control" type="email" id="email" name="email" placeholder="Your Email*" required="required" data-validation-required-message="Please enter your email address."/>

                    <p class="help-block text-danger"></p>

                  </div>

                  <div class="form-group">

                    <textarea class="form-control" rows="7" id="message" name="message" placeholder="Your Message*" required="required" data-validation-required-message="Please enter your message."></textarea>

                    <p class="help-block text-danger"></p>

                  </div>

               

                  <div class="text-center">

                    <button class="btn btn-block btn-round btn-d" id="cfsubmit" type="submit">Submit</button>

                  </div>

                </form>

--


PHP:
<?php



    $errors = array();



    // Check if name has been entered

    if (!isset($_POST['name'])) {

        $errors['name'] = 'Please enter your name';

    }



    // Check if email has been entered and is valid

    if (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {

        $errors['email'] = 'Please enter a valid email address';

    }



    //Check if message has been entered

    if (!isset($_POST['message'])) {

        $errors['message'] = 'Please enter your message';

    }



    $errorOutput = '';



    if(!empty($errors)){



        $errorOutput .= '<div class="alert alert-danger alert-dismissible" role="alert">';

         $errorOutput .= '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';



        $errorOutput  .= '<ul>';



        foreach ($errors as $key => $value) {

            $errorOutput .= '<li>'.$value.'</li>';

        }



        $errorOutput .= '</ul>';

        $errorOutput .= '</div>';



        echo $errorOutput;

        die();

    }







    $name = $_POST['name'];

    $email = $_POST['email'];

    $message = $_POST['message'];

    $from = $email;

    $to = 'MY EMAIL ADDRESS';

    $subject = 'Subject';



    $body = "From: $name\n E-Mail: $email\n Message:\n $message";



    $headers = "From: ".$from;





    //send the email

    $result = '';

    if (mail ($to, $subject, $body, $headers)) {

        $result .= '<div class="alert alert-success alert-dismissible" role="alert">';

         $result .= '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';

        $result .= 'Thank You! I will be in touch';

        $result .= '</div>';



        echo $result;

        die();

    }



    $result = '';

    $result .= '<div class="alert alert-danger alert-dismissible" role="alert">';

    $result .= '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';

    $result .= 'Something bad happened during sending this message. Please try again later';

    $result .= '</div>';



    echo $result;

If you need anything else please let me know. I'll be very grateful for any help.

Thanks
Stuart

Hello,

Thanks for making a thread. Please make sure when you are posting code to use BBCode. I have updated the post but please follow this guide in the future.

Lets dive into adding an attachement option to the form.

Updated HTML Code:


HTML:
<form id="contactForm" role="form" method="post" action="php/contact.php" enctype="multipart/form-data">
    <div class="form-group">
        <label class="sr-only" for="name">Name</label>
        <input class="form-control" type="text" id="name" name="name" placeholder="Your Name*" required="required"/>
    </div>

    <div class="form-group">
        <label class="sr-only" for="email">Email</label>
        <input class="form-control" type="email" id="email" name="email" placeholder="Your Email*" required="required"/>
    </div>

    <div class="form-group">
        <textarea class="form-control" rows="7" id="message" name="message" placeholder="Your Message*" required="required"></textarea>
    </div>

    <!-- Added the code for File Upload Input -->
    <div class="form-group">
        <label for="attachment">Attach a file (Optional)</label>
        <input type="file" class="form-control" id="attachment" name="attachment">
    </div>

    <div class="text-center">
        <button class="btn btn-block btn-round btn-d" id="cfsubmit" type="submit">Submit</button>
    </div>
</form>

Updated PHP Code:


PHP:
<?php

$errors = array();

// Check if name has been entered
if (!isset($_POST['name'])) {
    $errors['name'] = 'Please enter your name';
}

// Check if email has been entered and is valid
if (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $errors['email'] = 'Please enter a valid email address';
}

// Check if message has been entered
if (!isset($_POST['message'])) {
    $errors['message'] = 'Please enter your message';
}

// File handling
$attachment_path = "";
$attachment_name = "";
if (!empty($_FILES['attachment']['name'])) {
    $allowed_extensions = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'];
    $file_extension = pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION);

    if (!in_array(strtolower($file_extension), $allowed_extensions)) {
        $errors['attachment'] = 'Invalid file type. Allowed types: JPG, PNG, PDF, DOC, DOCX.';
    } elseif ($_FILES['attachment']['size'] > 5 * 1024 * 1024) { // 5MB file size limit
        $errors['attachment'] = 'File size must be less than 5MB.';
    } else {
        $attachment_path = $_FILES['attachment']['tmp_name'];
        $attachment_name = $_FILES['attachment']['name'];
    }
}

// Handle errors
if (!empty($errors)) {
    $errorOutput = '<div class="alert alert-danger" role="alert"><ul>';
    foreach ($errors as $error) {
        $errorOutput .= "<li>$error</li>";
    }
    $errorOutput .= '</ul></div>';
    echo $errorOutput;
    die();
}

// Get form data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
$to = 'ENTER YOUR EMAIL ADDRESS HERE';
$subject = 'New Contact Form Submission';

// Create email headers
$boundary = md5(time()); // Unique boundary for MIME email
$headers = "From: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";

// Create email body with attachment
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=UTF-8\r\n";
$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$body .= "From: $name ($email)\n\nMessage:\n$message\r\n";

// Attach file if uploaded
if (!empty($attachment_path)) {
    $file_content = file_get_contents($attachment_path);
    $encoded_file = chunk_split(base64_encode($file_content));

    $body .= "--$boundary\r\n";
    $body .= "Content-Type: application/octet-stream; name=\"$attachment_name\"\r\n";
    $body .= "Content-Disposition: attachment; filename=\"$attachment_name\"\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= "$encoded_file\r\n";
}

// Close email body
$body .= "--$boundary--";

// Send the email
if (mail($to, $subject, $body, $headers)) {
    echo '<div class="alert alert-success">Thank You! Your message has been sent.</div>';
} else {
    echo '<div class="alert alert-danger">Something went wrong. Please try again later.</div>';
}
?>

The updated code should work for what you need to do. Let us know if you run into anymore issues or need some assistance.
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom