I'm converting my Form Validation code into function but problem is that it's giving error Undefined index of $confirm variable which is already define and also confirm password is not working.
Function
function formValidation($action,$confirm){
$result = "";
$input = $_POST[$action];
$confirm = $_POST[$confirm];
// For Email Validation
$find = 'email';
$path = $action;
$pos = strpos($path,$find);
if(empty(user_input($input))){
$result = "$action is missing";
}elseif($pos !== false){
$email = filter_var($input, FILTER_SANITIZE_EMAIL);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$result = "Email invalid format";
}
}elseif($confirm !== $_POST['password']){
$result = "password is not confirm";
}
return $result;
}
And there is any way I call function one time and it checkx all fields and return error
Trigger
$email_err = $password_err = $username_err = $confirmPWD_err = "";
if(isset($_POST['submit'])){
$email_err = formValidation('prd_email','');
$password_err = formValidation('password','');
$username_err = formValidation('username','');
$confirmPWD_err = formValidation('password','confirm');
}
HTML
<form method="post">
<div class="form-group">
<input class="form-control" placeholder="username" name="username" type="text" />
<?php echo $username_err ?>
</div>
<div class="form-group">
<input class="form-control" placeholder="email" name="prd_email" type="text" />
<?php echo $email_err ?>
</div>
<div class="form-group">
<input class="form-control" placeholder="password" name="password" type="password" />
<?php echo $password_err ?>
</div>
<div class="form-group">
<input class="form-control" placeholder="Confirm Password" name="confirm" type="password" />
<?php echo $confirmPWD_err ?>
</div>
<input type="submit" class="btn btn-success" name="submit" value="submit" />
</form>
Try this, is it working for you?
function formValidation($action,$confirm = null){
$result = "";
$input = $_POST[$action];
if($confirm){$confirm = $_POST[$confirm];}
// For Email Validation
$find = 'email';
$path = $action;
$pos = strpos($path,$find);
if(empty(user_input($input))){
$result = "$action is missing";
}elseif($pos !== false){
$email = filter_var($input, FILTER_SANITIZE_EMAIL);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$result = "Email invalid format";
}
}elseif(!empty($confirm) && $confirm !== $_POST['password']){
$result = "password is not confirm";
}
return $result;
}
And call the function like this
if (isset($_POST['submit'])) {
$email_err = formValidation('prd_email');
$password_err = formValidation('password');
$username_err = formValidation('username');
$confirmPWD_err = formValidation('password', 'confirm');
}
Related
I'm trying to create a PHP registration script using PDO prepared statements with positional placeholders. But the MySQL queries don't execute. var_dump(); doesn't display any error.
I desperately need someone to closely look at my code and explain to me why the queries don't execute.
Below is a rewrite of register.php, which now displays errors, if certain, predefined conditions are not met. However, it doesn't display any error, when the insert or select query fail. var_dump(); doesn't display any error either, even though PDO queries fail to execute.
Please, I need your help to fix this. Your time and input are much appreciated in advance. Thanks.
register.php:
<?php
// include configuration file
require ("includes/config.php");
//Class import for image uploading
//classes is the map where the class file is stored (one above the root)
include ("classes/upload/upload_class.php");
// define variables and set to empty values
$firstnameErr = $lastnameErr = $usernameErr = $genderErr = $passwordErr = $confirmationErr = $emailErr = $birthdayErr = $phoneErr = "";
$firstname = $lastname = $username = $gender = $password = $confirmation = $email = $birthday = $phone = "";
// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$firstname = student_input($_POST["firstname"]);
$lastname = student_input($_POST["lastname"]);
$username = student_input($_POST["username"]);
$gender = student_input($_POST["gender"]);
$password = student_input($_POST["password"]);
$confirmation = student_input($_POST["confirmation"]);
$email = student_input($_POST["email"]);
$birthday = student_input($_POST["birthday"]);
$phone = student_input($_POST["phone"]);
// validate submission
if (empty($_POST["firstname"]))
{
$firstnameErr = "First name is required.";
}
else
{
$firstname = student_input($_POST["firstname"]);
}
if(empty($_POST["lastname"]))
{
$lastnameErr = "Last name is required.";
}
else
{
$lastname = student_input($_POST["lastname"]);
}
if(empty($_POST["username"]))
{
$usernameErr = "Username is required.";
}
else if(!empty($_POST["username"]))
{
// validate username
if (!preg_match("/^[a-zA-Z0-9]*$/", $username))
{
$usernameErr = "Username must contain only letters and numbers.";
}
if (strlen($username) < 4 || strlen($username) > 10)
{
$usernameErr = "Username must be from 4 to 10 characters.";
}
}
else
{
$username = student_input($_POST["username"]);
}
if(empty($_POST["gender"]))
{
$genderErr = "Gender is required.";
}
else
{
$gender = student_input($_POST["gender"]);
}
if(empty($_POST["password"]))
{
$passwordErr = "Enter a password.";
}
else if(!empty($_POST["password"]))
{
// validate username
if (!preg_match("/^[a-zA-Z0-9]*$/", $password))
{
$passwordErr = "Password must contain letters, numbers and special characters.";
}
if (strlen($password) < 8 || strlen($password) > 20)
{
$passwordErr = "Password must be from 8 to 20 characters.";
}
}
else if (empty($_POST["confirmation"]))
{
$confirmationErr = "Confirm your password.";
}
else if ($_POST["password"] != $_POST["confirmation"])
{
$confirmationErr = "Password and confirmation don't match.";
}
else
{
$password = student_input($_POST["password"]);
}
if(empty($_POST["email"]))
{
$emailErr = "Your email address is required.";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}
else
{
$email = student_input($_POST["email"]);
}
if(empty($_POST["birthday"]))
{
$birthdayErr = "Birthday is required.";
}
else if(!empty($_POST["birthday"]))
{
$today = date("d-m-Y");
$diff = date_diff(date_create($birthday), date_create($today));
if($diff->format('%y%') < 6)
{
$birthdayErr = "You must be at least 6 years old to register.";
}
else
{
$birthday = student_input($_POST["birthday"]);
}
}
if(empty($_POST["phone"]))
{
$phoneErr = "Phone number is required.";
}
else if(!empty($_POST["phone"]))
{
// Don't allow country codes to be included (assumes a leading "+")
if (preg_match('/^(\+)[\s]*(.*)$/',$phone))
{
$phoneErr = "You should not include the country code.";
}
// Remove hyphens - they are not part of a telephone number
$phone = str_replace ('-', '', $phone);
// Now check that all the characters are digits
if (!preg_match('/^[0-9]{10,11}$/',$phone))
{
$phoneErr = "Phone number should be either 10 or 11 digits";
}
// Now check that the first digit is 0
if (!preg_match('/^0[0-9]{9,10}$/',$phone))
{
$phoneErr = "The telephone number should start with a 0";
}
else
{
$phone = student_input($_POST["phone"]);
}
}
else if(!empty($_FILES["userimage"]))
{
//This is the directory where images will be saved
$max_size = 1024*250; // the max. size for uploading
$my_upload = new file_upload;
$my_upload->upload_dir = "images/user/"; // "files" is the folder for the uploaded files (you have to create this folder)
$my_upload->extensions = array(".png", ".gif", ".jpeg", ".jpg"); // specify the allowed extensions here
// $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)
$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
$my_upload->rename_file = false;
$my_upload->the_temp_file = $_FILES['userimage']['tmp_name'];
$my_upload->the_file = $_FILES['userimage']['name'];
$my_upload->http_error = $_FILES['userimage']['error'];
$my_upload->replace = "y";
$my_upload->do_filename_check = "n"; // use this boolean to check for a valid filename
if ($my_upload->upload()) // new name is an additional filename information, use this to rename the uploaded file
{
$full_path = $my_upload->upload_dir.$my_upload->file_copy;
$imagename = $my_upload->file_copy;
}
else
{
$imagename = "";
}
}
else
{
try
{
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute(student_input($_POST["username"]));
$user = $stmt->fetch(); # get users data
if($user["username"]==$username)
{
$errorMsg[]="Sorry username already exists"; //check condition username already exists
}
else if($user["email"]==$email)
{
$errorMsg[]="Sorry email already exists"; //check condition email already exists
}
else if($user["phone"]==$phone)
{
$errorMsg[]="Sorry, the phone number already exists"; //check condition email already exists
}
else if(!isset($errorMsg)) //check no "$errorMs g" show then continue
{
$new_password = password_hash($password, PASSWORD_DEFAULT); //encrypt password using password_hash()
// insert form input into database
$stmt= $pdo->prepare("INSERT INTO users (firstname, lastname, username, gender, password, email, birthday, phone, userimage) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")->execute($data);
// find out user's ID
$stmt = $pdo->query("SELECT LAST_INSERT_ID() AS user_id");
$user_id = $stmt[0]["user_id"];
// redirect to list users page
header("Location: userinfo.php");
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
// render the header template
include("templates/header.php");
// render add user template
include("templates/register-form.php");
// render the footer template
include("templates/footer.php");
?>
I have the following, relevant code in functions.php, which is called by the config.php:
// validate user input
function student_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Another thing: how do I print the errors on the register-form.php right below any existing error's input field?
register-form.php:
<br>
<br>
<h1>Register</h1>
<br>
<form enctype="multipart/form-data" action="register.php" method="post">
<fieldset>
<div class="form-group">
<label>First Name:</label><span class ="error">*</span> <input autofocus class="form-control" name="firstname" placeholder="First Name" type="text"/>
<span class = "error"><?php //echo $errorMsg["firstname"];?></span>
</div>
<div class="form-group">
<label>Last Name:</label><span class ="error">*</span> <input class="form-control" name="lastname" placeholder="Last Name" type="text"/><br />
<span class = "error"><?php //echo $errorMsg["lastname"];?></span>
</div>
<div class="form-group">
<label>Username:</label><span class ="error">*</span> <input class="form-control" name="username" type="text"/><br />
<span class = "error"><?php //echo $errorMsg["username"];?></span>
</div>
<div class="form-group">
<label>Gender:</label><span class ="error">*</span> <select class="form-control" name="gender" value="gender">
<option value="">Select your gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Password:</label><span class ="error">*</span> <input class="form-control" name="password" type="password"/ autocomplete="off"><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Confirm Password:</label><span class ="error">*</span> <input class="form-control" name="confirmation" type="password"/><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Email:</label><span class ="error">*</span> <input class="form-control" name="email" placeholder="Email" type="text"/><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Phone:</label><span class ="error">*</span> <input class="form-control" name="phone" placeholder="Phone" type="tel" min="10" max="11"/><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Date of Birth:</label><span class ="error"></span> <input class="form-control" name="birthday" placeholder="birthday" type="date" /><br />
<span class = "error"><?php //echo $error[birthday];?></span>
</div>
<div class="form-group">
<label>Passport Photo:</label><input class="form-control" name="userimage" id="fileimage" placeholder="Your Photo" type="file"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default" name="Register" value="Register">Register</button>
</div>
</fieldset>
</form>
<div>
or Login
</div>
<br/>
<br>
<br>
I have a form and all the validations, now I want to show the error messages in front of the text field not in the url. How do I do this?
Here is my PHP code:
<?php
if ((isset($_POST['submit']))){
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$fullname_valid = $email_valid = $username_valid = $password_valid = false;
if(!empty($fullname)){
if (strlen($fullname) > 2 && strlen($fullname)<=30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
}else {$fmsg .="fullname can contain only alphabets <br>";}
}else{$fmsg1 .="fullname must be 2 to 30 char long <br>";}
}else{$fmsg2 .="fullname can not be blank <br>";}
if (!empty($email)) {
if (filter_var($email , FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con,$query2) or die("can not fire query".mysqli_error($con));
if (mysqli_num_rows($fire2)>0) {
$msg .=$email."is already taken please try another one<br> ";
}else{
$email_valid=true;
}
# code...
}else{$msg .=$email."is an invalid email address <br> ";}
# code...
}else{$msg .="email can not be blank <br>";}
if(!empty($username)){
if (strlen($username) > 4 && strlen($username)<=15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con,$query) or die("can not fire query".mysqli_error($con));
if(mysqli_num_rows($fire)> 0){
$umsg ='<p style="color:#cc0000;">username already taken</p>';
}else{
$username_valid = true;
}
# code...
# code...
}else {$msg.= "username can contain only alphabets <br>";}
}else{$msg.= "username must be 4 to 15 char long <br>";}
}else{$msg.="username can not be blank <br>";}
if (!empty($password)) {
if (strlen($password) >=5 && strlen($password) <= 15 ) {
$password_valid = true;
$password = md5($password);
# code...
}else{$msg .= $password."password must be between 5 to 15 character long<br>";}
# code...
}else{$msg .= "password can not be blank <br>";}
if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con,$query) or die ("can not insert data into database".mysqli_error($con));
if ($fire){
header("Location: dashboard.php");}
}else{
header("Location: createaccount.php?msg=".$msg);
}
}
?>
and this is my html code:
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<div class="form-input">
<input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">
</div>
<input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">
<span id="message"></span>
<div class="form-input">
<input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
</div>
<div>
<input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
</div>
<div>
<input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
</div>
<div>
<input type="submit" name="submit" id="submit"
value="sign up" class="btn btn-primary btn-block">
forgot password?
<h3>have an account? log in</h3>
</div>
</form>
How do I get the error message in front of my text field, and also how do I get the specified error in front of the specified text field? I don't want to use ajax or javascript. I want to do it with PHP. I have tried this but no luck.
<?php if(isset($errorfname)) { echo $errorfname; } ?>
send msg to get params is not good idea.
Use session
$_SESSION['error_msg'] = $msg
header("Location: createaccount.php");
and add get error in php
$errors = '';
if(isset($_SESSION['error_msg'])) { $errors = $_SESSION['error_msg']; } ?>
and in html show $errors
By looking at your form does not have an action attribute therefore one can concluded that you are submitting the form at the same page as the form PHP_SELF
So if you want to display the error next to the field I would advice that you first declare an empty variables for each text error on top of your page then echo the variables next to each field.
<?php
$emailError = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$errors = 0;
if ((isset($_POST['submit']))) {
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$fullname_valid = $email_valid = $username_valid = $password_valid = false;
if (!empty($fullname)) {
if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
} else {
$fullnameError = "fullname can contain only alphabets <br>";
$errors++;
}
} else {
$fullnameError = "fullname must be 2 to 30 char long <br>";
$errors++;
}
} else {
$fullnameError = "fullname can not be blank <br>";
$errors++;
}
if (!empty($email)) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con, $query2) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire2) > 0) {
$emailError = $email . "is already taken please try another one<br> ";
} else {
$email_valid = true;
}
# code...
} else {
$emailError = $email . "is an invalid email address <br> ";
$errors++;
}
# code...
} else {
$emailError = "email can not be blank <br>";
}
if (!empty($username)) {
if (strlen($username) > 4 && strlen($username) <= 15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con, $query) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire) > 0) {
$usernameError = '<p style="color:#cc0000;">username already taken</p>';
$errors++;
} else {
$username_valid = true;
}
} else {
$usernameError = "username can contain only alphabets <br>";
$errors++;
}
} else {
$usernameError = "username must be 4 to 15 char long <br>";
$errors++;
}
} else {
$usernameError = "username can not be blank <br>";
$errors++;
}
if (!empty($password)) {
if (strlen($password) >= 5 && strlen($password) <= 15) {
$password_valid = true;
$password = md5($password);
# code...
} else {
$passwordError = $password . "password must be between 5 to 15 character long<br>";
$errors++;
}
# code...
} else {
$passwordError = "password can not be blank <br>";
$errors++;
}
//if there's no errors insert into database
if ($errors <= 0) {
if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
if ($fire) {
header("Location: dashboard.php");
}
}
}
}
?>
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<div class="form-input">
<input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">
<!-- display email error here -->
<?php echo $emailError?>
</div>
<input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">
<span id="message"></span>
<div class="form-input">
<input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
<?php echo $fullnameError?>
</div>
<div>
<input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
<?php echo $usernameError?>
</div>
<div>
<input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
<?php echo $passwordError?>
</div>
<div>
<input type="submit" name="submit" id="submit" value="sign up" class="btn btn-primary btn-block">
forgot password?
<h3>have an account? log in</h3>
</div>
</form>
NB: I would advice that you look into password_hash() and
password_verify()to hash your passwords, they provide better
security as compared tomd5()` and make sure your database column is
atleast 60 characters in length.. I would also advice to look into
prepared statements.
The following can help :
How can I prevent SQL injection in PHP?
Using PHP 5.5's password_hash and password_verify function
I think the best way is include from template in result
if ($fire){
header("Location: dashboard.php");
}else{
include("createaccount.php");
}
And in createaccount.php
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<p class="errors"><?= $msg ?></p>
...
I have got the following problem. It is a simple login and reg surface.
Register:
<form method="post">
Username :
<input type="text" name="username" placeholder="Username">
<br>
E-mail :
<input type="text" name="email" placeholder="E-mail ">
<br>
Password :
<input type="password" name="password" placeholder="Password">
<br>
<?php
if (isset($_POST['email']) && isset($_POST['password']) && isset($_POST['username'])) {
$allDatas = json_decode(file_get_contents('data.json'), true);
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$foundUser = false;
$valid = false;
//check the values
if (empty($_POST["email"])) {
?> <font size="1px"><?php echo "Email is required !"; ?> </font><?php
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
?> <font size="1px"><?php echo "Invalid email format!"; ?> </font><?php
}
}
if (empty($_POST["password"])) {
?> <br><font size="1px"><?php echo "Password is required !"; ?> </font><?php
}
if (empty($_POST["username"])) {
?> <br><font size="1px"><?php echo "Username is required !"; ?> </font><?php
}
//is it exists
foreach ($allDatas as $value) {
if ($value[0] == $username) {
?> <br><font size="1px"><?php echo "Username exists!"; ?> </font><?php
$foundUser = true;
break;
} elseif ($value[2] == $email) {
?> <br><font size="1px"><?php echo "E-Mail registered!";?> </font><br><?php
$foundUser = true;
break;
}
}
//add to database
if(!empty($_POST["password"]) && !empty($_POST["username"])&& !empty($_POST["email"]) && filter_var($email, FILTER_VALIDATE_EMAIL)){$valid = true;}
if (!$foundUser && $valid) {
$allDatas[] = array($username, $email, $password);
file_put_contents('data.json', json_encode($allDatas));
echo "Done";
}
unset($allDatas);
}
?>
<br>
<input type="submit" value="Registration">
</form>
<br>
<form action="index.php">
<input type="submit" name="back" value="Back">
</form>
and the login:
<form method="post">
Email:
<input type="text" name="email" placeholder="Email">
<br>
Password:
<input type="password" name="password" placeholder="Password">
<br>
<?php
$allDatas = json_decode(file_get_contents('data.json'), true);
$foundUser = false;
$action = "login.php";
if (isset($_POST['email']) && isset($_POST['password']) ) {
$password = $_POST['password'];
$email = $_POST["email"];
if (empty($_POST["email"])) {
?> <font size="1px"><?php echo "Email is required !"; ?> </font><?php
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
?> <font size="1px"><?php echo "Invalid email format!"; ?> </font><?php
}
}
if (empty($_POST["password"])) {
?> <br><font size="1px"><?php echo "Password is required !"; ?> </font><?php
}
foreach ($allDatas as $value) {
if ($value[2] == $email && $value[1] == $password) {
$foundUser = true;
$username = $value[0];
?> <font size="1px"><?php echo "Success! Welcome ", $username, " !"; ?> </font><?php
$action = "reddragon.html";
}
}
}
if(!$foundUser)
{
?><br> <font size="1px"><?php echo "Please type your datas!"; ?> </font><?php
}
?>
<br>
<input type="submit" value="Log in">
<br>
</form>
<font color="red" size="1px">Before you play, LOG IN!</font>
<form action="<?php echo "$action";?>">
<input type="submit" name="play" value="Play">
</form>
<form action="index.php">
<input type="submit" name="back" value="Back">
</form>
My problem is that, when I add a new member (username, psw, mail), it will be added to the JSON database, but the login surface does not see it! The old ones are ok, but the new one, that I've created by registration is not accepted by the login.
What can be the solution?
flip $email and $password on line #54 of register.php as follows:
$allDatas[] = array($username, $password, $email);
how to pass the collected input to another page after self validate in php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<body>
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr =$mobileTelNoErr = $sendMethodErr = "";
$forename = $surname = $email = $postalAddress = $landLineTelNo = $mobileTelNo = $sendMethod = "";
if($_SERVER["REQUEST_METHOD"] =="POST"){
$valid = true;
if(empty($_POST["forename"])){
$forenameErr = "Forename is required";
$valid = false; //false
} else {
$forename = test_input($_POST["forename"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["surname"])){
$surnameErr = "Surname is required";
$valid = false; //false
} else {
$surname = test_input($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["postalAddress"])){
$postalAddressErr =" Please enter postal address";
$valid = false; //false
} else {
$postalAddress = test_input($_POST["postalAddress"]);
}
if(empty($_POST["landLineTelNo"])){
$landLineTelNoErr = "Please enter a telephone number";
$valid = false; //false
} else {
$landLineTelNo = test_input($_POST["landLineTelNo"]);
// check if invalid telephone number added
if (!preg_match("/^[0-9 ]{7,}$/",$landLineTelNo)) {
$landLineTelNoErr = "Invalid telephone number entered";
}
}
if(empty($_POST["mobileTelNo"])){
$mobileTelNoErr = "Please enter a telephone number";
$valid = false; //false
} else {
$mobileTelNo = test_input($_POST["mobileTelNo"]);
// check if invalid telephone number added
if (!preg_match("/^[0-9 ]{7,}$/",$mobileTelNo)) {
$mobileTelNoErr = "Invalid telephone number entered";
}
}
if(empty($_POST["email"])){
$emailErr = "Email is required";
$valid = false; //false
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(empty($_POST["sendMethod"])){
$sendMethodErr = "Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//if valid then redirect
if($valid){
header('Location: userdetail.php');
exit();
}
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error">* <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error">* <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> </span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> * <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" placeholder="example:012-3456789" value="<?php echo $mobileTelNo;?>" />
<span class="error"><?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>" placeholder="example:123#hotmail.com"/>
<span class="error"> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error">* <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="checkbox" value="check" id="agree" />
I have read and agree to the Terms and Conditions and Privacy Policy
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</fieldset>
</form>
</div>
</body>
</html>
here is my php form...
it can validate itself in the same page but couldn't pass the data to another php page....
here is my another php code...
<?php
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr =$mobileTelNoErr = $sendMethodErr = "";
$forename = $surname = $email = $postalAddress = $landLineTelNo = $mobileTelNo = $sendMethod = "";
echo "<h1>Successfull submission :</h1>";
echo "<p>Forename : $forename <p/>";
echo "<p>Surname : $surname <p/>";
echo "<p>Email: $email</p>";
echo "<p>Post Address: $postalAddress</p>";
echo "<p>Landline: $landLineTelNo</p>";
echo "<p>Mobile : $mobileTelNo</p>";
echo "<p>Contact method: $sendMethod";
?>
You can use $_SESSION variables.
PHP $_SESSIONS
PHP Sessions and Cookies
So after the users has been validated set $_SESSION['surname'] = $surname;
Then on the top of each page add session_start(); to the top.
Then Under that add
if (isset($_SESSION['surname'])) {
$surname = $_SESSION['surname'];
} else {
die();
}
View the PHP docs for a more thorough understanding.
You may also want to look into setting up a MYSQL database if you want users to be able to create accounts.
Edit: form page
if($valid){
$_SESSION['surname'] = $surname;
$_SESSION['postalAddress'] = $postalAddress;
header('Location: userdetail.php');
exit();
}
I am new to php. I have tried the following code to redirect the page when sign In button is clicked, but it is not happening. please help me editing the code. probably, there is an error in header() function. Have I used the header() function correctly?
<body>
<?php
$emailErr = $passwordErr = "";
$email = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "*Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["password"])) {
$passwordErr = "*Password is required";
} else {
$password = test_input($_POST["password"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
include("signInform.php");
if($_POST["sign"])
{
header('Location:signInform.php');
}
?>
<br/><br/><br/><br/><br/>
<h1>WELCOME</h1>
<h2>Please, Register Yourself!</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>E-mail:</label><br />
<input type="text" name="email"/>
<span class="error"> <?php echo $emailErr;?></span>
<br />
<label>Password:</label><br />
<input type="password" name="password"/>
<span class="error"> <?php echo $passwordErr;?></span>
<br /><br />
<input type="submit" value="Register"/><br/>
<p>If already a user, Sign in! </p>
<input type="submit" value="Sign In" name="sign"/><br/>
</form>
</body>
Add #ob_start(); top of the page,
if (isset($_POST["sign"])) {
header('Location:signInform.php');
}
Just remove following line.
include("signInform.php");
and put header function like below.
header('location:signInform.php');
your issue is header already send.You can avoid this issue by using ob_start().Try like this:
<?php
ob_start();
$emailErr = $passwordErr = "";
$email = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["email"]))
{
$emailErr = "*Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["password"]))
{$passwordErr = "*Password is required";}
else
{$password = test_input($_POST["password"]);}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
include("signInform.php");
if($_POST["sign"])
{
header('Location:signInform.php');
exit();
}
?>
<body>
<br/><br/><br/><br/><br/>
<h1>WELCOME</h1>
<h2>Please, Register Yourself!</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>E-mail:</label><br />
<input type="text" name="email"/>
<span class="error"> <?php echo $emailErr;?></span>
<br />
<label>Password:</label><br />
<input type="password" name="password"/>
<span class="error"> <?php echo $passwordErr;?></span>
<br /><br />
<input type="submit" value="Register"/><br/>
<p>If already a user, Sign in! </p>
<input type="submit" value="Sign In" name="sign"/><br/>
</form>
</body>
use--- echo '<script> location.href="signInform.php";</script>';
instead of header('Location:signInform.php');
replace if($_POST["sign"])
{
header('Location:signInform.php');
}
to
if($_POST["sign"])
{
echo '<script> location.href="signInform.php";</script>';
}
and why did you include include("signInform.php"); this line that's why showing error already sent.