Simple PHP联系表格与垃圾邮件

huangapple go评论90阅读模式
英文:

Simple PHP contact form vs spam

问题

I understand that you'd like a translation of the code you provided. Here are the code parts without the HTML and explanations:

For the contact page:

<?php
    session_start();
    $_SESSION['form_time'] = time();

    define('SITE_KEY', '...');
    define('SECRET_KEY', '...');

    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']);

        // Mail processing script
        $to = 'email1';
        $me = 'email2';
        $subject = 'Feedback From Website';

        // List expected fields
        $expected = array('name', 'email', 'question');
        // Set required fields
        $required = array('name', 'email', 'question');

        // Set additional headers
        $headers = 'From: Megan Roth<feedback@meganroth.com>';

        // Set the include
        $process = 'includes/process.inc.php';
        if (file_exists($process) && is_readable($process)) {
            include($process);
        } else {
            $mailSent = false;
            mail($me, 'Server Problem', "$process cannot be read", $headers);
        }
    }
?>

For the mail processing script:

<?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 an 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 (is_array($val)) {
                foreach ($val as $item) {
                    isSuspect($item, $pattern, $suspect);
                    if ($suspect)
                        break;
                }
            } else {
                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 {
            foreach ($_POST as $key => $value) {
                $temp = is_array($value) ? $value : trim($value);
                if (empty($temp) && in_array($key, $required)) {
                    array_push($missing, $key);
                } elseif (in_array($key, $expected)) {
                    ${$key} = $temp;
                }
            }

            // Validate the email address
            if (!empty($email)) {
                $checkEmail = '/^[^@]+@[^\s\r\n\';,@%]+$/';
                if (!preg_match($checkEmail, $email)) {
                    $suspect = true;
                    $mailSent = false;
                    unset($missing);
                }
            }

            // Validate the comments
            $linkOne = false;
            $checkCommentsLinks = '/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i';
            if (preg_match($checkCommentsLinks, stripcslashes($question))) {
                $linkOne = true;
                $suspect = true;
                $mailSent = false;
                unset($missing);
            }

            $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);
            }

            $linkThree = false;
            if (preg_match('/http|www/i', $question)) {
                $linkThree = true;
                $suspect = true;
                $mailSent = false;
                unset($missing);
            }

            if (!$suspect && empty($missing)) {
                $message = '';
                foreach ($expected as $item) {
                    if (isset(${$item})) {
                        $val = ${$item};
                    } else {
                        $val = 'Not selected';
                    }
                    if (is_array($val)) {
                        $val = implode(', ', $val);
                    }
                    $message .= ucfirst($item) . ": $val\n\n";
                }

                $message = wordwrap($message, 70);

                if (!empty($email)) {
                    $headers .= "\r\nReply-To: $email";
                }

                $mailSent = mail($to, $subject, $message, $headers);

                if ($mailSent) {
                    unset($missing);
                }
            }
        }
    } else {
        http_response_code(400);
        exit;
    }
?>

I've provided a translation of the code without the HTML and explanations. If you have any specific questions about the code or need further assistance, please feel free to ask.

英文:

I realize this is probably bad practice but... I've used a simple php script I wrote with the help of a tutorial book I read years ago. I've adapted it as much as I'm able for use with multiple sites but it's largely the same across sites. I have tried and tried to eliminate spam type messages, but alas I cannot figure out what else I can do/can be done. I'm sure someone will mention that e.g. Javascript would be better but I don't have the time or drive to learn it at this point, so please stick to the PHP. The specific code follows below, suggestions will be greatly appreciated as to how to future proof this for spam elimination.

The contact page:

&lt;?php 
session_start();
$_SESSION[&#39;form_time&#39;] = time();
define (&#39;SITE_KEY&#39;, &#39;...&#39;);
define (&#39;SECRET_KEY&#39;, &#39;...&#39;);
if (array_key_exists(&#39;send&#39;, $_POST)) {
function getCaptcha($SecretKey) {
$Response = file_get_contents(&quot;https://www.google.com/recaptcha/api/siteverify?secret=&quot;.SECRET_KEY.&quot;&amp;response={$SecretKey}&quot;);
$Return = json_decode($Response);
return $Return;
}
$Return = getCaptcha($_POST[&#39;g-recaptcha-response&#39;]);
//var_dump($Return);
// mail processing script
$to = &#39;email1&#39;;
$me = &#39;email2&#39;;
$subject = &#39;Feedback From Website&#39;;
// list expected fields
$expected = array(&#39;name&#39;, &#39;email&#39;, &#39;question&#39;);
// set required fields
$required = array(&#39;name&#39;, &#39;email&#39;, &#39;question&#39;);
// set additional headers
$headers = &#39;From: Megan Roth&lt;feedback@meganroth.com&gt;&#39;;
// set the include
$process = &#39;includes/process.inc.php&#39;;
if (file_exists($process) &amp;&amp; is_readable($process)) {
include($process);
}
else {
$mailSent = false;
mail($me, &#39;Server Problem&#39;, &quot;$process cannot be read&quot;, $headers);
}
}
?&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
&lt;meta property=&quot;og:title&quot; content=&quot;Megan Roth, Mezzo-Soprano - Contact&quot;&gt;
&lt;meta property=&quot;og:type&quot; content=&quot;website&quot;&gt;
&lt;meta property=&quot;og:image&quot; content=&quot;http://www.meganroth.com/EditedImages/index.jpg&quot;&gt;
&lt;meta property=&quot;og:url&quot; content=&quot;http://www.meganroth.com/contact.php&quot;&gt;
&lt;meta property=&quot;og:description&quot; content=&quot;Mezzo-soprano Megan Roth enjoys a career as a soloist in opera and oratorio as well as with prestigious chamber ensembles around the country.&quot;&gt;
&lt;title&gt;Megan Roth, Mezzo-Soprano - Contact&lt;/title&gt;
&lt;meta name=&quot;description&quot; content=&quot;Mezzo-soprano Megan Roth enjoys a career as a soloist in opera and oratorio as well as with prestigious chamber ensembles around the country.&quot;&gt;
&lt;meta name=&quot;author&quot; content=&quot;Nathan Roth&quot; &gt;
&lt;link href=&quot;css/w3_parallax_template.css&quot; type=&quot;text/css&quot; rel=&quot;stylesheet&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;https://fonts.googleapis.com/css?family=Crimson+Pro&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;https://fonts.googleapis.com/css?family=EB+Garamond&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;https://fonts.googleapis.com/css?family=Domine&quot;&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css&quot;&gt;
&lt;link href=&quot;css/parallax12.css&quot; type=&quot;text/css&quot; rel=&quot;stylesheet&quot;&gt;
&lt;style&gt;
/************* ABOVE THIS LINE GLOBAL ***************/
form { width: 100%; }
form p { margin: 0px 0px 25px 20px; }
textarea {
width: 380px;
height: 150px;
}
@media screen and (max-width: 400px) { textarea {
width: 240px;
height: 120px;
} }
.textInput { width: 300px; }
@media screen and (max-width: 400px) { .textInput { width: 125px; } }
.sendButton { border:1px solid #000000!important; color: #000; background-color: #FAC41E; }
.sendButton:hover { border:1px; color:#000000; background-color: #08748F; }
form .website{ display:none; } /* hide because is spam protection */
.conStudio {
font-family: &quot;EB Garamond&quot;, Times, &quot;Times New Roman&quot;, serif;
font-size: 1.4em;
line-height: 1.68em;
color: #FAC41E;
font-weight: bold;
margin: 0px 0px 0px 0px;
}
&lt;/style&gt;
&lt;script&gt;
&lt;!--
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors=&#39;&#39;,args=MM_validateForm.arguments;
for (i=0; i&lt;(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!=&quot;&quot;) {
if (test.indexOf(&#39;isEmail&#39;)!=-1) { p=val.indexOf(&#39;@&#39;);
if (p&lt;1 || p==(val.length-1)) errors+=&#39;- &#39;+nm+&#39; must contain an e-mail address.\n&#39;;
} else if (test!=&#39;R&#39;) { num = parseFloat(val);
if (isNaN(val)) errors+=&#39;- &#39;+nm+&#39; must contain a number.\n&#39;;
if (test.indexOf(&#39;inRange&#39;) != -1) { p=test.indexOf(&#39;:&#39;);
min=test.substring(8,p); max=test.substring(p+1);
if (num&lt;min || max&lt;num) errors+=&#39;- &#39;+nm+&#39; must contain a number between &#39;+min+&#39; and &#39;+max+&#39;.\n&#39;;
} } } else if (test.charAt(0) == &#39;R&#39;) errors += &#39;- &#39;+nm+&#39; is required.\n&#39;; }
} if (errors) alert(&#39;The following error(s) occurred:\n&#39;+errors);
document.MM_returnValue = (errors == &#39;&#39;);
} }
//--&gt;
&lt;/script&gt;
&lt;script src=&quot;https://www.google.com/recaptcha/api.js?render=6LcEl-8UAAAAAMlzOfIDXmnooj34lkDNfKDTxN2m&quot;&gt;&lt;/script&gt;
&lt;!-- Global site tag (gtag.js) - Google Analytics --&gt;
&lt;script async src=&quot;https://www.googletagmanager.com/gtag/js?id=UA-34193066-1&quot;&gt;&lt;/script&gt;
&lt;script&gt;
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag(&#39;js&#39;, new Date());
gtag(&#39;config&#39;, &#39;UA-34193066-1&#39;);
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;?php include(&quot;includes/new_navigation12.inc.php&quot;); ?&gt;
&lt;!-- Container  --&gt;
&lt;div class=&quot;w3-content w3-container w3-padding-64&quot;&gt;
&lt;div class=&quot;w3-row&quot;&gt;
&lt;div class=&quot;hdquote&quot;&gt;
&amp;quot;…(her) soaring mezzo-soprano is clean and clear and her vocal glissandos precise and near perfect.&amp;quot;&lt;br&gt;
- &lt;em&gt;Asheville Citizen-Times&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;The Barber of Seville&lt;/strong&gt;, Brevard Music Center.
&lt;div class=&quot;decLine&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;w3-row&quot;&gt;
&lt;div class=&quot;w3-col m9 w3-padding-large&quot;&gt;  
&lt;?php 
if ($_POST &amp;&amp; isset($missing) &amp;&amp; !empty($missing)) {
?&gt;
&lt;p class=&quot;warning&quot;&gt;Please complete the missing item(s) indicated.&lt;/p&gt;
&lt;?php
}
elseif ($_POST &amp;&amp; $linkOne) {
?&gt;
&lt;p class=&quot;warning&quot;&gt;Sorry, Messages that contain inappropriate data will not be sent.&lt;/p&gt;
&lt;?php
}
elseif ($_POST &amp;&amp; $linkTwo) {
?&gt;
&lt;p class=&quot;warning&quot;&gt;Sorry, Messages that contain inappropriate data will not be sent.&lt;/p&gt;
&lt;?php
}
elseif ($_POST &amp;&amp; $linkThree) {
?&gt;
&lt;p class=&quot;warning&quot;&gt;Sorry, Messages that contain inappropriate data will not be sent.&lt;/p&gt;
&lt;?php
}
elseif ($_POST &amp;&amp; !$mailSent) {
?&gt;
&lt;p class=&quot;warning&quot;&gt;Sorry, there was a problem sending your message. Please try again later.&lt;/p&gt;
&lt;?php
}
elseif ($_POST &amp;&amp; $Return-&gt;success == true &amp;&amp; $Return-&gt;score &gt; 0.5 &amp;&amp; $mailSent) {
?&gt;
&lt;p class=&quot;success&quot;&gt;Your message has been sent. Thank you for your comments/questions!&lt;/p&gt;
&lt;?php } ?&gt;           
&lt;form action=&quot;&lt;?php echo $_SERVER[&#39;PHP_SELF&#39;]; ?&gt;&quot; method=&quot;post&quot; name=&quot;contact&quot; id=&quot;contact&quot; class=&quot;w3-container w3-card-4&quot; onSubmit=&quot;MM_validateForm(&#39;name&#39;,&#39;&#39;,&#39;R&#39;,&#39;email&#39;,&#39;&#39;,&#39;RisEmail&#39;,&#39;comments&#39;,&#39;&#39;,&#39;R&#39;);return document.MM_returnValue&quot;&gt;
&lt;p&gt;&lt;input name=&quot;website&quot; type=&quot;text&quot; class=&quot;website&quot;&gt;&lt;/p&gt;
&lt;p&gt;
&lt;label for=&quot;name&quot;&gt;Name: &lt;?php
if (isset($missing) &amp;&amp; in_array(&#39;name&#39;, $missing)) { ?&gt;
&lt;span class=&quot;warning&quot;&gt;Please enter your name&lt;/span&gt;&lt;?php } ?&gt;
&lt;/label&gt;
&lt;input name=&quot;name&quot; type=&quot;text&quot; class=&quot;textInput&quot; id=&quot;name&quot; 
&lt;?php if (isset($missing)) {
echo &#39;value=&quot;&#39;.htmlentities($_POST[&#39;name&#39;], ENT_QUOTES).&#39;&quot;&#39;;
} ?&gt;
&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;label for=&quot;email&quot;&gt;Email: &lt;?php
if (isset($missing) &amp;&amp; in_array(&#39;email&#39;, $missing)) { ?&gt;
&lt;span class=&quot;warning&quot;&gt;Please enter your email address&lt;/span&gt;&lt;?php } ?&gt;
&lt;/label&gt;
&lt;input name=&quot;email&quot; type=&quot;text&quot; class=&quot;textInput&quot; id=&quot;email&quot;
&lt;?php if (isset($missing)) {
echo &#39;value=&quot;&#39;.htmlentities($_POST[&#39;email&#39;], ENT_QUOTES).&#39;&quot;&#39;;
} ?&gt;
&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;label for=&quot;question&quot;&gt;Comments:&lt;?php
if (isset($missing) &amp;&amp; in_array(&#39;question&#39;, $missing)) { ?&gt;
&lt;span class=&quot;warning&quot;&gt;Please enter your comments&lt;/span&gt;&lt;?php } ?&gt;
&lt;/label&gt;
&lt;textarea name=&quot;question&quot; id=&quot;question&quot; cols=&quot;25&quot; rows=&quot;5&quot;&gt;&lt;?php 
if (isset($missing)) {
echo htmlentities($_POST[&#39;question&#39;], ENT_QUOTES);
} ?&gt;&lt;/textarea&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;input type=&quot;hidden&quot; id=&quot;g-recaptcha-response&quot; name=&quot;g-recaptcha-response&quot;&gt;              
&lt;/p&gt;
&lt;p&gt;
&lt;input class=&quot;sendButton&quot; type=&quot;submit&quot; name=&quot;send&quot; id=&quot;send&quot; value=&quot;Click to Submit Comments&quot;&gt;
&lt;/p&gt;
&lt;/form&gt;
&lt;script&gt;
grecaptcha.ready(function() {
grecaptcha.execute(&#39;&lt;?php echo SITE_KEY; ?&gt;&#39;, {action: &#39;homepage&#39;}).then(function(token) {
//console.log(token);
document.getElementById(&#39;g-recaptcha-response&#39;).value=token;
});
});
&lt;/script&gt;
&lt;p class=&quot;welcome&quot;&gt;Please take this time to send comments and your email address so we can stay in touch with you!&lt;/p&gt;&lt;br&gt;&lt;br&gt;
&lt;/div&gt;
&lt;div class=&quot;w3-col m3 w3-padding-large&quot;&gt;
&lt;img class=&quot;border&quot; src=&quot;EditedImages/Contact.jpg&quot; alt=&quot;Headshot for Megan Roth&#39;s Contact Webpage&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;w3-row w3-center&quot;&gt;
&lt;span class=&quot;conStudio&quot;&gt;Interested in private lessons? Please visit my &lt;a href=&quot;http://studio.meganroth.com/&quot; onclick=&quot;window.open(this.href, &#39;_blank&#39;);return false;&quot;&gt;studio site!&lt;/a&gt;&lt;/span&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;!-- Footer --&gt;
&lt;?php include(&quot;includes/new_footer12.inc.php&quot;); ?&gt;
&lt;script&gt;
// Change style of navbar on scroll
window.onscroll = function() {myFunction()};
function myFunction() {
var navbar = document.getElementById(&quot;myNavbar&quot;);
if (document.body.scrollTop &gt; 100 || document.documentElement.scrollTop &gt; 100) {
navbar.className = &quot;w3-bar&quot; + &quot; w3-card&quot; + &quot; w3-animate-top&quot; + &quot; w3-white&quot;;
} else {
navbar.className = navbar.className.replace(&quot; w3-card w3-animate-top w3-white&quot;, &quot;&quot;);
}
}
// Used to toggle the menu on small screens when clicking on the menu button
function toggleFunction() {
var x = document.getElementById(&quot;navDemo&quot;);
if (x.className.indexOf(&quot;w3-show&quot;) == -1) {
x.className += &quot; w3-show&quot;;
} else {
x.className = x.className.replace(&quot; w3-show&quot;, &quot;&quot;);
}
}
// Toggle between showing and hiding the sidebar, and add overlay effect
function w3_open() {
if (mySidebar.style.display === &#39;block&#39;) {
mySidebar.style.display = &#39;none&#39;;
overlayBg.style.display = &quot;none&quot;;
} else {
mySidebar.style.display = &#39;block&#39;;
overlayBg.style.display = &quot;block&quot;;
}
}
// Close the sidebar with the close button
function w3_close() {
mySidebar.style.display = &quot;none&quot;;
overlayBg.style.display = &quot;none&quot;;
}
/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById(&quot;myDropdown&quot;).classList.toggle(&quot;w3-show&quot;);
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
if (!e.target.matches(&#39;.dropbtn&#39;)) {
var myDropdown = document.getElementById(&quot;myDropdown&quot;);
if (myDropdown.classList.contains(&#39;w3-show&#39;)) {
myDropdown.classList.remove(&#39;w3-show&#39;);
}
}
}
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

And now for the actual mail processing script:

&lt;?php
// 30 second minimum
session_start();
$time_limit = 30; 
$suspect = false;
if (isset($_SESSION[&#39;form_time&#39;]) &amp;&amp; is_numeric($_SESSION[&#39;form_time&#39;])) {
$seconds_passed = time() - $_SESSION[&#39;form_time&#39;];
if ($seconds_passed &lt; $time_limit) {
$suspect = true;
} 
} else {
$suspect = true;
}
# spam protection
if (isset($_POST[&quot;website&quot;]) &amp;&amp; $_POST[&quot;website&quot;] == &quot;&quot;) {		
if (isset($_SERVER[&#39;SCRIPT_NAME&#39;]) &amp;&amp; strpos($_SERVER[&#39;SCRIPT_NAME&#39;], &#39;inc.php&#39;)) exit;
// remove escape characters from POST array
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value) {
$value = is_array($value) ? array_map(&#39;stripslashes_deep&#39;, $value) : stripslashes($value);
return $value;
}
$_POST = array_map(&#39;stripslashes_deep&#39;, $_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 = &#39;/Content-Type:|Bcc:|CC:/i&#39;;
// function to check for suspect phrases
function isSuspect($val, $pattern, &amp;$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 =&gt; $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) &amp;&amp; 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 = &#39;/^[^@]+@[^\s\r\n\&#39;&quot;;,@%]+$/&#39;;
// reject the email address if it doesn&#39;t match
if (!preg_match($checkEmail, $email)) {
$suspect = true;
$mailSent = false;
unset($missing);
}
}
// validate the comments
// regex to identify html links
$linkOne = false;
$checkCommentsLinks = &#39;/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&amp;@#\/%?=~_|!:,.;]*[-a-z0-9+&amp;@#\/%=~_|]/i&#39;; // &#39;/(http:\/\/|www)/&#39;;
if(preg_match($checkCommentsLinks, stripcslashes($question))){
$linkOne = true;
$suspect = true;			
$mailSent = false;
unset($missing);
}
//validate comments against email addresses
$linkTwo = false;
$checkCommentsEmail = &#39;/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/&#39;;
if(preg_match($checkCommentsEmail, stripcslashes($question))){
$linkTwo = true;
$suspect = true;			
$mailSent = false;
unset($missing);
}
//look for links in comments
$linkThree = false;
if(preg_match(&#39;/http|www/i&#39;,$question)) {
$linkThree = true;
$suspect = true;			
$mailSent = false;
unset($missing);
}
// go ahead only if not suspect and all required fields OK
if (!$suspect &amp;&amp; empty($missing)) {
// initialize the $message variable
$message = &#39;&#39;;
// 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 &#39;Not Selected&#39;
else {
$val = &#39;Not selected&#39;;
}
// if an array, expand as comma-separated string
if (is_array($val)) {
$val = implode(&#39;, &#39;, $val);
}
// add label and value to the message body
$message .= ucfirst($item).&quot;: $val\n\n&quot;;
}
// limit line length
$message = wordwrap($message, 70);
// create Reply-To header
if (!empty($email)) {
$headers .= &quot;\r\nReply-To: $email&quot;;
}
// 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;
}
?&gt;

Something I'm really banging my head against lately is the latest spam messages actually are sending an email with a subject line (don't know where a subject comes into this) that starts "SPAM". Any help will be more than appreciated!! Thanks for reading!

答案1

得分: 1

没有未来的防止垃圾邮件的方法,您已经使用了三种方法来防止它:

  1. Captcha(验证码)
  2. 匹配在发送的数据中的某些垃圾词汇,您可以添加更多垃圾词汇
  3. 蜜罐(Honeypot)

您还可以添加以下方式:

  1. CSRF 令牌
  2. 测量发送表单所需的时间,例如,如果表单在 30 秒内发送,则被怀疑
  3. 生成动态的输入名称
  4. 使用 JavaScript 在客户端验证数据

在您的 isSuspect 函数中,当 $suspect 为真时应该跳出,这样您就不必检查所有其他值。

//...
foreach ($val as $item) {
   isSuspect($item, $pattern, $suspect);
   if ($suspect)
       break;
}
//...

测量时间的示例

在生成表单时,保存时间在一个 session 中:

session_start();
$_SESSION['form_time'] = time();

在提交表单时,检查时间:

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;
}

注意: 如果用户打开多个表单,值将被覆盖,将使用最后一个值,并且以前打开的表单将无效。

这只是一种基本的方法,有许多实现方式,30 秒只是我选择的任意值。

英文:

There is no future proof to prevent spam, you already use three ways to prevent it

  1. Captcha
  2. Matching certain spammy words in the data sent, you could add more spammy words
  3. Honeypot

You can add

  1. CSRF token
  2. Measure time that takes to send the form, eg. if the form is sent in less that 30 seconds then is suspect
  3. Generate dynamic input names
  4. Validate data in the client-side with javascript

In your isSuspect function you should break when $suspect is true, so you don't have to check all others values

//...
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
if ($suspect)
break;
}
//...

Example of measuring time

When generating the form save the time in a session:

session_start();
$_SESSION[&#39;form_time&#39;] = time();

When submitting the form check for the time:

session_start();
$time_limit = 30; 
$suspect = false;
if (isset($_SESSION[&#39;form_time&#39;]) &amp;&amp; is_numeric($_SESSION[&#39;form_time&#39;])) {
$seconds_passed = time() - $_SESSION[&#39;form_time&#39;];
if ($seconds_passed &lt; $time_limit) {
$suspect = true;
} 
} else {
$suspect = true;
}

NOTE: if the user opens multiple forms the values will be overwritten, the last value will be used and the previous oppened forms will be invalidated

This is just basic way, there are many ways to implement this, the 30 seconds is just an arbitrary value that I chose

huangapple
  • 本文由 发表于 2023年2月24日 01:57:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548581.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定