Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

For more information on how Google's third-party cookies operate and handle your data, see: Google Privacy Policy

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

#PHP

How to Keep Form Data After Submit and Refresh Using PHP

If you need a website or want to collaborate, contact me or find our more.

Author: Radu

Pay once, use forever—get huge lifetime software deals on ProductCanyon • Ad

Whenever a user adds some invalid data to a form and submits it, the page will have to refresh to show the errors, in case you don’t use JavaScript or something like that.

The bad news is that the input data will disappear, which can be very annoying, especially if the form has many fields.

Luckily, there are two simple methods that you can use.

1. Keep Form Data on Refresh Using the PHP Ternary Operator

The ternary operator is a shorter and more practical version of the standard if/else statement.

It’s used like this:

<?php $a ? $b : $c;

This translates into something like this:

<?php
    if ($a) {
        // do $b
        $b;
    } else {
    // do $c
        $c;
    }

So, to use this in a form to remember the data after the user presses submit and the page refreshes, you’ll have to add this in the value="" attribute of the input:

<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name'], ENT_QUOTES) : ''; ?>

You should wrap the output in htmlspecialchars() for security.

So, the input HTML tag should look like this:

<input name="name" type="text" value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name'], ENT_QUOTES) : ''; ?>">

What this does is to display the data in the name field if it’s set (added by the user). Otherwise, leave it empty.

2. Keep the Form Data on Refresh with the PHP Null Coalescing Operator

In PHP 7, the null coalescing operator was introduced, which is equivalent to the ternary operator, but shorter.

This:

<?php echo $_POST['name'] ?? ''; ?>

is equivalent to this:

<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>

So, to keep the input data on submit and refresh, use it in the value="" attribute, like this:

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

But, again, you should use htmlspecialchars() for security.

<input type="text" name="name" value="<?php echo htmlspecialchars($_POST['name'] ?? '', ENT_QUOTES); ?>">

Note that you have to add the operator inside the htmlspecialchars() function. Otherwise, you’ll get an “Undefined index” error.

You Can’t Always Make Use of the HTML Value Attribute

There are cases where you can’t use the value="" attribute to add a ternary or coalescing operator. So, you need to get more creative.

Let’s take the <select> HTML tag as an example, where you’ll have to use the values for $_POST.

To keep the data on refresh in a <select> tag with PHP, you can make use of the selected HTML attribute, which makes an <option> to be selected by default.

So, you’ll have to add something like this in the <option> tag:

<?php echo (isset($_POST['select']) && $_POST['select'] === 'option1') ? 'selected' : ''; ?>

If <select> has a value, and if it’s equal to the <option> value, then echo selected, otherwise, don’t echo anything.

Here’s the whole part :

<select name="select" id="">
    <option value="">Select</option>
    <option value="option1" <?php echo (isset($_POST['select']) && $_POST['select'] === 'option1') ? 'selected' : ''; ?>>Option 1</option>
    <option value="option2" <?php echo (isset($_POST['select']) && $_POST['select'] === 'option2') ? 'selected' : ''; ?>>Option 2</option>
</select>

Careful with <textarea>.

Unlike inputs, <textarea> has an ending tag: </textarea>.

So, you need to put the PHP operator between the tags, not inside.

<textarea name="message">   
    <?php echo isset($_POST['message']) ? htmlspecialchars($_POST['message'], ENT_QUOTES) : ''; ?>    
</textarea>

I made this mistake, of course. 😃

This Won’t Work for The File Input

The above methods won’t work for the File input, for security reasons.

And I’m not aware of any other workaround with PHP. Perhaps with some Javascript.

So, the users will have to upload the file again if the page refreshes but the form isn’t submitted successfully.

That’s a Wrap

If this post helped you, please consider following me on Bluesky or Instagram to support me.

Also, don't hesitate to contact me if you're interested in my web design services, want to collaborate, or just have something to say.

About Radu

I've been working online from home for over 11 years, gaining valuable experience and developing a wide range of skills, including web design and development, optimization, and SEO.

More posts