0

I'm working on learning some basic security for a webserver.

I quickly noticed how the difference between storing the values in an array or not before executing them affected the security of the website.

Safe code:

$posts = $_POST['posts'];
$query = $pdo->prepare("insert INTO post (post) VALUES (:post)");
    
$data = array(
':post' => $posts);

$query->execute($data);

Not safe code:

$posts = $_POST['posts'];
$query = $pdo->prepare("insert INTO post (post) VALUES ('$posts')");
$query->execute($data);
  1. How would I be able to inject SQL code into the "Safe code"?
  2. Why is there a difference between the two?
  • 2
    You can't inject into the safe code. That's why it's safe. If you want to learn more about the concept, see [how SQL injection works](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work) and how to [prevent it](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – El_Vanja Jan 19 '21 at 12:03
  • The first one is safe. Nothing can go wrong unless there's a bug in PDO that allows a bypass, and that would literally be front-page news, so you'd hear about it. The second one is an express train to ruining your career, destroying your business, and ending up on [this list](https://codecurmudgeon.com/wp/sql-injection-hall-of-shame/). – tadman Jan 19 '21 at 12:42

0 Answers0