treehouse : what would you like to learn today?
Web Design Web Development iOS Development

help with php form email tutorial from css-tricks

  • Hey all,
    I appreciate anyone's ability to help point me in the right direction. I've tried modifying the form created at the tutorial for sending html emails with php, and have hit a bit of a hiccup.

    my dev page is here

    Upon submission of the form, I'm getting the 'Hack-Attempt detected' error message. I've combed through my field names and don't see anything missing or mis-spelled. If someone would be able to point me in the right direction as to what is wrong in my code, I would really appreciate it.


  • Can you post your PHP code please? :-)

  • <?php

    session_start();

    function getRealIp() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) { //check ip from share internet
    $ip=$_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { //to check ip is pass from proxy
    $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
    $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
    }

    function writeLog($where) {

    $ip = getRealIp(); // Get the IP from superglobal
    $host = gethostbyaddr($ip); // Try to locate the host of the attack
    $date = date("d M Y");

    // create a logging message with php heredoc syntax
    $logging = <<<LOG
    \n
    << Start of Message >>
    There was a hacking attempt on your form. \n
    Date of Attack: {$date}
    IP-Adress: {$ip} \n
    Host of Attacker: {$host}
    Point of Attack: {$where}
    << End of Message >>
    LOG;
    // Awkward but LOG must be flush left

    // open log file
    if($handle = fopen('hacklog.log', 'a')) {

    fputs($handle, $logging); // write the Data to file
    fclose($handle); // close the file

    } else { // if first method is not working, for example because of wrong file permissions, email the data

    $to = 'myemail@email.com';
    $subject = 'HACK ATTEMPT';
    $header = 'From: from@company.com';
    if (mail($to, $subject, $logging, $header)) {
    echo "Sent notice to admin.";
    }

    }
    }

    function verifyFormToken($form) {

    // check if a session is started and a token is transmitted, if not return an error
    if(!isset($_SESSION[$form.'_token'])) {
    return false;
    }

    // check if the form is sent with token in it
    if(!isset($_POST['token'])) {
    return false;
    }

    // compare the tokens against each other if they are still the same
    if ($_SESSION[$form.'_token'] !== $_POST['token']) {
    return false;
    }

    return true;
    }

    function generateFormToken($form) {

    // generate a token from an unique value, took from microtime, you can also use salt-values, other crypting methods...
    $token = md5(uniqid(microtime(), true));

    // Write the generated token to the session variable to check it against the hidden field when the form is sent
    $_SESSION[$form.'_token'] = $token;

    return $token;
    }

    // VERIFY LEGITIMACY OF TOKEN
    if (verifyFormToken('form1')) {

    // CHECK TO SEE IF THIS IS A MAIL POST
    if (isset($_POST['req-email'])) {

    // Building a whitelist array with keys which will send through the form, no others would be accepted later on
    $whitelist = array('token','req-name','req-company','req-email','phone','domino','hitachi','vldeo','markemimaje','diagraph','otherequipment','thermal','hotstamps','labels','inkjet','othercoding','upgrade','othervalues','codequality','price','integration','postsales','interest');

    // Building an array with the $_POST-superglobal
    foreach ($_POST as $key=>$item) {

    // Check if the value $key (fieldname from $_POST) can be found in the whitelisting array, if not, die with a short message to the hacker
    if (!in_array($key, $whitelist)) {

    writeLog('Unknown form fields');
    die("Hack-Attempt detected. Please use only the fields in the form");

    }
    }

    // PREPARE THE BODY OF THE MESSAGE

    $message = '<html><body>';
    $message .= '<h1>dominovseries.com Contest Submission</h1>';
    $message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
    $message .= "<tr style='background: #eee;'><td colspan='2'><strong>Contact Information</strong></td></tr>";
    $message .= "<tr><td><strong>Name:</strong> </td><td>" . strip_tags($_POST['req-name']) . "</td></tr>";
    $message .= "<tr><td><strong>Company:</strong> </td><td>" . strip_tags($_POST['req-company']) . "</td></tr>";
    $message .= "<tr><td><strong>Email:</strong> </td><td>" . strip_tags($_POST['req-email']) . "</td></tr>";
    $message .= "<tr><td><strong>Phone:</strong> </td><td>" . strip_tags($_POST['phone']) . "</td></tr>";
    $message .= "<tr style='background: #eee;'><td colspan='2'><strong>Survey Feedback</strong></td></tr>";
    $message .= "<tr><td><strong>Equipment Supplier:</strong> </td><td>" . strip_tags($_POST['domino']) . "</td></tr>";
    $message .= "<tr><td><strong></td><td>" . strip_tags($_POST['vldeo']) . "</td></tr>";
    $message .= "<tr><td><strong></td><td>" . strip_tags($_POST['hitachi']) . "</td></tr>";
    $message .= "<tr><td><strong></td><td>" . strip_tags($_POST['markemimaje']) . "</td></tr>";
    $message .= "<tr><td><strong></td><td>" . strip_tags($_POST['diagraph']) . "</td></tr>";
    $message .= "<tr><td><strong>Other Equipment Suppliers:</strong> </td><td>" . strip_tags($_POST['otherequipment']) . "</td></tr>";
    $message .= "<tr><td><strong>Coding Method:</strong> </td><td>" . strip_tags($_POST['thermal']) . "</td></tr>";
    $message .= "<tr><td></td><td>" . strip_tags($_POST['hotstamps']) . "</td></tr>";
    $message .= "<tr><td></td><td>" . strip_tags($_POST['inkjet']) . "</td></tr>";
    $message .= "<tr><td></td><td>" . strip_tags($_POST['labels']) . "</td></tr>";
    $message .= "<tr><td><strong>Other Coding Methods:</strong> </td><td>" . strip_tags($_POST['othercoding']) . "</td></tr>";
    $message .= "<tr><td><strong>Plans to Upgrade:</strong> </td><td>" . strip_tags($_POST['upgrade']) . "</td></tr>";
    $message .= "<tr><td><strong>Values in a Supplier:</strong> </td><td>" . strip_tags($_POST['integration']) . "</td></tr>";
    $message .= "<tr><td></td><td>" . strip_tags($_POST['codequality']) . "</td></tr>";
    $message .= "<tr><td></td><td>" . strip_tags($_POST['postsales']) . "</td></tr>";
    $message .= "<tr><td></td><td>" . strip_tags($_POST['price']) . "</td></tr>";
    $message .= "<tr><td><strong>Other Values in a Supplier:</strong> </td><td>" . strip_tags($_POST['othervalues']) . "</td></tr>";
    $message .= "<tr><td><strong>Interested in Contact:</strong> </td><td>" . strip_tags($_POST['interest']) . "</td></tr>";
    $message .= "</table>";
    $message .= "</body></html>";

    // CHANGE THE BELOW VARIABLES TO YOUR NEEDS

    $to = 'email@company.com';

    $subject = 'Contest Form Submission';

    $headers = "From: " . $cleanedFrom . "\r\n";
    $headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    if (mail($to, $subject, $message, $headers)) {
    echo 'Your message has been sent.';
    } else {
    echo 'There was a problem sending the email.';
    }

    // DON'T BOTHER CONTINUING TO THE HTML...
    die();

    }
    } else {

    if (!isset($_SESSION[$form.'_token'])) {

    } else {
    echo "Hack-Attempt detected. Got ya!.";
    writeLog('Formtoken');
    }

    }

    ?>
  • Right, so from a guess, it has something to do with your naming of the

    $_SESSION[$form.'_token']

    Or a Session error, maybe in that it has not been created correctly?
  • honestly not sure, I'm admittedly pretty novice when it comes to php, so when I created this page, I removed all the fields from the tutorial I didn't need, then added mine one by one.... testing making sure it worked, which it did... then I added the checkboxes and select inputs, and it broke, so I thought it would be in the ids used. guess I'll go back and continue adding one at a time until I see the issue pop up.
  • I was able to get my form working successfully. I basically started from scratch and went one by one, testing. slow but it won the day :) Now the only issue I see is that upon successful submission, the confirmation statement is hidden by my page's background image?
  • That sounds like a z-indexing problem. Try wrapping your success message in a div and paragraph maybe?
  • I'll give that a shot, even better, how would I make redirect to a confirmation page? I tried changing the echo to location: below - it still submits the form, just doesn't do anything.


    // CHANGE THE BELOW VARIABLES TO YOUR NEEDS

    $to = 'email@email.com';

    $subject = 'Test form submission from form';

    $headers = "From: " . $cleanedFrom . "\r\n";
    $headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    if (mail($to, $subject, $message, $headers)) {
    header("Location: thank-you.html");
    } else {
    echo 'There was a problem sending the email.';
    }

    // DON'T BOTHER CONTINUING TO THE HTML...
    die();
  • I think you can use something like this:


    if (mail($to, $subject, $message, $headers)) {
    echo '<script>window.location="thank-you.html";</script>';
    } else {
    echo '<p class="error">There was a problem sending the email.</p>';
    }

  • Thanks TT_Mark & Standuncan for your help. the rewrite for redirecting to a confirmation page didn't seem to work with the script in the echo. neither did applying a z-index to the basic confirmation statement.

    appreciate the effort though. Great site and forum!
  • It's worked for me in the past so... but my mail function is a little different than yours. I'm not real fluent with php so sorry I can't help more.
  • well I've been trying just about every variation of header or echo to make it redirect and nothing has been successful. if anyone has any ideas, I'm all ears :/

    Thanks
  • I certainly don't doubt your code standuncan :) unfortunately I'm pretty much a novice at editing PHP.... if there was a way to modify the mail function, w/o requiring rewriting the whole thing I'd be open to it, but I just don't know, lol.

    Thanks again.