Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set HTML value attribute (with spaces)

Tags:

html

forms

php

When I use PHP to set the value of a HTML form input element, it works fine provided I don't have any spaces in the data.

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

If I enter "Jonathan" as the username, it is repeated back to me as expected. If I enter "Big Ted", however, I only get "Big" repeated back when I submit the form.

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

like image 650
DatsunBing Avatar asked Jun 20 '10 04:06

DatsunBing


People also ask

Can HTML attributes have spaces?

Yes. The name attribute contains CDATA. It can be more or less anything you like. (You shouldn't include leading or tailing white space because user agents can ignore it, but white space in the middle is fine).

Can data attributes have spaces?

And, of course, any data-* attribute value can contain spaces that are meaningful (including leading and trailing spaces) so those spaces have to be reflected when accessing the element using that attribute value.

Can HTML tag names have spaces?

Rule 6: Tag Names Cannot Contain Spaces.


2 Answers

Quote it. Otherwise the space will just become an attribute separator and everything after spaces will be seen as element attributes. Rightclick page in webbrowser and view source. It should not look like this (also see syntax highlight colors):

<input value=Big Ted>

but rather this

<input value="Big Ted">

Not to mention that this would still break 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']) : ''); ?>">
like image 64
BalusC Avatar answered Oct 14 '22 22:10

BalusC


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

You have to wrap the variable result with quotes, so that the browser can know what's the content of the input.

like image 45
Cristian Avatar answered Oct 14 '22 22:10

Cristian