How to prevent html code from being written to the "database"?

146 views Asked by At

The working principle of my code is the following: if in the input line there are have such smileys (":)", ":(") then you need to replace them with pictures. Here's how I do it:

$smile = array(":)", ":(");
$grafic = array("<img src = './image/Smile.png' alt='Smile' align='middle'>",
    "<img src = './image/Sad.png' alt='Smile' align='middle'>");    
$new_message = str_replace($smile, $grafic, $message);

$file = "../data/messages.json";
$json_content = json_decode(file_get_contents($file), true);

if (!empty($new_message)) {
    $json_content[] = array("time" => $time, "user" => $user, "message"  => $new_message);
    file_put_contents($file, json_encode($json_content, JSON_PRETTY_PRINT));
}

But then, I have to write down the already changed string I write in the "database" (json file) and there we can see following:

[
    {
        "time": "1499985376",
        "user": "Max",
        "message": "Hello <img src = '.\/image\/Smile.png' alt='Smile' align='middle'>"
    }
]

How can I write a word "smile" or "sad" instead of the HTML tags?

1

There are 1 answers

2
Armin Šupuk On
  1. Just create a new variable and save the message before you make the changes, like: $rawMessage = $message;.
  2. Then use the $rawMessage to save the message to the database.