How to set HTML value attribute (with spaces)

后端 未结 5 953
日久生厌
日久生厌 2020-11-27 08:08

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.



        
相关标签:
5条回答
  • 2020-11-27 08:16

    As you see its not PHP5 or even PHP question at all.
    Basic HTML knowledge is obligatory for one who want to be a PHP user.

    And with using templates it looks way more neat:

    Getting data part code:

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

    And template code:

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

    If you divide your code to 2 parts it become way more supportable and readable.

    0 讨论(0)
  • 2020-11-27 08:22
    <input type="text" name="username"
    <?php echo (isset($_POST['username'])) ? ('value = "'.$_POST["username"].'"') : "value = \"\""; ?> />
    

    Be aware of your quote usage.

    0 讨论(0)
  • 2020-11-27 08:25
    <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.

    0 讨论(0)
  • 2020-11-27 08:34

    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']) : ''); ?>">
    
    0 讨论(0)
  • 2020-11-27 08:41

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

      <option value="'.$row['name'].'">
    
    0 讨论(0)
提交回复
热议问题