I am trying to find a way to escape the scripts or tags inserted to my database and at the same time preserve the text formatting. However I bumped into several problems that only solved either of the two.
I’m trying to do it in $blog['title']
and $blog['content']
I tried using nl2br()
to preseve the formatting. It works on preserving the formatting but it still does not escape HTML tags and scripts.
These are my codes. Please note that I am using class where all my functions are there and instantiated the class in my current blog page.
Blog Post HTML Block
<?php if(isset($_GET['id'])){ $selectedBlog = $cakeOrdering->get_data("SELECT blogID, title, content, img, author, dateCreated FROM blogs WHERE blogID = ?", array($_GET['id'])); if(is_array($selectedBlog) || is_object($selectedBlog)){ foreach($selectedBlog as $blog){ ?> <!-- Blog Posts --> <div class="blog_item"> <div class="blog_img"> <img class="img-fluid" src="../img/blogs/<?php echo $blog['img']; ?>" alt=""> </div> <div class="blog_text"> <div class="blog_time"> <div class="float-left"> <a href="#"><?php echo $blog['dateCreated']; ?></a> </div> <div class="float-right"> <ul class="list_style"> <li><a href="#">By : <?php echo $blog['author']; ?></a></li> <li><a href="#">category</a></li> <li><a href="#">Comments: 8</a></li> </ul> </div> </div> <a href="#"><h4><?php echo $cakeOrdering->escape($blog['title']); ?></h4></a> <p style="word-wrap: break-word;"><?php echo $cakeOrdering->escape(nl2br($blog['content'])); ?></p> </div> </div> <?php }}} ?>
I have created a function I called escape in my php class
// Escaping characters public function escape($string){ echo htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); }
if I use this:
$cakeOrdering->escape(nl2br($blog['content']));
but if I remove the escape function like this
nl2br($blog['content']);
it outputs: (preserved formatting but also executes the script)
Advertisement
Answer
Call it the other way round:
nl2br($cakeOrdering->escape($blog['content']));