How to prevent spam URLs in a PHP contact form

前提是你 提交于 2021-01-27 13:13:25

问题


I have created a form where a user can add a review. Perhaps this is very obvious but how can I avoid a user inserting a url in the text area. Is there a way to check this? I have put in a captcha to check for humans.

<form action="" method="POST" name="form">
  some other input fields

             <span id="sprytextarea1">
             <textarea name="Comments" cols="50" rows="3" ></textarea>
             <span class="textareaRequiredMsg">A value is required.</span></span></p>

  <img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" /><input type="text" name="captcha_code" size="10" maxlength="6" />

<a href="#" onclick="document.getElementById('captcha').src = '/securimage/securimage_show.php?' + Math.random(); return false">[ Different Image ]</a>

  <input name="Submit" type="submit" value="Submit your form ">
           <input type="hidden" name="MM_insert" value="form">
           </form>

Any suggestions welcome.


回答1:


Using PHP you can try two things using preg_match() and strip_tags() or a combination of them both. below will clean the textarea, escape it as well for database.

Once the form is submitted try this.

$post = array();

foreach($_POST as $k => $v){

// strip all HTML and escape values for database

$post[$k] = strip_tags(mysql_real_escape_string($v));
}

// check of we have URL in text area

if(preg_match('/www\.|http:|https:/'i,$post['Comments']){

// prevent form from saving code goes here
echo 'error please remove URLs';

}else{
// let form be saved
}



回答2:


Just put the if condition,before insert db.

if(preg_match("/\b(?:(?:https?|ftp|http):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$_POST['comment'])){

echo 'error please remove URLs';

}else
{....



回答3:


Simply, there is no any automatic way to check a URL in input text. You just have to use a human check for the user input.

For example: suppose that you tried to apply regex check for a URL and I want to trick it, I may able to write infinite string that shown as a URL:

  • http: example .com
  • h ttp:// ecxampleDOTcom
  • ht-tp: / / ecample. Com
  • etc

So any commenting system to achieve the ultimate spam protection, it applies moderator review in which a human being check the content.



来源:https://stackoverflow.com/questions/20254482/how-to-prevent-spam-urls-in-a-php-contact-form

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!