htmlentities() does not work

Asked

Viewed 218 times

0

Hello,

I am saving HTML code in a session variable:

$_SESSION["recuperarInvalido"] = "<p id='recuperarInvalido'> O e-mail introduzido é inválido! </p>";

But when typing the session variable value:

echo htmlentities($_SESSION["recuperarInvalido"]);

In the browser appears like this:

<p id='recuperarInvalido'> O e-mail introduzido é inválido! </p>

But you should show up like this:

O e-mail introduzido é inválido!
  • has already started the session? session_start();

  • @Guilhermespinxo Yes, it’s started.

3 answers

2

echo $_SESSION["recuperarInvalido"];

just remove "htmlentities()", as it was made to convert html to string, to literally show html on the front!

2

Miguel,

I searched here, and according to the w3schools the function htmlentities is used to just do the opposite of what you want. It is made so that a String is completely displayed by the browser, no matter what its content is. So char < and > are converted into &lt; and &gt; and are not interpreted by the browser as html tags but as text.

To get what you want, simply remove the function htmlentities:

echo $_SESSION["recuperarInvalido"];

However, I must warn you that this will work, but it is not the best approach. I believe that it is not a good practice to write HTML code in the backend, usually I leave the HTML to the template file.

The user William posted a reply just below that leaves the php code of your backend, more separate from your HTML code.

1

Let’s see, you could store session values in a variable $session

$session = $_SESSION["recuperarInvalido"] = 'O e-mail introduzido é inválido!';

Here you check if there is a $_SESSION['recuperarInvalido'], if there is an ai yes you have the browser render.

<?php
        if (isset($session)) {
        ?>
            <p id='recuperarInvalido'> ><?php echo $session; ?> </p> 
    <?php } ?>

This way I find more practical.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.