-1

I have a form that sends datas to my DB.

However I want to make sure it is safe.

I used to use htmlspecialchars($variableToSecure)

But I learned it is not enough (protects only from html injections)

I searched on internet and found mysql_real_escape_string($variableToSecure)

But this one is obsolete and doesn't exist since php 7.0

I wish to know what is the best way to secure a variable now?

agone07
  • 51
  • 6

1 Answers1

0

The best thing to do is use PDO with prepared statements, which looks like this:

$pdo = new PDO('connection string');

$stmt = $pdo->prepare('SELECT * FROM myTable WHERE myField = :myParam');
$stmt->bindValue(':myParam', 'actual value which goes into the statement', PDO::PARAM_STR);
$stmt->execute();

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

More info on PDO: https://www.php.net/manual/en/book.pdo.php

This protects against SQL injection attacks, you'll also need to do some filtering on your inputs to prevent XSS attacks, for example if you're displaying HTML from the database you need to ensure the user can't add <script> tags as this could allow them to run arbitrary code in your users browsers.

Matt
  • 1,073
  • 1
  • 8
  • 14