How to set an HTML value attribute (with spaces)

When I use PHP to set the value of an input element of an HTML form, it works fine if I have no data spaces.

<input type="text" name="username" <?php echo (isset($_POST['username'])) ? "value = ".$_POST["username"] : "value = \"\""; ?> /> 

If I enter "Jonathan" as the username, it will be returned to me, as expected. However, if I enter the Big Ted, I only get the Big ones when I submit the form.

Note that the variable $_POST["Username"] correct; when I repeat it using PHP it is set to "Big Ted".

+6
html php forms
source share
5 answers

To quote. Otherwise, the space will simply become an attribute separator and thatโ€™s all after the spaces are considered as attributes of the elements. Right page in web browser and view source. It should not look like this (also see Syntax Highlights):

 <input value=Big Ted> 

but rather it

 <input value="Big Ted"> 

Not to mention that it still breaks when someone has a quote in his name (and your code is thus sensitive to XSS attacks ). Use htmlspecialchars() .

Kickoff example:

 <input value="<?php echo (isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''); ?>"> 
+18
source share
 <input type="text" name="username" <?php echo (isset($_POST['username'])) ? "value = '".$_POST["username"]' : "value = ''"; ?> /> 

You must wrap the result of the variable with quotation marks so that the browser can know what the contents of the input are.

+1
source share
 <input type="text" name="username" <?php echo (isset($_POST['username'])) ? ('value = "'.$_POST["username"].'"') : "value = \"\""; ?> /> 

Keep in mind the use of your quote.

+1
source share

As you can see, it is not PHP5 or even a PHP question at all.
Basic HTML knowledge is a must for anyone who wants to be a PHP user.

And using templates, it looks more neat:

Getting the code of the data part:

 $username = ""; if isset($_POST['username'])) $username = htmlspecialchars($_POST["username"]); 

And the template code:

 <input type="text" name="username" value="<?=$username?>"> 

If you divide the code into 2 parts, it will become more convenient and readable.

+1
source share

just make sure you put a colon after the field, for example:

  <option value="'.$row['name'].'"> 
+1
source share

All Articles