Retaining checkbox value of a form after posting

This is first checkbox
This is second checkbox

Use the checkbox in above form and on submit the status of the Checkboxes are retained.

This tutorial is part of the series where we will try to understand how to retain value of every component of a form. You can read our main tutorial on how to retain value for component of a form here.

We will use php header redirection to post back the values to our main page where checkbox is present. We will call form page as first page and action or submitted page as second page. The form data will be received by second page and after validation it is supposed to complete all the processing and in case of error it will post back the form data back to form page by using query string through address bar.

We will use the example of two checkbox but same system can be extended to more than two or single checkbox in a form.

Here is the code of a form with two checkboxes
$t1=$_GET['t1'];
$t2=$_GET['t2'];

if($t1=="yes"){$t1v="checked";}
else{$t1v=="";}

if($t2=="yes"){$t2v="checked";}
else{$t2v=="";} 

echo "<form method=post action=pb-chk.php>
<input type=checkbox name=t1 value=yes $t1v> This is first checkbox<br>
<input type=checkbox name=t2 value=yes $t2v> This is second checkbox
<input type=submit value=Submit>";
To keep the second page simple we will keep only the redirection part. Here we have excluded the part which takes care if the form passes its validation and execute the actual script.

Inside the file pb-chk.php we receive the data using POST method and create the query string. ( GET method is used to receive data in Form page or pb-check.php page )
Here is the code of second page, pb-chk.php
$t1=$_POST['t1']; // receive form ( checkbox value) data using POST method
$t2=$_POST['t2'];
header ("Location: pb-check.php?t1=$t1&t2=$t2"); // redirect to First page or Form page
Difference between GET and POST method of Form submission
PHP Form Managing Radio button using PHP

Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







AARON

04-01-2019

I have been searching the whole net for this and here I am with the true answer to my problem. Thank you!




PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer