B
B
billybons20062016-07-13 15:18:32
PHP
billybons2006, 2016-07-13 15:18:32

What is the best way for a self-written CMS to filter comment data before displaying it?

There is a site, "cms" - self-written. I plan to add the ability to add comments. Data from the form (text, no photos or files there) will be entered into the mysql database using the phpfaq.ru/safemysql class in a raw, unformatted form. The question is how to display this data (text of comments) in the safest way, so as not to get all sorts of xss and other things.
Previously, I did something like this:

$input_text = trim($input_text);
$input_text = strip_tags($input_text);
$input_text = htmlspecialchars($input_text);
$input_text = mysql_escape_string($input_text);

well, and then print($input_text).
Perhaps there is either an established practice, as it is better / more correct, perhaps there is already a ready-made class for this.
Added much later:
I began to look at this SafeMysql class more carefully, I didn’t understand something - it’s not PDO at all. This is a wrapper over mysqli ... I was previously confused by the constantly mentioned placeholders in the text of the class.
For example:
$name = $db->getOne('SELECT name FROM table WHERE id = ?i',$_GET['id']);
Looking in class:
public function getOne()
  {
    $query = $this->prepareQuery(func_get_args());
    if ($res = $this->rawQuery($query))
    {
      $row = $this->fetch($res);
      if (is_array($row)) {
        return reset($row);
      }
      $this->free($res);
    }
    return FALSE;
  }

I look at the private function prepareQuery($args) code, and it just filters by argument types. Something like:
...
switch ($part)
{
case '?n':
  $part = $this->escapeIdent($value);
  break;
case '?s':
  $part = $this->escapeString($value);
  break;
...
}
...

And the actual call to the database:
private function rawQuery($query)
{
...
$res   = mysqli_query($this->conn, $query);
...
}

Can this garden be considered an analogue of PDO, or is it just a class using the deprecated mysqli_query, just with careful data filtering?
Added:
The safemysql class is not PDO, does not use prepared queries, but simply filters the input. The class is convenient, but still I switch to PDO.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2016-07-13
@miraage

1) Working with the database at a low level should be done through PDO. I like Doctrine DBAL for such purposes.
2) Escaping the output: htmlspecialchars($text, ENT_QUOTES, 'utf-8');
// EDIT
This is the approach used in Laravel.
htmlentities($value, ENT_QUOTES, 'UTF-8', false);

D
dev400, 2016-07-13
@dev400

htmlentities()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question