php - htmlspecialchars() on array of values fetch -


lets fetch data pdo

$stmt = $this->dbh->prepare("select * posts");     $stmt->execute();     $result = $stmt->fetchall();     return $result; 

how should use htmlspecialchars() before displaying results using echo on view page? is ok escape array of results right after fetchall() or should escape results 1 one in view page?

if use htmlspecialchars() right after fetch, following work?

$stmt = $this->dbh->prepare("select * posts");     $stmt->execute();     $result = $stmt->fetchall();     $results=  implode(',', $results);     $results= htmlspecialchars($results);     $results= explode(',', $results);     return $results; 

disregarding whether solution in question works (it not marc b pointed out), technically doesn't matter where encode values long encoded before being written page. it's pretty design decision.

let me note though htmlspecialchars() not holy grail against xss. protects when output written in html context, not when it's written javascript example.

consider this:

...your html content... <script type="text/javascript">     var myvar = <?= myvar ?>; </script> ... 

in case, calling htmlspecialchars() on myvar not enough if may contain user input. in example above, don't need special character exploit xss. same applies things <div onclick="myfun('something', <?=myvar?>)"> -- it's still javascript context, need different encoding.

a full tutorial on xss not fit (and believe not belong) in answer here, wanted raise attention fact html encoding not enough @ all.

having said that, applying htmlspecialchars() right after reading data database think wrong, because @ point don't care data used (what context written into). may separation of concerns thing in code.

so spare encoding data until gets written page, because know encoding use.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -