Grow your CSS skills. Land your dream job.

Last updated on:

Cleaning Variables

Variables that are submitted via web forms always need to be cleaned/sanitized before use in any way, to prevent against all kinds of different malicious intent.

Technique #1

function clean($value) {

       // If magic quotes not turned on add slashes.

       // Adds the slashes.
       { $value = addslashes($value); }

       // Strip any tags from the value.
       $value = strip_tags($value);

       // Return the value out of the function.
       return $value;

$sample = "<a href='#'>test</a>";
$sample = clean($sample);
echo $sample;


  1. This is a good start, but it isn’t anywhere near as efficient as it needs to be in today’s PHP usage.
    Look into htmlspecialchars() and/or htmlentities(), stripslashes() and (for database users) mysqli_real_escape_string()

    Example usage:

    function clean($str, $entities = true) {
        // Strip user-added slashes
        $str = stripslashes($str);
        // Optional "overkill" - remove *all* backslashes
        $str = str_replace('\\', '', $str);
        // Strip tags
        $str = strip_tags($str);
        // If entities = true, make the string XSS safe (to a degree)
        if($entities == true)
            $str = htmlspecialchars($str);
        // Return the string
        return $str;

    I’d only recommend using that on output.
    If you’re submitting to a database (like posting a comment, for example), then escape your data!!

    // Assuming you're already connected to the database using procedural mysqli
    $_POST['user_posted_data'] = mysqli_real_escape_string($conn, $_POST['user_posted_data'];
    // Then query the database.

    Of course, I’d advocate PDO over mysqli_*() functions, as they automatically escape (for lack of a better description)

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".