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 inFoo Bar
. - The
htmlentities()
function will not remove but convert all symbols into HTML entities. For example,$clean = htmlentities("<p>Foo</p>");
will result in<p>Foo</p>
That covers the basics, but let us walk through a few examples in this guide, read on!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
REMOVE HTML TAGS
All right, let us now get into the examples of how to remove HTML tags in PHP and MySQL.
TUTORIAL VIDEO
1) DUMMY REVIEW TABLE
CREATE TABLE `reviews` (
`review_id` bigint(20) NOT NULL,
`review_name` varchar(255) NOT NULL,
`review_text` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `reviews`
ADD PRIMARY KEY (`review_id`);
ALTER TABLE `reviews`
MODIFY `review_id` bigint(20) 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
<?php
// (A) THE PROBLEMETIC REVIEW
$_POST = [
"name" => "Le Hackr",
"text" => "<strong>Good product!</strong> <p>Foo Bar</p>".
"<script>alert('POO PAR')</script>"
];
// (B) CONNECT TO DATABASE - CHANGE SETTINGS TO YOUR OWN !
$dbhost = "127.0.0.1";
$dbname = "test";
$dbuser = "root";
$dbpass = "";
$dbchar = "utf8mb4";
$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) STRIP TAGS MYSQL FUNCTION
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 create and store our own custom functions in MySQL (we also call them procedures).
3B) USING MYSQL STRIP TAGS
INSERT INTO `reviews`
(`review_name`, `review_text`)
VALUES
('Jane Doe', strip_tags('Hello world <strong>foo</strong> bar'));
Then, we can use the custom strip_tags()
function in our SQL statements.
EXTRAS
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
- Strip Tags – Official PHP Manual
- PHP HTML Entities – Official PHP Manual
- Display HTML Code As Text – Code Boxx
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!