Hiding a Form after submitted?

Like the title says, I’d like the form to not appear once the user submitted the form, I tried searching it online and it seems like a popular topic but most of them does not work for me, I would really appreciate it if someone could help me out, thank you

Here’s my code:

  <?php
  $name = $age = $password = $email = $username = "";
  $namePU = $agePU = $passwordPU = $emailPU = $usernamePU = $formPU = "";
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $Form_Val = true;
    $name = clean_input($_POST["name"]);
    $age = clean_input($_POST["age"]);
    $password = clean_input($_POST["password"]);
    $email = clean_input($_POST["email"]);
    $username = clean_input($_POST["username"]);


    if (empty($name)) {
      $namePU = "Required";
      $Form_Val = false;
    }

    if (empty($email)) {
      $emailPU = "Required";
      $Form_Val = false;
    }
  
    if (empty($username)) {
      $usernamePU = "Required";
      $Form_Val = false;
    }

    if (empty($password)) {
      $passwordPU = "Required";
      $Form_Val = false;
    }

    if ($Form_Val) {
      $formPU = "Thank you for registering, $name! You can now login with your username $username. The confirmation email has been send to $email.";
    }
  }

  function clean_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
  }
?>
<form method="post" action="index.php">
  Name: <input type="text" name="name">
  <span style="color: #f00;">*<?php echo $namePU;?></span><br>
  Email: <input type="text" name="email">
  <span style="color: #f00;">*<?php echo $emailPU;?></span><br>
  Username: <input type="text" name="username">
  <span style="color: #f00;">*<?php echo $usernamePU;?></span><br>
  Password: <input type="password" name="password">
  <span style="color: #f00;">*<?php echo $passwordPU;?></span><br>
  Age: <input type="number" name="age" min="13" max="120">
  <span style="color: #f00;">*<?php echo $agePU;?></span><br>
  <input type="submit"><br>
</form>
<?php echo $formPU;?>

Use a session variable to ‘remember’ that the registration from processing code has completed without any errors. If this session variable is set and the user is on the registration page, don’t display the registration form and do display the ‘Thank you … The confirmation email …’ message. Clear this session variable when the user navigates to any page other then the registration page.

You would have navigation link(s) on the registration page to allow the user to goto any other page. You do have a ‘registration’ link on the index page to allow the user to goto the registration page?

Also, upon successfully completing the form processing code, you should execute a header() redirect to the exact same URL of the current page to cause a get request for that page. This is referred to as a Post, Redirect, Get - PRG design pattern. This will prevent the browser from trying to re-submit the form data should the user reload the page or navigate away from and back to the page.

1 Like

Well, there are many ways to do this. If you are using this as a login page, you can just redirect it to the home page. Inside the PHP section at the bottom, just before the ?> end, add something like this.

<header “Location: home.php”>

This will switch to the page in the location. Then, in that page you can handle the rest.
Otherwise, you can use SESSION array to save a value and conditionally display different pages depending on a variable. Loosely something like this;

<?PHP
session_start();
some processing here...  Setting a SESSION variable "page" to the correct page...
If ($_SESSION["page"]=="") {
?>
<form> ...  login page here if no page was selected...  </form>
<?PHP
} elseif ($_SESSION["page"]=="home") {
?>
<form> ...  Home page showing this users basic home page after login ... </form>
<?PHP
} elseif ($_SESSION["page"]=="profile") {
?>
<form> ...  User's profile page...  </form>
ETC

Now, to make it easier to follow, I would suggest that you create separate pages depending on what you are attempting to create. The first way would move to the correct page from a menu button or whatever you have on your page and would have a different page for each of the site’s functions. The second way would have everything in one file which is not the preferred way to do it.

But, this depends on what you are doing…

1 Like

Sorry, PDHR, we were typing at the same time… LOL

Hi, nope, If currently still don’t have any navigation links, will it still work? But I’ll try adding a header function, thank you!

Hello, thank you for your reply. If I want it to function something like quiz forms, where once the user clicks the submit button, it’ll still remain to the same URL/page, will your method still works?

Yes, if you only one one page, just use forms and post the new form using your buttons.
Example, if you have a submit button, put a value in it to tell the code what is being selected.
Also, if you have a SELECT drop-down, submit the page on-change of that drop-down.
Once posted, you need to check the submit buttons, ALL of them, to see which was selected
and handle the display as needed for every single button.

Hope that makes sense to you.

1 Like

So sorry for the amount of questions but, how do I add values on my submit button? And also, in order to check the submit buttons, I’ll have to use the ‘isset( )’ function? Tysm :slight_smile:

Ask ALL the question you want to. That is why we are here. To help you learn!

Well, first, normally, you put all these sections at the top of the page. Then, you have your page.
In your page, you use the posted values to alter your content as needed depending on the user inputs.
Here is a basic layout to give you an idea how to handle it. Just a sample, not real code!
( To post this, I started and ended it with four ` s ```` )

<?PHP
//  Check if user posted the page...
if($_SERVER['REQUEST_METHOD'] == 'POST') {
   $errors = "";
   //  User posted the form, now get all of the posted inputs and validate them
   //  To do this check if exists, if so validate them
   if(isset($_POST["email"]) AND trim($_POST["email"])!="") {
      $email = $_POST["email"];
      //  here you would check if this email is in the correct format (validate would be for another post)
   }else{
      $errors .= "Please enter a valid email address!<br>";
   }
   if(isset($_POST["name"]) AND trim($_POST["name"])!="") {
      $name = $_POST["name"];
      //  here you would check if this name is in the correct format (contains letters only as example)
   }else{
      $errors .= "Please enter a valid name!<br>";
   }
   ... continue with all input fields...
}
//  All input fields have been validated and acquired from the posted form.
if ($errors!="") {
   //  No errors were found in the user's inputs.  Now we can process it and save the data as needed
} //  If there were errors, you would not update the data, just display the list of errors in the page...
?>
<html>
... here would be the HTML and CSS for the page ...
<div class="content">   ...  this DIV would be where the content would be displayed conditionally ...
<?PHP
if($errors!="") {
   //  Errors in the user's data were found, just display them!
   echo "There are errors in your input fields, please fix them and continue:<br><br>" . $errors;
}else{
   //  No errors found, now display data based on whatever...
   ...  This is where you use the data to display conditionally whatever you need ...
}

Now, this is just a starting example. One other issue is you do not want the user to have to retype all of the data they previously entered. Therefore, you would need to set the values to the old data they typed during the first attempt. Let’s say they did not enter the email address but all the other data. You would want to show the old data in all the fields except the email address. To do that, you can set all the inputs to nothing before you acquire the posted values. Reset them all before you load and validate the fields. Loosely something like this:

<?PHP
//  Check if user posted the page...
if($_SERVER['REQUEST_METHOD'] == 'POST') {
   $errors = "";
   $name = "";
   $email = "";
   ...  reset all data fields to nothing, then load them again from the posted values ...

This starts with blank data. All fields the user entered data into will be loaded when posted. Data missing will be set to blank. Then, in the fields in your form, you enter the blank or previous data like this:

  Name: <input type="text" name="name" value="<?PHP echo $name; ?>">
  Email: <input type="text" name="email" value="<?PHP echo $email; ?>">

NOTE: PHP is server-side and is executed before the browser sees it, so these are replaced by the data and when sent to the browser, it never sees anything between <?PHP and ?>…

Hope this helps make sense of it all! Good luck!

1 Like

Alright, thank you! :blush:

As for the “if ($errors!=”") " section, why is one of them used for when there’s no error and the other one is used when there is?

Also for this part, do I just display the same thing as:

Or are they both separate things?

And lastly, is the “$errors” under your example the same as “$Form_Val = false;” under mine? Thank you for the examples and explanations :slight_smile:

There’s a mistake in the logic that may be affecting why you are asking that question. Inside the form processing code, at the point of deciding if there are no errors in order to use the submitted form data, you would test if $errors is equal to an empty string $errors == "" or you can use empty($errors). Inside the html document, at the point where you want to display any errors, you would test if $errors is not equal to an empty string $errors != "" or you can use !empty($errors).

1 Like

Ahh, so if I use the ‘if’ function, I’ll just have to do either one of them? (== /!=)

In the meantime, I tried another way on a test file and it worked! But how do I make it work on my previous code? it probably did not work because there are more functions to it (regular patterns etc) And also is there a way to make everything into one page? Since in order for this method to work, I had to add another file to it. But this doesn’t really matter

Here is the working code-

 <?php
 if(isset($_POST['testname'])) {
   $Name = $_POST['name'];
     $test1 = $_POST['test'];
        echo "Welcome back, " . $Name;
} else {
     include 'form.php';
       echo "pls enter ur name";
              }
                 ?>

And here’s the code under ‘form.php’:
image
(sorry had to make it a picture since I’m unable to paste the code here)

Edit: It gives out error messages when I use this method, and also this part of the code doesn’t really work well

Well, EMPTY does not always work. There are occasionally problems with it. Such as with integers.
$a = 0;
This will display as EMPTY. You could check for NULL’s, but, that also has it’s own issues.

To see if an input is really not used, I suggest using isset() function…

if (!isset($name)) {

isset is to see if it is set.
!isset to see if it is NOT set.

But, either way, you need to empty the variable before seeing if it was posted. As in my example, you set $errors = “”; to make sure it is blank. Then add to it if something is wrong. Your last example is from some other type of display setting extra unneeded variables. All those $emailPU, etc, are adding more variables which are not needed if you use the one $errors variable as I posted. But, also, if you are trying to put this code into a reusable format to use on other pages, sometimes the extra waste of variables are just fine.

Lastly, you changed all this around from the original. You stated you wanted to do it in one page and now are using an included file. Not what you asked for. Remember, PHP is handled on the server before the browser ever sees it. Therefore you can use PHP to control the outputs of the HTML/CSS. So, instead of this:

} else {
   include 'form.php';
}

You can just do it this way, dropping out of PHP and going back into it…

} else {
?>
<form ...>
...
</form ...>
<?PHP
}
?>

NOTE: You can post form.php just like any code. Just use four back-ticks in the upper left of your keyboard before and after the code. ( It looks like a backwards apostrophe )

1 Like

Ahh okay, I’ll try to fix my code with your corrections and will get back to you once I’m done, thank you! :slight_smile:

Hi! So sorry for taking so long lol, I’ve added in everything you’ve said and I’m now able to hide the form, thank you so much!

But there’s one problem I’m currently facing, the conditions isn’t working, so right now everything is not required and I’m still able to submit a form that doesn’t follow the correct format (age above 120 etc), here is where I’m at right now :blush:

      <?php
    $name = $age = $password = $email = $username = "";
    $namePU = $agePU = $passwordPU = $emailPU = $usernamePU = $formPU = "";
    if(isset($_POST['testname'])) {
$errors = "";
$name = $_POST["name"];
$age = $_POST["age"];
$password = $_POST["password"];
$repeat = $_POST["repeat"];
$email = $_POST["email"];
$username = $_POST["username"];
echo "Thank you for registering, $name! You can now login with your username $username. The confirmation email has been send to $email.";

 if (!isset($name)) {
 $errors = "Name is required.";
          } elseif (!preg_match("/^[a-zA-Z-']*$/",$name)) {
      $errors = "Only letters, spaces and apostrophes are allowed.";
    }

if (!isset($email)) {
      $errors = "Email is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
       $errors = "Invalid email format.";
    }
  
 if (!isset($username)) {
      $errors = "Username is required.";
    } elseif (!preg_match("/^[0-9a-zA-Z]*$/",$username)) {
      $errors = "Only letters and numbers are allowed";
    }

 if (!isset($password)) {
      $errors = "Password is required.";
    } elseif (!preg_match("/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/",$password)) {
      $errors = "Must contain at least 8 characters, 1 small letter, 1 capital letter and 1 number.";
    } 

 if ($_POST["password"] !== $_POST["repeat"]) {
     $errors = "Password does not match, please try again.";
    }

      function clean_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
  }
    }

 else {
 ?>
 <form method="post" action="index.php">
  Name: <input type="text" name="name">
  <span style="color: #f00;">*<?php echo $namePU;?></span><be>
  Email: <input type="text" name="email">
  <span style="color: #f00;">*<?php echo $emailPU;?></span><be>
  Username: <input type="text" name="username">
  <span style="color: #f00;">*<?php echo $usernamePU;?></span><be>
   Password: <input type="password" name="password">
  <span style="color: #f00;">*<?php echo $passwordPU;?></span><be>
  Repeat Password: <input type="password" name="repeat">
  <span style="color: #f00;">*<?php echo $repeatPU;?></span><be>
 Age: <input type="number" name="age" min="13" max="120">
 <span style="color: #f00;">*<?php echo $agePU;?></span><be>
<input type="submit" value="Submit" name="testname"><be>
           </form>
      <?php
        echo $formPU; 
                           }                     
         ?>

Here’s the output:
image

Thank you!

Except if there are any errors, the user must be able to correct them and resubmit the form. Does your logic do that? Using if(the submit button is set){ process the form } else { display the form } doesn’t do this. In fact, the code to process the form data, which should be above the start of the html document, and the code to display the form, which goes inside the html document, are two separate responsibilities.

There are two things you are trying to accomplish - 1) the logic needed to control when the registration form is displayed, and 2) the implementation code for the form processing and the form.

For item #1 - you want to display the form from the point when the visitor navigates to the registration page (if you are doing this on your main index page, you need to make this a separate page), up to the point when the form processing code has completely executed without any errors. Until you have reached this point, you want to display the form, display any errors, and populate the form field values with any existing data.

BTW - the completion of the registration form processing code would include inserting the submitted data into a database table, detecting any duplicate values in unique fields (username and email), and sending the confirmation email that you have cited in the ‘success’ message. I’m not sure if you are leaving this out for now or you don’t know that code to do this is part of the registration process. You would only display the success message after all these things have successfully occurred.

The logic for the form processing should -

  1. Detect if a post method form has been submitted. You were originally doing this.
  2. If there is more than one form on a page (which you are not ready to do yet), you would additionally detect which form has been submitted. You would use a hidden form field for this and not the submit button. You cannot guarantee that the submit button will be set for all version of all clients, and it won’t be set if you switch to using ajax to submit the data.
  3. Keep the submitted form data as an array, then operate on elements of this array throughout the rest of the code.
  4. Trim all the input data at once. This can be done using one line of code, provided you have done item #3 on this list.
  5. Validate all the inputs, storing validation error messages in an array, using the field as the array index, so that any depended validation steps can test if there is not already an error for a field and so that you can display the error messages adjacent to the fields they belong with.
  6. After the end of the validation, if there are no errors (the array holding the error messages will be empty), use the submitted form data, which would include inserting a row of data in a database table and sending the email.
  7. After all of the above, if there are no errors (inserting the data and sending the email can produce their own errors), redirect to the exact url of the current page to cause a get request for the page. To display the success message after this redirect, store it in a session variable. This session variable is how you can ‘remember’ that the registration process has successfully been completed. You can then use the existence of this session variable to control the display of the form.

See the following example code showing these points -

<?php

session_start();

$post = []; // an array to hold a trimmed working copy of the form data
$errors = []; // an array to hold user/validation error messages

if($_SERVER["REQUEST_METHOD"] == "POST")
{
	// trim all the data at once
	$post = array_map('trim',$_POST);
	
	// validate inputs (this example only shows two of the inputs) -
	// note: php's empty() function considers values to be empty that you may not expect. if you are specifically testing for empty strings, you should use that as your test condition
	if($post['username'] === '')
	{
		// store error messages in the $errors array using the field name as the index
		$errors['username'] = 'Required';
	}
	if($post['password'] === '')
	{
		$errors['password'] = 'Required';
	}
	
	// the rest of the validation logic would go here...
	
	// if there are no errors, use the submitted form data
	if(empty($errors))
	{
		// you would build and execute a prepared INSERT query here...
		// any column that must be unique (username, email) is defined as a unique index
		// to detect duplicate values, you would test if the query produced a duplicate index error
		// if there's only one unique index, the duplicate is in that column
		// if you have more than one unique index, you would then query to find which column(s) contain duplicate values
		// you would add error messages to the $errors array for any duplicate values
		
		// if there are no errors at this point, you would build and send the confrontation email
		
	}
	
	// if no errors at this point, success
	if(empty($errors))
	{
		// fake some values that will be in the final code
		$post['first_name'] = 'first name'; // note: most people have at least a first and last name, not just a name
		$post['email'] = '[email protected]';
		
		// put the success message in a session variable
		$_SESSION['register'] = "Thank you for registering, {$post['first_name']}. You can now login with your username, {$post['username']}. A confirmation email has been sent to {$post['email']}.";
		// redirect to the exact same url of this page to cause a get request - Post, Redirect, Get (PRG)
		die(header("Refresh:0"));
	}
}
?>

<style>
   .er {
		background-color: white;
		color: red;
   }
</style>

<?php
// display the registration form
if(!($_SESSION['register'] ?? false))
{
?>
<form method="post">
<label>Username: <input type="text" name="username" value="<?php echo htmlentities($post['username'] ?? '',ENT_QUOTES); ?>">
<span class='er'>* <?php echo htmlentities($errors['username'] ?? '',ENT_QUOTES);?></span></label><br>
<label>Password: <input type="password" name="password" value="<?php echo htmlentities($post['password'] ?? '',ENT_QUOTES); ?>">
<span class='er'>* <?php echo htmlentities($errors['password'] ?? '',ENT_QUOTES);?></span></label><br>
<input type="submit"><br>
</form>
<?php
}
else
{
	// display the registration success message
	echo htmlentities($_SESSION['register'],ENT_QUOTES);
}
?>
1 Like

Try something like this…

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    //  Reset all input fields
    $name = $age = $password = $email = $username = "";
    $namePU = $agePU = $passwordPU = $emailPU = $usernamePU = $formPU = "";

    //  Get all of the form's input fields
    $name = htmlspecialchars(stripslashes(trim($_POST["name"])));
    $age = htmlspecialchars(stripslashes(trim($_POST["age"])));
    $password = htmlspecialchars(stripslashes(trim($_POST["password"])));
    $repeat = htmlspecialchars(stripslashes(trim($_POST["repeat"])));
    $email = htmlspecialchars(stripslashes(trim($_POST["email"])));
    $username = stripslashes(trim($_POST["username"])));

    //  Validate all inputs
    if (!isset($name) AND trim($name)!="") {
        $errors .= "Name is required.<br>";
    } elseif (!preg_match("/^[a-zA-Z-']*$/",$name)) {
        $errors .= "Only letters, spaces and apostrophes are allowed in name.<br>";
    }
    if (!isset($email) AND trim($email)!="") {
        $errors .= "Email is required.<br>";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors .= "Invalid email format.<br>";
    }
    if (!isset($username) AND trim($username)!="") {
        $errors .= "Username is required.<br>";
    } elseif (!preg_match("/^[0-9a-zA-Z]*$/",$username)) {
        $errors .= "Only letters and numbers are allowed for username!<br>";
    }
    if ( !isset($password) ) {
        $errors .= "Password is required.<br>";
    } elseif (!preg_match("/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/",$password)) {
        $errors .= "Password must contain at least 8 characters, 1 small letter, 1 capital letter and 1 number.<br>";
    }
    if ($_POST["password"] != $_POST["repeat"]) {
        $errors .= "Passwords does not match.";
    }

    //  All fields are acquired and validated, display any errors.
    if ($errors!="") {
        //  Errors found in fields, display these at top of form
        echo "<div style='color:red;'>There are errors in your data:<br>" . $errors . "</div>";
    } else {
        //  No errors in fields, process the live data and store in database
        echo "Thank you for registering, $name! You can now login with your username $username. The confirmation email has been send to $email.";
        //  ...  Here you would save the data in the database and do whatever else you want to with data
    }
}
?>
 <form method="post" action="index.php">

NOTES: First, note that for adding to the errors list I am using " period equal " NOT just " equal "…
This concatenates the errors one after the other. If you just use the equal sign, it will only show the last error not all of them. Also, I display them in red so they stand out. For the validation section, I use various ways to make sure they are correct. Checking first for empty or no inputs and then special handling for each one. For example the email address must have a @ in it, etc. To check if empty, I usually check if the variable does not exist, but, use trim when getting them. This prevents the user from entering blanks only. I also moved your other two stripslashes and specialchars to the first part, just do them all when you acquire the posted versions. This runs faster than calling a function. Or, you can replace all of that using the filter_input() function. But, you can learn about that on your own later.

Hope that helps get you started… ( Did not test all this, just an example… )

1 Like

Thank you so much for your detailed explanations! I’m able to learn new kind of code I personally haven’t learnt yet. But I still don’t really understand the ‘session_start();’ function, so sorry I’m really new to php ahah

Hi, your example worked just fine, thank you!! As for line 8-13, why is ‘stripslashes’ necessary? But other than that, I’m able to understand most of it, thank you :blush:

Sponsor our Newsletter | Privacy Policy | Terms of Service