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.

PHP Submitting form in PHP to email

Edrol97

Silver Coder
Hi all, am very new and inexperienced with PHP. I have this code for submitting a form to email that I asked ChatGPT to write (may or may not be a fatal flaw), and I can't seem to get it to work. Any and all help appreciated. Note, unless it's not obvious from what I've said, I'm a complete novice. Thanks, Eliot.

PHP:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Collect form data and sanitize it
    $name = htmlspecialchars(trim($_POST['name']));
    $email = htmlspecialchars(trim($_POST['email']));
    $telephone = htmlspecialchars(trim($_POST['telephone']));
    $piece = htmlspecialchars(trim($_POST['piece']));
    $comments = htmlspecialchars(trim($_POST['comments']));
    if (!empty($name) && !empty($email) && !empty($telephone) && !empty($piece)) {
        echo "<h2>Form Submission Successful!</h2>";
        echo "<p><strong>Name:</strong> $name</p>";
        echo "<p><strong>Email:</strong> $email</p>";
        echo "<p><strong>Telephone:</strong> $telephone</p>";
        echo "<p><strong>Piece</strong> $piece</p>";
        echo "<p><strong>Size:</strong> $comments</p>";
    } else {
        echo "<h2>Error: Please fill out all required fields.</h2>";
    }
} else {
    echo "<h2>Error: Invalid request method.</h2>";
}
 $to = "[email protected]";  // Replace with your actual email address
 $subject = "New Form Submission";
 $message = "
 Name: $name\n
 Email: $email\n
 Telephone: $telephone\n
 Piece: $piece\n
 Size: $comments
 ";
 $headers = "From: $email";  // Sender's email
 // Send the email
 if (mail($to, $subject, $message, $headers)) {
     echo "<h2>Thank you! Your form has been submitted successfully.</h2>";
 } else {
     echo "<h2>Sorry, there was an issue sending your form. Please try again later.</h2>";
 }
} else {
 echo "<h2>Error: Please fill out all required fields.</h2>";
}
} else {
echo "<h2>Error: Invalid request method.</h2>";
}
?>
 
Last edited:
It looks like you're trying to create a simple PHP form submission script. There are a few issues in your code that may be causing it not to work as expected. Let's go through them step by step.

1. Form Handling Logic: The structure of your conditional statements is a bit off. You have nested else statements that could be simplified.

2. Email Sending Logic: The email functionality should be placed in the right spot to ensure it only runs after you validate the form data.

3. HTML Structure: Ensure that your form is correctly set up to use the POST method, and that the form fields have the correct names corresponding to the ones you're using in your PHP code.

PHP:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Collect form data and sanitize it
    $name = htmlspecialchars(trim($_POST['name']));
    $email = htmlspecialchars(trim($_POST['email']));
    $telephone = htmlspecialchars(trim($_POST['telephone']));
    $piece = htmlspecialchars(trim($_POST['piece']));
    $comments = htmlspecialchars(trim($_POST['comments']));

    // Check if required fields are filled
    if (!empty($name) && !empty($email) && !empty($telephone) && !empty($piece)) {
        // Prepare email
        $to = "[email protected]"; // Replace with your actual email address
        $subject = "New Form Submission";
        $message = "Name: $name\nEmail: $email\nTelephone: $telephone\nPiece: $piece\nComments: $comments";
        $headers = "From: $email";

        // Send the email
        if (mail($to, $subject, $message, $headers)) {
            echo "<h2>Thank you! Your form has been submitted successfully.</h2>";
        } else {
            echo "<h2>Sorry, there was an issue sending your form. Please try again later.</h2>";
        }
    } else {
        echo "<h2>Error: Please fill out all required fields.</h2>";
    }
} else {
    echo "<h2>Error: Invalid request method.</h2>";
}
?>

### Key Changes:
  • Moved the email sending logic to only execute after the form data validation is successful.
  • Simplified the structure of the if statements to make it clearer.
  • Ensured that the HTML headers are only echoed once, depending on the success or failure of the operation.

### HTML Form Example:
Make sure you have a corresponding HTML form like this:

HTML:
<form method="POST" action="">

    <input type="text" name="name" placeholder="Your Name" required>

    <input type="email" name="email" placeholder="Your Email" required>

    <input type="tel" name="telephone" placeholder="Your Telephone" required>

    <input type="text" name="piece" placeholder="Piece of Work" required>

    <textarea name="comments" placeholder="Any comments..."></textarea>

    <button type="submit">Submit</button>

</form>

### Additional Notes:
  • Make sure your server is configured to send emails (some local development environments might not support the mail() function).
  • Always validate and sanitize user input for security purposes.
  • Consider using a library like PHPMailer for more robust email handling.

Feel free to ask if you need further assistance!
 
Hey Eliot! You're on the right track here—it's awesome you're diving into PHP! 😄

Think of this like sending a letter. You've written it, put a stamp on it, but instead of handing it to the mail carrier, you've just left it sitting on the kitchen table. 😂

The problem here is that mail() doesn’t always work out of the box, especially on local servers. It's like trying to send your letter without a functioning post office!

What you'll need is an email service to actually send the email, and one of the most common ways is to use a tool like PHPMailer or SwiftMailer, which does the heavy lifting of logging into your email and sending it properly.

You can follow these steps:

  1. Install PHPMailer (or another library) using Composer.
  2. Set it up to authenticate with your email account (e.g., Gmail uses SMTP).
  3. Then, instead of mail(), use the mailer library to send your email.
Let me know if you need more help setting that up, or I can guide you through the PHPMailer install!
 
Back
Top Bottom