skip to Main Content

I need some assistance. About a decade ago I compiled a decent PHP mail script for website contact forms. Apparently, it has been rendered obsolete and now doesn’t work in some places. I need some help figuring out why. It’s attached as an ‘answer’ here apparently cuz I couldn’t figure out editing the code blocks instead of posting. The main problem with this one is it’s always falling to !mailSent. I added errors at the top as suggested but I’ve cleared the ones that showed. Nothing else is helping atm. Please let me know what you see! Thank you!

This occurred on a free hosting platform (000webhost) which stinks for many reasons. I guess they claimed they enforced PHP v8 across the board and that’s what broke my original. Funny though, I use the original form/script over at GoDaddy in multiple places and it still works fine there… Now migrating to another free host on this one (awardspace) which offers user ability to downgrade php from like V5 on. I just need to get something working…

2

Answers


  1. Chosen as BEST ANSWER

    I can't even figure out how to edit this post properly. So consider this an edit please. Hosting told me to create a domain email, which I did, then add it as the FROM header, which I did. I'm trying to post the original page & script here that I would much rather work than the first post.

        <?php 
    
    ini_set('error_reporting', E_ALL);
    ini_set('display_errors', 'On');  //On or Off
    
        //session_start();
        //$_SESSION['form_time'] = time();
    
    if (array_key_exists('send', $_POST)) {
        
        // function getCaptcha($SecretKey) {
    //      $Response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".SECRET_KEY."&response={$SecretKey}");
    //      $Return = json_decode($Response);
    //      return $Return;
    //  }
    //  $Return = getCaptcha($_POST['g-recaptcha-response']);
        //var_dump($Return);
        
        // mail processing script 
        $to = email;
        $subject = 'Studio Inquiry';
        
        // list expected fields
        $expected = array('name', 'email', 'question');
        // set required fields
        $required = array('name', 'email', 'question');
        
        // set additional headers
        $headers = 'From: B R <[email protected]>';
    
        // set the include
        $process = 'includes/process2.inc.php';
        if (file_exists($process) && is_readable($process)) {
            include($process);
        }
        else {
            $mailSent = false;
            mail($me, 'Server Problem', "$process cannot be read", $headers);
        }
    }
    ?>
    <!DOCTYPE html>
    <html lang="en-US">
    <head>
    <title>Ebony and Ivory Music Studio - General Contact</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="fb:app_id" content="">
    <meta property="og:title" content="Ebony and Ivory Music Studio - General Contact">
    <meta property="og:type" content="website">
    <meta property="og:image" content="http://ebonyandivorymusic.org/images/1897.jpg">    
    <meta property="og:url" content="http://ebonyandivorymusic.org">
    <meta property="og:description" content="Barbara Roth, of Cincinnati, Colerain, Groesbeck, Cheviot, Montfort Heights, Anderson, Clermont, Batavia, Price Hill, Ohio, piano and violin teacher with 50 years experience.">
    <meta name="description" content="Barbara Roth, of Cincinnati, Colerain, Groesbeck, Cheviot, Montfort Heights, Anderson, Clermont, Batavia, Price Hill, Ohio, piano and violin teacher with 50 years experience.">
    <meta name="author" content="Nathan Roth" >
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <!-- Custom styles for this template -->
    <link href="css/newnav86.css" rel="stylesheet">
    <link href="css/w38.css" rel="stylesheet">
    <style>
    body,h1,h2,h3,h4,h5,h6 {font-family: "Lato", sans-serif}
    .w3-bar,h1,button {font-family: "Montserrat", sans-serif}
    .fa-anchor,.fa-coffee {font-size:200px}
            form { width: 100%; }
            form p { margin: 0px 0px 25px 20px; }
            label {
                display: block;
                font-family: "Calibri", "Times New Roman", Times, serif;
                font-size: 1em;
                line-height: 1.421875em;
                color: #FEF8E6;
            }
            textarea {
                width: 380px;
                height: 150px;
            }
            @media screen and (max-width: 769px) { textarea {
                width: 240px;
                height: 120px;
            } }
            .textInput { width: 300px; }
            @media screen and (max-width: 769px) { .textInput { width: 125px; } }
            .sendButton { border:1px solid #000000!important; color: #FEF8E6; background-color: #666666; }
            .sendButton:hover { border:1px; color:#000000; background-color: #FEF8E6; }
            .warning {
                font-family: "Calibri", "Times New Roman", Times, serif;
                font-size: 1em;
                line-height: 1.21875em;
                font-weight: bold;
                color: #FF0000;
            }
            .success {
                font-family: "Calibri", "Times New Roman", Times, serif;
                font-size: 1em;
                line-height: 1.21875em;
                font-weight: bold;
                color: #6E1410;
            }
            .welcome {
                font-family: "Calibri", "Times New Roman", Times, serif;
                font-size: 1.3em;
                line-height: 1.7875em;
                font-weight: bold;
                color: #FEF8E6;
            }
            form .website{ display:none; } /* hide because is spam protection */
    </style>
    <script>
        <!--
        function MM_validateForm() { //v4.0
          if (document.getElementById){
            var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
            for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
              if (val) { nm=val.name; if ((val=val.value)!="") {
                if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
                  if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.n';
                } else if (test!='R') { num = parseFloat(val);
                  if (isNaN(val)) errors+='- '+nm+' must contain a number.n';
                  if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
                    min=test.substring(8,p); max=test.substring(p+1);
                    if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.n';
            } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.n'; }
            } if (errors) alert('The following error(s) occurred:n'+errors);
            document.MM_returnValue = (errors == '');
        } }
        //-->
        </script>
        <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-xxxxxxx-1"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
    
      gtag('config', 'UA-xxxxxxx-1');
    </script>
    
    
    </head>
    
    <body>
    
    <!-- Navbar -->
    <?php include("includes/newnavnavigation.inc.php"); ?>
    
    <div class="content">
    <!-- Header -->
    <header id="header" class="w3-container w3-center">
      <h1 class="w3-jumbo"><img src="images/header.jpg" alt="Ebony and Ivory Music Studio Header Image"></h1>
    </header>
    
    <div class="w3-row-padding w3-padding-64 w3-container" style="margin-top: -60px; margin-left: 0px;">
      <div class="w3-content" style="margin-left: 0px;">
        <div class="w3-twothird" style="margin-left: 0px;">
        
                <h2>Thank you for visiting! Ask a general question or contact me to set up an introductory lesson!</h2>
                
                <!--<div id="right">
                        <span style="margin-left: 60px;"><a href="https://lessons.com/oh/cincinnati/violin-lessons/" title="lessons.com" target="_blank"><img src="//cdn.lessons.com/assets/images/tmp/lessons-2018.png" width="100" alt="lessons.com"></a></span><br><br> 
                        <img src="images/1884.jpg" alt="Headshot for Contact Webpage">
                    </div>--> 
                
                <?php 
                if ($_POST && isset($missing) && !empty($missing)) {
                ?>
                <p class="warning">Please complete the missing item(s) indicated.</p>
                <?php
                }
                elseif ($_POST && $linkOne) {
                ?>
                <p class="warning">Sorry, Messages that contain inappropriate data will not be sent.</p>
                <?php
                }
                elseif ($_POST && $linkTwo) {
                ?>
                <p class="warning">Sorry, Messages that contain inappropriate data will not be sent.</p>
                <?php
                }
                elseif ($_POST && $linkThree) {
                ?>
                <p class="warning">Sorry, Messages that contain inappropriate data will not be sent.</p>
                <?php
                }
                elseif ($_POST && !$mailSent) {
                ?>
                <p class="warning">Sorry, there was a problem sending your message. Please try again later.</p>
                <?php
                }
                elseif ($_POST && $Return->success == true && $Return->score > 0.5 && $mailSent) {
                ?>
                <p class="success">Your message has been sent. Thank you for your comments/questions!</p>
                <?php } ?>           
                <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contact" id="contact" class="w3-container w3-card-4" onSubmit="MM_validateForm('name','','R','email','','RisEmail','comments','','R');return document.MM_returnValue">
                <p><input name="website" type="text" class="website"></p>
                  <p>
                    <label for="name">Name: <?php
                    if (isset($missing) && in_array('name', $missing)) { ?>
                    <span class="warning">Please enter your name</span><?php } ?>
                    </label>
                    <input name="name" type="text" class="textInput" id="name" 
                    <?php if (isset($missing)) {
                        echo 'value="'.htmlentities($_POST['name'], ENT_QUOTES).'"';
                        } ?>
                    >
                  </p>
                  <p>
                    <label for="email">Email: <?php
                    if (isset($missing) && in_array('email', $missing)) { ?>
                    <span class="warning">Please enter your email address</span><?php } ?>
                    </label>
                    <input name="email" type="text" class="textInput" id="email"
                    <?php if (isset($missing)) {
                        echo 'value="'.htmlentities($_POST['email'], ENT_QUOTES).'"';
                        } ?>
                    >
                  </p>
                  <p>
                    <label for="question">Comments:<?php
                    if (isset($missing) && in_array('question', $missing)) { ?>
                    <span class="warning">Please enter your comments</span><?php } ?>
                    </label>
                    <textarea name="question" id="question" cols="25" rows="5"><?php 
                        if (isset($missing)) {
                            echo htmlentities($_POST['question'], ENT_QUOTES);
                        } ?></textarea>
                  </p>
                  <p>
                            <!-- <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">   -->            
                  </p>
                  <p>
                    <input type="submit" name="send" id="send" class="sendButton" value="Click to Ask Question">
                  </p>
                </form>
                <!-- <script>
                        grecaptcha.ready(function() {
                            grecaptcha.execute('<?php echo SITE_KEY; ?>', {action: 'homepage'}).then(function(token) {
                               //console.log(token);
                               document.getElementById('g-recaptcha-response').value=token;
                            });
                        });
                </script> -->
                
                <br><br>
                
                <img class="centerimage" src="images/facebook_1475422948378.jpg" alt="Image of Barb Teaching">
                
                </div>
    
        <div class="w3-third w3-center" style="margin-top: 60px;">
          <span style="margin-left: 0px;"><a href="https://lessons.com/oh/cincinnati/violin-lessons/" title="lessons.com" target="_blank"><img src="//cdn.lessons.com/assets/images/tmp/lessons-2018.png" width="100" alt="lessons.com"></a></span><br><br> 
                        <img style="width: 70%; border: 2px solid #6E1410;" src="images/1884.jpg" alt="Headshot for Contact Webpage">
        </div>
      </div>
    </div>
    
    <!-- Footer -->
    <?php include("includes/newnavfooter.inc.php"); ?>
    
    </div>
    <script>
    // Used to toggle the menu on small screens when clicking on the menu button
    function myFunction() {
        var x = document.getElementById("navDemo");
        if (x.className.indexOf("w3-show") == -1) {
            x.className += " w3-show";
        } else { 
            x.className = x.className.replace(" w3-show", "");
        }
    }
    </script>
    
    </body>
    </html>
    

    And the script process2

    <?php
    
        // 30 second minimum
        session_start();
        $time_limit = 30; 
        $suspect = false;
    
        if (isset($_SESSION['form_time']) && is_numeric($_SESSION['form_time'])) {
            $seconds_passed = time() - $_SESSION['form_time'];
            if ($seconds_passed < $time_limit) {
               $suspect = true;
            } 
        } else {
            $suspect = true;
        }
        
        # spam protection
        if (isset($_POST["website"]) && $_POST["website"] == "") {      
        
        if (isset($_SERVER['SCRIPT_NAME']) && strpos($_SERVER['SCRIPT_NAME'], 'inc.php')) exit;
    
        // remove escape characters from POST array
        //if (get_magic_quotes_gpc()) {
        //  function stripslashes_deep($value) {
        //      $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
        //      return $value;
        //  }
        //  $_POST = array_map('stripslashes_deep', $_POST);
        //}
    
        // create empty array for any missing fields
        $missing = array();
        
        // assume that there is nothing suspect
        $suspect = false;
        // create a pattern to locate suspect phrases
        $pattern = '/Content-Type:|Bcc:|CC:/i';
        // function to check for suspect phrases
        function isSuspect($val, $pattern, &$suspect) {
        // if the variable is an array, loop through each element
        // and pass it recursively back to the same function
        if (is_array($val)) {
            foreach ($val as $item) {
               isSuspect($item, $pattern, $suspect);
               if ($suspect)
                   break;
            }
        }
        else {
          // if one of the suspect phrases is found, set Boolean to true
          if (preg_match($pattern, $val)) {
            $suspect = true;
            }
          }
        }
        
        // check the $_POST array and any subarrays for suspect content
        isSuspect($_POST, $pattern, $suspect);
        
        if ($suspect ) {
            $mailSent = false;
            unset($missing);
        }
        else {
        // process the $_POST variables
            foreach ($_POST as $key => $value) {
                // assign to temporary variable and strip whitespace if not an array
                $temp = is_array($value) ? $value : trim($value);
                // if empty and required, add to $missing array
                if (empty($temp) && in_array($key, $required)) {
                    array_push($missing, $key);
                }
                // otherwise, assign to a variable of the same name as $key
                elseif (in_array($key, $expected)) {
                    ${$key} = $temp;
                }
            }
        }
        
        // validate the email address
        if (!empty($email)) {
            // regex to identify illegal characters in email address
            $checkEmail = '/^[^@]+@[^srn'";,@%]+$/';
            // reject the email address if it doesn't match
            if (!preg_match($checkEmail, $email)) {
                $suspect = true;
                $mailSent = false;
                unset($missing);
            }
        }
        
        // validate the comments
        // regex to identify html links
        $linkOne = false;
        $checkCommentsLinks = '/b(?:(?:https?|ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i'; // '/(http://|www)/';
        if(preg_match($checkCommentsLinks, stripcslashes($question))){
            $linkOne = true;
            $suspect = true;            
            $mailSent = false;
            unset($missing);
        }
        
        //validate comments against email addresses
        $linkTwo = false;
        $checkCommentsEmail = '/^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/';
        if(preg_match($checkCommentsEmail, stripcslashes($question))){
            $linkTwo = true;
            $suspect = true;            
            $mailSent = false;
            unset($missing);
        }
        
        //look for links in comments
        $linkThree = false;
        if(preg_match('/http|www/i',$question)) {
            $linkThree = true;
            $suspect = true;            
            $mailSent = false;
            unset($missing);
        }
        
        // go ahead only if not suspect and all required fields OK
        if (!$suspect && empty($missing)) {
            // initialize the $message variable
            $message = '';
            // loop through the $expected array
            foreach($expected as $item) {
                // assign the value of the current item to $val
                if (isset(${$item})) {
                    $val = ${$item};
                }
                // if it has no value, assign 'Not Selected'
                else {
                    $val = 'Not selected';
                }
                // if an array, expand as comma-separated string
                if (is_array($val)) {
                    $val = implode(', ', $val);
                }
                // add label and value to the message body
                $message .= ucfirst($item).": $valnn";
                }
        
            // limit line length
            $message = wordwrap($message, 70);
            
            // create Reply-To header
            if (!empty($email)) {
                $headers .= "rnReply-To: $email";
            }
        
            // send it
            $mailSent = mail($to, $subject, $message, $headers);
            if ($mailSent) {
                // $missing is no longer needed if the email is sent, so unset it
                unset($missing);
            }
        }
        } 
        else {
            http_response_code(400);
            exit;
        }
        ?>
    

  2. Free hosting platform (000webhost) enforced PHP v8 across the board and that’s what broke your original code. Migrate to another free host

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search