I am new with php, but I have already made a registration script that works fine. But the problem is every time I press the submit button to check my error, I'm going to a new page.
My question is how I make that error comes on the same page?
The code I am useing for the html form.
I want the error display in the error div box that I made Any idea ?
<div id="RegistrationFormLayout">
<h1>Registration Page</h1>
<div id="ErrorMessage"></div>
<form action="script/registration.php" method="post">
<label for="Username">Username</label>
<input type="text" name="Regi_username">
<label for="FirstName">FirstName</label>
<input type="text" name="Regi_Firstname">
<label for="LastName">LastName</label>
<input type="text" name="Regi_Lastname">
<label for="EamilAddress">Regi_EmailAddres</label>
<input type="text" name="Regi_EmailAddres">
<label for="Password">Password</label>
<input type="password" name="Regi_password">
<button type="submit" value="Submit" class="Login_button">Login</button>
</form>
</div>
If I understand correctly, you want form validation errors there. This is a very common pattern, and the simple solution is to always set a form's action attribute to the same page that displays the form. This allows you to do the form processing before trying to display the form (if there are $_POST values). If the validation is successful, send a redirect header to the "next step" page (with header()).
The basic pattern looks like this (in very very simplified PHP)
<?php
if(count($_POST)) {
$errors = array();
$username = trim($_POST['Regi_username']);
if(empty($username)) {
$errors[] = 'username is required';
}
if(count($errors) == 0) {
header('Location: success.php');
die();
}
}
<ul class="errors">
<?php foreach($errors as $error) { ?>
<li><?php echo $error;?></li>
<?php } ?>
</ul>
Related
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)
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"];
Part of your problem is that upon any failed validation you are using a redirect. Alternatively you can display an error message to the user: suggesting they need to correct their input by going back a page (browser back).
When forms get longer users need some hand holding with error correction. Their errors need to be clearly indicated with a message alongside as to how they can fix it.
Avoiding using the 'browser back' method above it's common to have the form send to its own url. I've included an example below.
By doing this you can repopulate the form with posted values upon error and add error feedback. You must be careful to escape user input in this situation.
I've added a generic error feedback notice. Which isn't that helpful in its current form. You could improve upon this by adjusting the validation code to return an array of error notices and use that within your form for more targeted error feedback. You could also add - all fields are required - text to help the user.
Upon successful validation that's when to redirect the user to a confirmation page. This can prevent form resubmissions.
Your name regex pattern in its current form will not allow hyphens or apostrophes. I haven't changed it below. Do bear this in mind. "Michael O'leary" would be faced with an error and likely not understand why. You need to be careful when using strict rules for user input. Also this will reject some unicode.
You also need to escape user input appropriately. Note that you may be satisfied that the name and email after validation follows a particular pattern, but becareful of raw user input. The message text is passed on raw after validation.
<?php
$nome = $_POST['nome'] ?? null;
$email_visitante = $_POST['email'] ?? null;
$mensagem = $_POST['mensagem'] ?? null;
$feedback = null;
if(isset($_POST['submit'])) {
if(validate($nome, $email_visitante, $mensagem) !== false) {
process($nome, $email_visitante, $mensagem);
// Redirect to success/thankyou/confirmation page.
header('location:success.html');
exit;
}
// This is a generic message, could this be more helpful?
$feedback = 'Your form has errors. Please correct them.';
}
form($nome, $email_visitante, $mensagem, $feedback);
function process($nome, $email_visitante, $mensagem) {
// do something with your values.
}
function validate($nome, $email_visitante, $mensagem) {
if(empty($nome)) {
return false;
}
if(empty($email_visitante)){
return false;
}
if(empty($mensagem)){
return false;
}
if (!preg_match("/^[a-zA-Z ]*$/",$nome)) {
return false;
}
if (!filter_var($email_visitante, FILTER_VALIDATE_EMAIL)) {
return false;
}
return true;
}
function form($nome = null, $email_visitante = null, $mensagem = null, $feedback = null) {
?>
<?= $feedback ?>
<form action='' method='POST' name='emailform'>
<div class='form-group'>
<label for='name'>Your name:</label>
<input type='text' id='name' name='nome' value='<?= htmlspecialchars($nome) ?>'>
</div>
<div class='form-group'>
<label for='email'>Your email address:</label>
<input type='text' id='email' name='email' value='<?= htmlspecialchars($email_visitante) ?>'>
</div>
<div class='form-group'>
<label for='message'>Your message:</label>
<textarea class='form-control' cols='30' rows='10' maxlength='300' id='message' name='mensagem'><?= htmlspecialchars($mensagem) ?></textarea>
</div>
<div class='form-group'>
<input type='submit' name='submit' value='Send message'>
</div>
</form>
<?php
}
I want to make Login page with PHP.
And want to use button but it didn't works.
and it looks like just refresh the page.
I tried button tag in the form.
How can I make this works??
<?php
include "login.php";
?>
<form method="post" id="sign">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="email" name="user_mail" id="user_mail" value="<?php echo addslashes($_POST['user_mail'] ?? '') ?>">
<label class="mdl-textfield__label" for="user_mail">Email</label>
</div>
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="password" name="passcode" id="passcode" value="<?php echo addslashes($_POST['passcode'] ?? '') ?>">
<label class="mdl-textfield__label" for="passcode">Password</label>
</div>
</form>
//this <input> works
<input type="submit" name="signup" form="sign"/>
//I want to use this <button>
<button type="submit" name"signup" form "sign" formmethod="post"></button>
<?php
if ($error ?? '') {
echo addslashes($error);
}
login.php
if ($_POST['signup'] ?? '') {
$error = '';
if (!$_POST['user_mail']) $error .= "<br />Please enter email";
else if (!filter_var($_POST['user_mail'], FILTER_VALIDATE_EMAIL)) $error .= "<br />Please enter valid email";
if (!$_POST['passcode']) $error .= "<br />Please enter password";
else {
if (strlen($_POST['passcode']) < 8) $error .= "<br />Please enter a password more than eight";
if (!preg_match('`[A-Z]`', $_POST['passcode'])) $error .= "<br />please least one capital letter";
}
if ($error) $error = "there were errors:" . $error;
<button> means put a button on the page and execute whatever is in the onclick method. <submit> submits a form.
If you want a button to sumbit your form, use the onclick method of the button to do it. Why can't you use submit, though?
See here, they use a link <a onclick='...' but you can do the same for your button: How to submit a form with JavaScript by clicking a link?
As #Arun says below, you can use:
<button type='submit'> inside your form, too. There are lots of ways to do things, so my only advice on top of this is to be consistent. I use input out of habit, and that way I don't have a bunch of mixed conventions throughout my code.
If you want to submit a form on button click, add click event of button using jquery and submit a form like:
Html:
<button type="submit" name"signup" id="btn_submit" value="submit" >Submit</button>
Jquery:
$("#btn_submit").click(function() {
$("#sign").submit(); // submit a form
});
You need to make 2 changes:
Add action attribute
Move your button element inside the form. You can't expect any button on the page to submit your form. It must be inside the form, to which it is associated.
<form method="post" id="sign" action="form-destination.php">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="email" name="user_mail" id="user_mail" value="<?php echo addslashes($_POST['user_mail'] ?? '') ?>">
<label class="mdl-textfield__label" for="user_mail">Email</label>
</div>
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="password" name="passcode" id="passcode" value="<?php echo addslashes($_POST['passcode'] ?? '') ?>">
<label class="mdl-textfield__label" for="passcode">Password</label>
</div>
<button type="submit" name"signup" form "sign" formmethod="post"></button>
</form>
<?php
if ($error ?? '') {
echo addslashes($error);
}
?>
I think you need to put a action on the form element:
<form method="post" id="sign" action="login.php">
i don't know PHP so i might be wrong.
I am new to web designing. Now, I have created a form, and if the user input doesn't meet the requirements I display error message, and if it does I do some mysql commands to enter the info to the database. Now one way to do this is to code the php file into the html and use this command,<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> like described [here][1]
But I don't want to put the script in the same file. How do I do that in another php file such that if user input is invalid, it will return to the homepage with the error message updated?
Here is my code
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="register.css">
</head>
<h1>Register as A new user</h1>
<div id="signup">
<form id="registration_form" action="registration.php" method="post">
<p>
<label>Name</label>
<input type="text" name="name"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Email</label>
<input type="text" name="email"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Password</label>
<input type="password" name="passwd"/>
<span class="errorMessage"></span>
</p>
<p>
<label>Repeat Password</label>
<input type="password" name="repasswd"/>
<span class="errorMessage"></span>
</p>
<input type="submit" class="button" value="sign up"/>
</form>
</div>
What should be in the registration.php? Like the link, I do everything, I set a flag to the error, Now if the flag is true I return the user to the homepage with the error messages, and if false, I show a message saying registration successful. How do I do the part,"return to homepage with the appended error message"?
All your validation and bulletproofing should be in the registration.php
stuff like this:
//both parameters are required, so make sure they were passed-in
if(!isset($_GET['name'])) {
die('Must pass \'name\');
//both parameters are required, so make sure they were passed-in
if(!isset($_GET['email'])) {
die('Must pass \'email\');
}
if(!isset($_GET['passwd'])) {
die('Must pass \'password\');
} else {
//do cool stuff here
}
Don't forget your JS validation as well for the front end. I really hope this helps and gives you a bit of direction.
put your validation codes in "validate.php" or any file name you like
then change the action to validate.php to
then in validate.php if validation matches the requirements.
header("Location: registration.php");
if not match
header("Location: back to the httml with form.php");
You can learn form validation here : http://allitstuff.com/registration-form-in-php-with-validation/
I have a website where any visitor can subscribe to receive the newsletter.I encountered the problem of having my resubmitted when everytime when i refreshed the page.I solved it by applying the PRG concept. Now a user never submits the same form twice, i have just one problem : i have designed the form in such a way that when the is succesfully/or fails a message is display under the input fields. Unfortunatly now that i have the PRG concept applied i never get any message displayed . What to do ?
index.php - where i have the divs containing the submit form and the message display
<div id="newsletter" >
<form id="abonat" name="abonat" action="formular.php" method="post" onsubmit="return golire()" autocomplete="on" >
<span>Subscribe</span>
<input type="text" id="nume" name="nume" placeholder="Name" required />
<input type="email" id="email" name="email" placeholder="Email" autocomplete="off" required/>
<input type="submit" value="Subscribe" class="button" style="width:26%;float:left;" />
</form>
</div>
<div id="mesaj_newsletter">
<span><?php if (isset($mesaj)) echo $mesaj; ?> </span>
</div>
formular.php - where the validation takes place,and the message is decided
include('conect.php');
function validEmail($email){
//code that verifies if it is a valid email adress
}
if( (isset($_POST['email']))&&(isset($_POST['nume'])) ){
$nume=mysql_real_escape_string($_POST['nume']);
$email=mysql_real_escape_string($_POST['email']);
$z=1;
if(validEmail($email)==TRUE){
$result=mysql_query("SELECT * FROM abonat");
while($data=mysql_fetch_row($result)){
if(($data[1]==$email)||($data[2]==$nume))
$z=0;
}
if($z==1){
mysql_query("INSERT INTO abonat(email,nume) VALUES ('$email','$nume')");
$mesaj="Your email has been registered";
}
else $mesaj="You are already registered";
}
else $mesaj="You have not entered a valid email adress";
}
mysql_close($con);
header('Location:index.php');
?>
Try setting a cookie called e.g. $_COOKIE['status_message'] with 60 second timeout.
set_cookie('status_message','This is our message',(time()+60));
Then when the page is refreshed, check to see if the cookie has any data;
if(isset($_COOKIE['status_message'])){
echo $_COOKIE['status_message'];
set_cookie('status_message','',(time()-3600));
}
This will echo out any populated message and destroy the cookie.
Put your $mesag in query string like this
header("Location:index.php?msg=$mesag");
then use $_GET['msg'] on index.php and get value there and display it.
I Have a form which when submitted needs to go to the page and then show one of 4 hidden divs depending on the page.
Here is the form
<form>
<input id="place" name="place" type="text">
<input name="datepicker" type="text" id="datepicker">
<input type="submit" name="submit" id="submit" />
</form>
Here is the page
<div id="brighton">
<p>Brighton</p>
</div>
<div id="devon">
<p>Devon</p>
</div>
<div id="search">
<p>search</p>
</div>
<div id="variety">
<p>variety</p>
</div>
So if Brighton is typed into the place input i need the form to submit the page and show the Brighton div and if Devon is typed in to show the Devon div etc and if the 2/12/2012 is typed into the date picker input and Brighton into the place input it goes to the page and shows the variety div.
i also need it so if the 1/12/2012 is typed in to the date picker input the page redirects to the page show.html.
any help would be greatly appreciated
thanks.
This is easy if you know PHP at all. It looks like you need a good, easy start. Then you will be able to achieve this in seconds.
Refer to W3SCHOOLS PHP Tutorial.
To achieve what you have mentioned, first make the following changes in your form:
<form action="submit.php" method="post">
<input id="place" name="place" type="text">
<input name="datepicker" type="text" id="datepicker">
<input type="submit" name="submit" id="submit" />
</form>
Create a new file called submit.php and add the following code:
<?php
$place = $_POST['place'];
$date = $_POST['datepicker'];
if ($date == '1/12/2012') {
header('Location: show.html');
exit;
}
?>
<?php if ($place == 'Brighton''): ?>
<div id="brighton">
<p>Brighton</p>
</div>
<?php elseif ($place == 'Devon'): ?>
<div id="devon">
<p>Devon</p>
</div>
<?php elseif ($place == 'search'): ?>
<div id="search">
<p>search</p>
</div>
<?php elseif ($place == 'Variety'): ?>
<div id="variety">
<p>variety</p>
</div>
<?php endif; ?>
Now the above example is not the complete solution, but it gives you an idea as to how you can use if-then-else construct in PHP to compare values and do as desired.
Post your form to a php page and then check the posted form parameters to determine which div to show.
<?php
if ($_POST["place"] == "Brighton") {
?>
<div id="brighton">
<p>Brighton</p>
</div>
<?php
} else if ($_POST["place"] == "Devon") {
?>
<div id="devon">
<p>Devon</p>
</div>
<?php
}
?>
Do that for each div and parameter combination. Make sure you set the "method" attribute on your form to "post":
<form action="somepage.php" method="post">...</form>
In the resulting HTML you will only see the one that matches the form parameter.