LoginSignup
0
0

More than 1 year has passed since last update.

prepareメソッドでセキュリティ強化

Posted at

SQLでの危険なコード

input.html
  <form action="input_do.php" method="post">
    <textarea name = "memo" cols="50" rows='10' placeholder="自由にメモを残して"></textarea></br>
    <button type='submit'>登録する</button>
  </form>
input_do1.php
  try{
    $db = new PDO('mysql:dbname=〜);

    $db->exec('INSERT INTO memos SET memo="' . $_POST['memo'] . '", created_at=NOW()');
  } ~

例えば、上記のinput.htmlのform内から入力した内容をデータベースに保存する場合がある。
上記例だと、input_do.php内のSQLである$_POST['memo']を、そのまま記述してしまうと書き換えられる危険性がある。

pepare関数で対策

input_do2.php
  <?php
  try{
    $db = new PDO('mysql:dbname=〜);

    $statement = $db->prepare('INSERT INTO memos SET memo=?, created_at=NOW()');
    $statement -> execute(array($_POST['memo']));

  } ~
  ?>

まず、$statementという変数を作り、$dbオブジェクトにprepareメソッドを使用する。prepareメソッド内にSQL文を挿入して、memo=$_POST['memo']をmemo=?とする。
この? にindex.htmlのformから入力した値が入る。
また、危険な方は$db ->exec となっていたが、$statment->executeとなっている。
executeメソッド内には実際に何が入るかという値を指定している。この中にmemo=?の入力値が入る。

まとめ

いまいち細かい理屈はわからなかったが、

SQLが固定されいている時

$db ->exec を使う

QLがユーザー次第で変わる時

$db->prepareを変数に入れる。
prepareの中身の変動するSQLに = ? とする。
$変数名->executeを使う

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0