How To Remove HTML Tags In PHP & MYSQL – Simple Example

Welcome to a tutorial on how to remove HTML tags in PHP and MySQL. So you have completed your comments system, forum, review, or whatever that accepts user feedback. But there is one problem – Bad guys are abusing it by adding all sorts of funky HTML and script tags.

To remove HTML tags in PHP, we can either use the strip_tags() or htmlentities() function:

  • The strip_tags() function will remove all HTML tags. For example, $clean = strip_tags("<p>Foo</p> Bar"); will result in Foo Bar.
  • The htmlentities() function will not remove but convert all symbols into HTML entities. For example,  $clean = htmlentities("<p>Foo</p>"); will result in &lt;p&gt;Foo&lt;/p&gt;
  • Lastly, we can also create a stored function in MySQL to strip HTML tags as an alternative.

That covers the basics, but let us walk through a few examples in this guide, read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Remove HTML Tags Useful Bits & Links
Tutorial Video The End

 

 

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

  • Create a test database and import the 1-database.sql file.
  • Change the database settings in 2-remove-html.php to your own and launch it in the browser.
  • Alternatively, import 3a-strip-tag.sql for the stored MySQL function and check out 3b-insert.sql.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

REMOVE HTML TAGS

All right, let us now get into the examples on how to remove HTML tags in PHP and MySQL.

 

1) DUMMY REVIEW TABLE

1-database.sql
CREATE TABLE `reviews` (
  `review_id` int(255) NOT NULL,
  `review_name` varchar(255) NOT NULL,
  `review_text` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `reviews`
  ADD PRIMARY KEY (`review_id`);

ALTER TABLE `reviews`
  MODIFY `review_id` int(255) NOT NULL AUTO_INCREMENT;

For this example, we will be using a dummy review table. Pretty straightforward with only 3 fields –

  • review_id ID, primary key.
  • review_name Name of reviewer.
  • review_text The review itself.

 

 

2) REMOVE HTML TAGS WITH PHP

2-remove-html.php
<?php
// (A) THE PROBLEMETIC REVIEW
$_POST = [
  "name" => "Le Hackr",
  "text" => "<strong>Good product!</strong> <p>Foo Bar</p>".
            "<script>alert('POO PAR')</script>"
];
 
// ! CHANGE DATABASE SETTINGS TO YOUR OWN !
$dbhost = '127.0.0.1';
$dbname = 'test';
$dbuser = 'root';
$dbpass = '';
$dbchar = 'utf8';
$pdo = new PDO(
  "mysql:host=$dbhost;dbname=$dbname;charset=$dbchar", 
  $dbuser, $dbpass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
  ]
);
 
// (C) INSERT SQL
$stmt = $pdo->prepare(
  "INSERT INTO `reviews` (`review_name`, `review_text`) VALUES (?, ?)"
);
 
// (C1) STRIP ALL HTML TAGS
echo $stmt->execute([
  $_POST['name'],
  strip_tags($_POST['text'])
]) ? "OK" : "ERROR!" ;
 
// (C2) STRIP HTML TAGS (BUT SELECTIVELY ALLOW SOME)
echo $stmt->execute([
  $_POST['name'],
  strip_tags($_POST['text'], "<p><strong>")
]) ? "OK" : "ERROR!" ;
 
// (C3) ALLOW HTML BUT CONVERT TO HTML ENTITIES
echo $stmt->execute([
  $_POST['name'],
  htmlentities($_POST['text'])
]) ? "OK" : "ERROR!" ;

Yep, it’s that simple. As in the introduction above:

  • We can use strip_tags(STRING) to remove all HTML tags from a string.
  • To allow some tags, we can pass in a second parameter – strip_tags(STRING, ALLOWED).
  • If you are creating a coding website that allows users to share their code snippets, use htmlentities(STRING) instead.

 

 

3) ALTERNATIVE – STORED MYSQL FUNCTION

3a-function.sql
DELIMITER $$
CREATE FUNCTION `strip_tags`($str text) 
RETURNS text
DETERMINISTIC
BEGIN
  DECLARE $start, $end INT DEFAULT 1;
  LOOP
    SET $start = LOCATE("<", $str, $start);
    IF (!$start) THEN RETURN $str; END IF;
    SET $end = LOCATE(">", $str, $start);
    IF (!$end) THEN SET $end = $start; END IF;
    SET $str = INSERT($str, $start, $end - $start + 1, "");
  END LOOP;
END$$
DELIMITER ;

Credits to the contributors on this post on StackOverflow. If you have not already heard about it, yes, we can store functions in MySQL (we also call them procedures). All we have to do is to create a similar strip_tags() function and use it in our SQL statements.

3b-insert.sql
INSERT INTO `reviews` 
  (`review_name`, `review_text`) 
VALUES 
  ('Jane Doe', strip_tags('Hello world <strong>foo</strong> bar'));

 

 

USEFUL BITS & LINKS

That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

How To Remove HTML Tags In PHP MySQL (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *