Providing Default Values for Text Fields in PHP


How To Supply Default Values for Text Fields in PHP?



If you want to provide a default value to a text field in your form, you need to pay attention to following notes:

  • The default value should be provided in the 'VALUE=default_value' attribute in the <INPUT TYPE=TEXT ...> tag.
  • The length of the default value should be less than the max length specified in the "MAXLENGTH=nnn" attribute. If you provide default value longer than the max length, the default value will be truncated when submitted.
  • You should put the default value inside double-quotes as 'VALUE="$default_value"' to protect spaces.
  • You must apply htmlspecialchars() translation function to the default value to protect HTML sensitive characters, like double quotes.

The PHP script below is a modified version of submit_comments.php with a default value in the "comment" field:

  $comment = 'I want to say: "It\'s a good site! :->"';
  $comment = htmlspecialchars($comment);
  print("<html><form action=processing_forms.php method=post>");
  print("<table><tr><td colspan=2>Please enter and submit your"
    ." comments about</td></tr>");
  print("<tr><td>Your Name:</td>"
    ."<td><input type=text name=name></td></tr>\n");
    ."<td><input type=text name=comment value=\"$comment\" size=40>"
  print("<tr><td colspan=2><input type=submit><td></tr></table>\n");

If you view this PHP page, you will a form with default value nicely displayed in the comment field. If you submit the form, you will get something like this:

Number of values: 2
  name = Alan
  comment = I want to say: \"It\'s a good site! :->\"

Notice that special characters are protected with slashes when form is submitted. See the next tip on how to remove slashes.


Removing Slashes on Submitted Input Values in PHP

Retrieving Input Values from Checkboxes in PHP

Processing Web Forms in PHP

⇑⇑ PHP Tutorials

2016-11-13, 1169👍, 0💬