HTML / CSSを使用してサイトを構築した後、PHPとスクリプトの基本を学んでいます。メールアドレスと名前を収集するためだけに、データベースに送信する簡単なフォームを作成しようとしています。以下は私が使用しているコードの基本です。いくつかの調整がありますが、大きなことは何もありません。私はこのデータをサニタイズする必要があることを知っており、これを行う方法に関する数十の投稿や記事などを読んだことがありますが、escape_stringまたはPHP関数をこれに追加する方法がわかりません。やったと思って何十通りも試しましたが、テストしてみると何の違いもないようです。私はこれをしているのは私の初心者の無知だけだと知っていますが、私は髪を引っ張っているようなものなので、どんな助けも素晴らしいでしょう。
<?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);
?>
@ 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);
?>