46

What is the easiest way to Html encode in PHP?

Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
Mathias F
  • 15,906
  • 22
  • 89
  • 159
  • 5
    I think he means the php equivalent to the ASP.NET method "htmlencode". It is used to sanatize the input by replacing characters like '<' with <. He doesn't want to strip them away. –  Sep 23 '10 at 23:40

4 Answers4

57

By encode, do you mean: Convert all applicable characters to HTML entities?

htmlspecialchars or htmlentities

You can also use strip_tags if you want to remove all HTML tags :

strip_tags

Note: this will NOT stop all XSS attacks

Vallières
  • 1,409
  • 13
  • 17
  • 1
    I am not shure which I have to use. I need this to avoid XSS-atacks. – Mathias F Dec 09 '09 at 13:23
  • 2
    Then htmlspecialchars should do the trick. Or use filter_var with the FILTER_SANITIZE_SPECIAL_CHARS filter. – Arkh Dec 09 '09 at 13:28
  • 11
    `htmlspecialchars` > `htmlentities` in most cases. HTML entities for non-ASCII characters should be a thing of the past; just use UTF-8 and drop the characters straight in. – bobince Dec 09 '09 at 14:55
  • priority will be for htmlspecialchars in php – Moby M Jul 18 '17 at 12:05
5

Encode.php

<h1>Encode HTML CODE</h1>

<form action='htmlencodeoutput.php' method='post'>
<textarea rows='30' cols='100'name='inputval'></textarea>
<input type='submit'>
</form>

htmlencodeoutput.php

<?php

$code=bin2hex($_POST['inputval']); 
$spilt=chunk_split($code,2,"%");
$totallen=strlen($spilt);
 $sublen=$totallen-1;
 $fianlop=substr($spilt,'0', $sublen);
$output="<script>
document.write(unescape('%$fianlop'));
</script>";

?> 
<textarea rows='20' cols='100'><?php echo $output?> </textarea> 

You can encode HTML like this .

Akhila Prakash
  • 481
  • 4
  • 17
2

Try this:

<?php
    $str = "This is some <b>bold</b> text.";
    echo htmlspecialchars($str);
?>
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Moby M
  • 910
  • 2
  • 7
  • 26
1

I searched for hours, and I tried almost everything suggested.
This worked for almost every entity :

$input = "āžšķūņrūķīš ○ àéò ∀∂∋ ©€ ♣♦ ↠ ↔↛ ↙ ℜ℞";


echo htmlentities($input, ENT_HTML5  , 'UTF-8');

result :

&amacr;&zcaron;&scaron;&kcedil;&umacr;&ncedil;r&umacr;&kcedil;&imacr;&scaron; &cir; &agrave;&eacute;&ograve; &forall;&part;&ReverseElement; &copy;&euro; &clubs;&diamondsuit; &twoheadrightarrow; &harr;&nrarr; &swarr; &Rfr;&rx;rx;
Lu Blue
  • 335
  • 3
  • 10