Trying to enter, display, save and retrieve code as text

I am using php blog code from code-projects.org which is actually pretty good. My problem is, in the blog content I want to display code examples.

If I enter html on the screen, obviously it gets read as html rather than text
If I use &gt and &lt it gets saved to mysql database first time but when I load it and save it again the special characters are lost and the actual html characters are stored exactly as on the screen. So next time I open page it is wrong again

Any suggestions

So is the question how to display code on the screen? Or what exactly?

Two options are,

echo htmlentities($the_code);

or printing in pre tags

<pre>
<p>this will be like this</p>
</pre>
not like this

OK, I already tried pre tags but they only preserve white spaces I will look into htmlentities - thank you. I think I need to investigate further myself as it is more complicated I think. I think I need to look at it several different ways. Basically my problem is I am using a form to update the MySQL database - which works - I can save html characters by entering < and > in the MySQL table - that works ok. But when I use the form to display and edit and save again, the html tags are interpreted and formatted text is displayed.
So I enter in form - &lt;b&gt;hello world&lt;/b&gt;
It is saved in database as - &amp;lt;b&amp;gt;hello world&amp;lt;/b&amp;gt;<b&><br></b&>
Screen refreshes and displays - <b>hello world</b> - Perfect, exactly what I want!
But then if I save the form to database again it displays as hello world
and the database contains - &lt;b&gt;hello world&lt;/b&gt;<b&><br></b&>
I need to do something like the preformatted text option (Ctrl+Shift+C) in this forum text editor. What I am doing here to explain my problem is exactly what I want to do with my form.
Thanks for your kind assistance.
Kerry

Hi again
OK I have got some success, if I enter
<code>&amp;lt;b&amp;gt;hello world&amp;lt;/b&amp;gt;</code>
directly in the database it works, it displays ok and updates ok
My problem now is trying to find out what to enter in the form to get
<code>&amp;lt;b&amp;gt;hello world&amp;lt;/b&amp;gt;</code>
entered in the database

have you tried using strip_tags? assign the post data to a variable before entering into db: $message = strip_tags($_POST["message"], '<code><b>'); then display it from the db as: html_entity_decode($message);

OK, making progress slowly, I honestly thought there would be something already out there to do this, so many support sites like this are basically blogs that allow you to enter comments and code. So my journey so far …

Thanks johnphpnewb but I don’t actually want to strip the tags out, I want to keep them, display them and be able to edit them. It seems that if I enter on the screen (in the form) -

<a href='test'>Testa>

I need to save in the database -

&amp;amp;lt;a href='test'&amp;amp;gt;Test&amp;amp;lt;/a&amp;amp;gt;
to get this, for some reason, I have to use htmlspecialchars() 3 times.

<?php
$original = "<a href='test'>Test</a>";
echo 'Original = '.$original.'<br>';
$new_1 = htmlspecialchars("<a href='test'>Test</a>", ENT_NOQUOTES);
echo 'new_1 = '.$new_1.'<br>';
$new_2 = htmlspecialchars($new_1, ENT_NOQUOTES);
echo $new_2.'<br>';
$new_3 = htmlspecialchars($new_2, ENT_NOQUOTES);
echo $new_3.'<br>';
?>

This gives the result -

Original = Test
new_1 = <a href=‘test’>Test</a>
&lt;a href=‘test’&gt;Test&lt;/a&gt;
&amp;lt;a href=‘test’&amp;gt;Test&amp;lt;/a&amp;gt;

The next complication is that the only idea I can think of is to identify code blocks with a tag (<* *> or start finish or something like that and then select all sub strings between these tags and replace it with a string processed by a function that runs the above process !! So really if I progress down this route I now need a way to basically identify all occurrences of a substring, between 2 substrings and replace them with processed substrings using the method above - any ideas, advice… anything. :slight_smile: Cheers

1 Like

HI
Thanks to the excellent assistance, advice and suggestions here I have solved my initial problem. I can now save html code to MySQL database, display it, edit it and save it again. If this helps anyone else I will add I am using Windows 10, Xampp with MySql and PHP 7.

The solution as suggested htmlspecialchars() when I create or update - it seems I do not need to use htmlspecialchars_decode()

It has raised another question, which in fairness is a separate question so I will post it as such

Thanks again guys - awesome support site - glad I joined!

Oh! sorry. I thought that you wanted the <code></code> tags to be executed and just display the <b>Hello World!</b> code. I didn’t read your post very well. I haven’t slept much lately. I am very tired.

I made a form and a form output page on my pc with xampp. I get the desired results whenever i use the following code:

form.php

$message = trim(html_entity_decode($_POST["message"]));

formprocess.php

$message1 = html_entity_decode($message);
echo htmlentities(html_entity_decode($message1));

edit: added quotes conversion

echo htmlentities(html_entity_decode($message1, ENT_QUOTES));

html_entity_decode

You need to start using the php website

Thanks johnphpnewb :slight_smile:

Sorry Mrwilson1 but I do not understand

Hi
I would like to thank everybody here for there excellent help and advice, I have learned a lot! It seems that my problem relates to the 3rd party bog script I am using. Everything you have suggested works fine if I code myself, but the blog script applies certain formatting that then messes things up, instead of trying to find work arounds to fix the way the blog script works, I have decided to code myself using the advice I received here, so far things are progressing much more quickly. I am still confused about @ Mrwilson1 comment -

You need to start using the php website

Am I posting in the wrong place, if so - apologies
Thanks again everybody

I understand that you want to type any code into a textarea form control, then convert the text to viewable code after saving to a database. yes?

The code that i’ve posted will work for you, so this is not progress.
Try it yourself:

form.php

<?php
  header("Content-Type: text/html; charset=utf-8");
?>
<!doctype html>
<head>
  <title>Form</title>
</head>
<body>

<div>
<form method="post" action="formsubmit.php">
  <div><textarea name="message" rows="5" placeholder="Enter Code Here"></textarea></div>
  <div><input type="submit" name="submit" value="Submit" /></div>
</form>
</div>

</body>
</html>

formsubmit.php

<?php
  header("Content-Type: text/html; charset=utf-8");
?>
<!doctype html>
<head>
  <title>Form</title>
</head>
<body>

<div>
  <?php
      $message = trim(html_entity_decode($_POST["message"]));
      $message = html_entity_decode($message);
      echo "Encoded/Decoded Output<br /><br />";
      echo "<pre>" . htmlentities(html_entity_decode($message, ENT_QUOTES)) . "</pre>";
  ?>
</div>

</body>
</html>

the logic in the code is simple: since you may sometimes type partially encoded text, then it will pass through the first decode. however, the first pass has nothing to decode if you only have quotes or an ampersand. we decode it again to be sure that the string is fully decoded. Then we fully encode it correctly, then finally decode again for output. You should be able to copy your entire post(s) here and see the results.

just don’t echo output as heredoc syntax because any code will then be rendered, which is bad.

you can optimize the code however you like but the logic is the same: encode/decode

<?php
      $message = trim(html_entity_decode($_POST["message"]), ENT_QUOTES);
      echo "Encoded/Decoded Output<br /><br />";
      echo "<pre>" . htmlentities(html_entity_decode($message, ENT_QUOTES)) . "</pre>";
?>

This is the php site he is referring too. It is actually the PHP manual.

https://www.php.net/manual/en/function.html-entity-decode.php

1 Like

Hi
Many many thanks, you are a star really helpful
Cheers

1 Like

aah OK, I am familiar with this. Problem is the manual is good for seeing syntax, parameters etc but you need to know which command / expression you are looking for first, which is why you contact a support forum. Otherwise it’s like trying to learn to drive from a book :slight_smile:

Hello Kerry, i am happy to help. I am always thankful whenever someone helps me. Giving back to the community is a good thing.

you mentioned that you don’t know why you had to use decode three times and i haven’t explained it clearly. i am usually so tired that i struggle to form sentences. I often sleep five hours per day. My life is hectic right now. Anyway, i believe that php will ignore some of your entries because you are entering partially encoding strings. Thus, quotes will slip through the decode so you have to decode again and again depending upon the text entered. You also added ENT_NOQUOTES which complicated the matter.

if you have xampp, then you can play with code and have no consequences to pay. Try it yourself.

Enter <script>alert("test");</script> into a form. submit the form.
Use echo htmlentities($_POST['message'], ENT_QUOTES, 'utf-8');
this will display &lt;script&gt;alert(&quot;test&quot;);&lt;/script&gt;

if you only use html_entity_decode, then the script will execute and the alert box will appear. this is very bad.

now, i am not n expert so i don’t know if i am correct but i can’t see how my xampp and pc is any different than yours. i don’t like the idea of displaying gibberish as, say, a username:

&lt;script&gt;alert(&quot;test&quot;);&lt;/script&gt;

so i prefer to prevent the code from being executed but not displaying html entities in place of rendered entities. I only ever read about using htmlentities to escape output, but this produces the opposite effect of what i want. I want it to be escaped but also rendered as code on the screen. I’ve played with this long enough now and when i use htmlentities with html_entity_decode, then i get the rendered code that i am looking for. But this is dangerous if you do not properly clean. Thus, i use html_entity_decode twice, then htmlentities(html_entity_decode()) to get the desired results:

Hello, <script>alert("test");</script>
instead of Hello, &lt;script&gt;alert(&quot;test&quot;);&lt;/script&gt;.

i have yet to find reference material about this but it seems to work. However, i am not an expert, so i don’t know if it is correct or not. maybe it is not supposed to work but php has a bug. If the bug were to be repaired, then the code would execute. In this case, i recommend that you just stick with rendering htmlentities() output.

Hi @johnphpnewb I think the big problem I have is the blog script I downloaded. Using your advice I can save and view code as a separate script. I now have to decide whether to hack the code I downloaded or write my own script.
Thanks again for your kind, informative comments.
Kerry

@johnphpnewb - Phew finally cracked it thanks to your help, using this function on create and update - anything between all code tags is displayed as code, everything else is rendered, saves to MySQL and updates - very happy.

function encode($txt) {
 $callback = function($matches) {
   return '<code' . $matches[1] . '>' . htmlentities($matches[2], ENT_QUOTES, 'UTF-8') . '</code>';
 };
 $txt = preg_replace_callback('#\<\s*code(.*?)>(.+?)<\s*\/code\s*>#', $callback, $txt);
 return $txt;
 }
Sponsor our Newsletter | Privacy Policy | Terms of Service