I working on two pages, a first one which has a form with three fields: name, email and message). This page will send these data to a second page, that will validate if those fields meet the criteria.
If on the second page, any of those fields does not meet the criteria, I want to redirect to the first page (or a third php one), fill the form with previous information and tell the user to correct the fields properly.
I’m strugling to send the data form the second page to the first (or third) one. Does anyone knows a good way to do it?
Here’s my code:
First page – contato.html
<form action="validate.php" method="POST" name="emailform"> <div class="form-group"> <input type="text" id="name" name="nome" placeholder="Type your name"> </div> <div class="form-group"> <input type="text" id="email" name="email" placeholder="type your@email.com here"> </div> <div class="form-group"> <textarea class="form-control" cols="30" rows="10" maxlength="300" id="message" name="mensagem" placeholder="Leave your message." ></textarea> </div> <div class="form-group"> <input type="submit" name="submit" value="Send message" onclick="alert('Thank you!')" ></form>
Second Page – validate.php
if(isset($_POST['nome'])) $nome = $_POST['nome']; if(isset($_POST['email'])) $email_visitante = $_POST['email']; if(isset($_POST['mensagem'])) $mensagem = $_POST['mensagem']; // if does not meet the criteria, redirect to contato.html and update the form with the info if(empty($nome)){ Header("location:contato.html"); } if(empty($email_visitante)){ Header("location:contato.html"); } if(empty($mensagem)){ Header("location:contato.html"); } // check for letters and space only if (!preg_match("/^[a-zA-Z ]*$/",$nome)) { Header("location:contato.html"); } // check if e-mail address is well-formed if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) { Header("location:contato.php"); }
Does anyone knows how to do it? Either sending to a third page or redirecting to the first one (and fill the form in again)
Advertisement
Answer
You have to use sessions and store data there in one page and access in another, here is a small usage
<?php // page 1 session_start(); // Set session variables $_SESSION["nome"] = $nome; $_SESSION["email"] = $email_visitante; $_SESSION["mensagem"] = $mensagem; <?php // page 2|3|N - any other page session_start(); // Get session variables $nome = $_SESSION["nome"]; $email_visitante = $_SESSION["email"]; $mensagem = $_SESSION["mensagem"];