Sol*_*ake 1 php mysql sql input-sanitization
我只是在用HTML/CSS构建网站后学习PHP和脚本的基础知识.我正在尝试创建一个提交到数据库的简单表单,只是为了收集电子邮件地址和名称.下面是基本的我正在使用的代码.我有一些调整,但没什么大不了的.我知道我需要清理这些数据并且我已经阅读了很多关于如何执行此操作的帖子,文章等等.我只是没有看到如何将escape_string或PHP函数添加到此.我以为我做了,我已经尝试了几十种方法,但是当我测试它时似乎没有任何区别.我知道这只是我的noobie无知就是这样做,但我有点拉头发,所以任何帮助都会很棒.
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
Run Code Online (Sandbox Code Playgroud)
@ rwhite35这是最终结果应该是什么样的?
<?php
// sanitize a string in prep for passing a single argument to system() (or similar)
function sanitize_system_string($string, $min='', $max='')
{
$pattern = '/(;|\||`|>|<|&|^|"|'."\n|\r|'".'|{|}|[|]|\)|\()/i';
// no piping, passing possible environment variables ($),
// seperate commands, nested execution, file redirection,
// background processing, special commands (backspace, etc.), quotes
// newlines, or some other special characters
$string = preg_replace($pattern, '', $string);
//make sure this is only interpreted as ONE argument
$string = '"'.preg_replace('/\$/', '\\\$', $string).'"';
$len = strlen($string);
if((($min != '') && ($len < $min)) || (($max != '') && ($len > $max)))
return FALSE;
return $string;
}
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("form-try", $con);
$firstname = sanitize_system_string($_POST['firstname'],2,44);
$lastname = sanitize_system_string($_POST['lastname'],2,44);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
Run Code Online (Sandbox Code Playgroud)
使用PDO扩展的示例:
<?php
$stmt = $dbh->prepare("INSERT INTO Persons (FirstName, LastName, Age) VALUES (?,?,?)");
$stmt->bindParam(1, $_POST[firstname]);
$stmt->bindParam(2, $_POST[lastname]);
$stmt->bindParam(3, $_POST[age]);
$stmt->execute();
?>
Run Code Online (Sandbox Code Playgroud)
这将允许您插入带单引号的记录.
| 归档时间: |
|
| 查看次数: |
1509 次 |
| 最近记录: |