【问题标题】:php form preg_match protect unwanted charactersphp form preg_match 保护不需要的字符
【发布时间】:2015-09-16 22:14:27
【问题描述】:

这是我的 php 代码,例如我想保护我的表单免受不需要的标签的影响

<a harf='http://anyweb.com'>Look </a> or 
<script> something here </script> or 
<?php header( "Location:tks.php" ); ?>

我尝试过将任何链接或代码发布到我的表单,但非常困难的是,任何人都可以缩短并轻松保护我的表单免受不需要的链接和代码的影响。 这是我尝试过的代码

<?
 $error="";
if(!empty($_POST)) 
    { 

if(empty($_POST['name'])){
    $error = 'Invalid name. Try again';
    }
elseif(empty($_POST['message'])){
    $error = 'Invalid message. Try again';
    }
elseif(preg_match('/http/',$_POST['name'])){
    $error = 'Invalid content message. Try again';
    }
elseif(preg_match('/http/',$_POST['message'])){
    $error = 'Invalid content message. Try again';
    }
elseif(preg_match('/</',$_POST['name'])){
    $error = 'Invalid content message. Try again';
    }
elseif(preg_match('/</',$_POST['message'])){
    $error = 'Invalid content message. Try again';
    }
else {  
$name = $_POST['name'];
$message = $_POST['message'];

//include('sqlconnect.php');
//$sql = "INSERT INTO msg (name, message, date)VALUES ('$name', '$message', 'now()')"; 
//mysql_query($sql) or die(mysql_error());

header( "Location:tks.php" );
exit;
}
}
?>

【问题讨论】:

    标签: php forms


    【解决方案1】:

    您可能想看看 PHP 的内置卫生过滤器:http://php.net/manual/en/filter.filters.sanitize.php

    所以也许这样的事情可以解决问题:

    if ($_POST['message'] != filter_var($_POST['message'], FILTER_SANITIZE_STRING) {
        $error="Try again";
    }
    

    【讨论】:

    • tks 我应该用你的回答做得更好if ($_POST != filter_var($_POST, FILTER_SANITIZE_STRING)) { $error="Try again"; }
    【解决方案2】:

    为了保护您发布的数据免受原始 HTML 的影响,可能在插入数据库之前,您可以使用 strip_tags 剥离它们的标签,如下所示:

    $name = strip_tags($_POST['name']);
    $message = strip_tags($_POST['message']);
    

    【讨论】:

    • tks Naija strip_tags 正在处理帖子只提交内容删除标签,但我希望我的表单在提交到数据库之前保护标签帖子,因为如果内容有标签返回到我想要的数据库中填充无用的消息错误信息。
    【解决方案3】:

    阅读:http://php.net/manual/ru/function.htmlspecialchars.php 它可以保护您的网站免受脚本、标签等的影响 另外,如果您想阻止链接,请尝试以下操作: 链接演示:https://regex101.com/r/fV3pO3/1 标签演示:https://regex101.com/r/iQ5lH9/1

    【讨论】:

    • 我已阅读 htmlspecialchars 但它转换为原始文档非功能可行代码但我想保护任何代码来自我的表单返回错误页面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    相关资源
    最近更新 更多