Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo HTML tag into php input value

Tags:

html

php

I have problem , I want to echo the string which is html tag, so I don't know how to say that but this is my code

echo '<input type="hidden" name="id" value='.($row['id']).'>';

where the value of $row['id'] is '<b>test</b>', the problem is on the output of the echo, the closing tag of <b> will close the input tag, so the value of input just '<b' thanks.

like image 767
Aldy syahdeini Avatar asked Aug 16 '26 06:08

Aldy syahdeini


2 Answers

htmlentities($row['id'],ENT_QUOTES) this will encode < > to &lt; and &gt;

$str = "A 'quote' is <b>bold</b>";


echo htmlentities($str);
// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;

echo htmlentities($str, ENT_QUOTES);
// Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;

Both above are correct, second one safer.

like image 169
Flash Thunder Avatar answered Aug 17 '26 19:08

Flash Thunder


  1. Pass data through htmlspecialchars to make it safe for inserting into HTML attributes (by converting characters with special meaning to entities).
  2. Quote attribute values (your code doesn't have " around the outputted row id) so that spaces, = and so on will be treated as part of the value

Such:

echo '<input type="hidden" name="id" value="'. htmlspecialchars($row['id']) . '">';

Or, better yet, don't output chunks of markup in PHP mode, switch to straight output mode until you need a variable / function call:

<input type="hidden" name="id" value="<?php echo htmlspecialchars($row['id']); ?>">
like image 40
Quentin Avatar answered Aug 17 '26 21:08

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!