Home » Php » How can I set the value of a textbox through PHP?

How can I set the value of a textbox through PHP?

Posted by: admin July 12, 2020 Leave a comment

Questions:

So I have this empty textboxes in a registrationg page. The user enters some data, hits continue and then there’s a confirmation page. If the data is incorrect, the user hits go back to go correct whatever was wrong. However, when he goes back, all the textboxes are empty. So the first thing that comes to my mind is to store the user data in a Session (I have a User class that holds all this data so I store the class in the session). When the user goes back I am able to retrieve the data.

I do something like this:

if($_SESSION['UserInfo'])
{
    $user = $_SESSION['UserInfo'];

    $firstName = $user->FirstName;
    $lastName = $user->LastName;
}

How would I put these variables in a textbox?

How to&Answers:

To set the value, you can just echo out the content inside the value attribute:

<input type="text" name="firstname" value="<?php echo htmlentities($firstName); ?>" />
<input type="text" name="lastname" value="<?php echo htmlentities($lastName); ?>" />

Answer:

Of course you will want to escape it but…

<input type="text" value="<?php echo $firstName ?>" />

or if the form is posted, it would be easier to do:

<input type="text" name="firstName" value="<?php echo $_POST['firstName'] ?>" />

fine… even though it was out of the scope of the question here is the escaped version:

<input type="text" name="firstName" value="<?php echo htmlentities($_POST['firstName']) ?>" />

Answer:

smth like

<input type="text" value="<?php echo $first_name;?>">

Don’t forget to escape with htmlentities() or smth similar. If you don’t know why – google XSS.