Hello i do have a problem,i do not use js or jq just bootstrap link in head,it shoud pop up if forms are invalid but for some reason it wont,thats my prob.On some my other codes it is working but now it wont here i dont know why,i wouldnt post this,but struggling with trivials like this for a day :( dont give me minuses,i dont ask for plus but neither - I would appreciate hlp!
*Signup back*
<?php
if(isset($_POST['signup-submit'])){
require 'db.inc.php';
$error = false;
$username = $_POST['uid'];
$email = $_POST['mail'];
$pwd = $_POST['pwd'];
$pwdrpt = $_POST['pwd_repeat'];
if (empty($username) || empty($email) || empty($pwd) || empty($pwdrpt)) {
header("location: ../signup.php?error=emptyfields&uid=".$username."&mail=".$email);
exit();
}
// else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)){
// header("location: ../signup.php?error=invalidmail&uid");
// exit();
// }
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error = true;
$errorEmail = 'Please input a valid Email address';
header("location: ../signup.php?error=invalidmail&uid=".$username);
exit();
}
elseif (!preg_match("/^[a-zA-Z0-9]*$/", $username)){
$error = true;
$errorUsername = 'Please input username';
header("location: ../signup.php?error=invaliduid&mail=".$email);
exit();
}
*SignUp front*
<form action="includes/signup.inc.php" method="post" novalidate>
<h3 align="center"><strong>Sign Up<strong></h3>
<!-- <?php
if (isset($_GET['error'])) {
if ($_GET['error'] == 'invalidmail') {
echo '<p class="signuperror">Enter valid email address!</p>';
}
}
?> -->
<input class="form-control" type="text" placeholder="Username" name="uid">
<div><span class="text-danger"><?php if(isset($errorUsername)) echo $errorUsername; ?></span>
</div>
<br>
<input class="form-control" type="text" placeholder="Enter Email" name="mail">
<div><span class="text-danger"><?php if(isset($errorEmail)) echo $errorEmail; ?></span></div>
Try this
<?php
if(isset($_POST['signup-submit'])){
$error = false;
$username = $_POST['uid'];
$email = $_POST['mail'];
if (empty($username) || empty($email)) {
header("location: index1.php?error=emptyfields");
exit();
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error = true;
$errorEmail = 'Please input a valid Email address';
header("location: index1.php?error=invalidmail");
exit();
}
elseif (!preg_match("/^[a-zA-Z0-9]*$/", $username)){
$error = true;
$errorUsername = 'Please input username';
header("location: index1.php?error=invaliduid");
exit();
}
}
?>
<form action="" method="post" novalidate>
<h3 align="center"><strong>Sign Up<strong></h3>
<?php
if (isset($_GET['error'])) {
if ($_GET['error'] == 'invalidmail') {
echo '<p class="signuperror">Enter valid email address!</p>';
}
}
?>
<input class="form-control" type="text" placeholder="Username" name="uid">
<div><span class="text-danger"><?php if(isset($errorUsername)) echo $errorUsername; ?></span>
</div>
<br>
<input class="form-control" type="text" placeholder="Enter Email" name="mail">
<div><span class="text-danger"><?php if(isset($errorEmail)) echo $errorEmail; ?></span></div>
<input type="submit" name="signup-submit" id="signup-submit">
</form>
Related
I am trying to carry out some validation checks on a user signup form using HTML and PHP. I have tried to add in one which checks the character length of the username that's been inputted. When I run the script I do hit the correct URL error: http://localhost:8888/PRCO304/signup.php?error=invalidlengthuname=ttttttt however I do not get the html message that should be returned to the signup.php page to the user. `Which should be: "Username must be at least 8 characters long!"
scripts/signup-script.php:
<?php
// Checking whether the user got to this page by clicking the proper signup button.
if (isset($_POST['signup-submit'])) {
require 'db.php';
$firstName = $_POST['first-name'];
$lastName = $_POST['last-name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
// We check for any empty inputs.
if (empty($firstName) || empty($lastName) || empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
header("Location: ../signup.php?error=emptyfields&uname=".$username."&mail=".$email);
exit();
}
// We check for an invalid username AND invalid e-mail.
else if (!preg_match("/^[a-zA-Z0-9]*$/", $username) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?error=invalidunamemail");
exit();
}
// We check for an invalid username. In this case ONLY letters and numbers.
else if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../signup.php?error=invaliduname&mail=".$email);
exit();
}
// We check for minimum amount of characters in username.
else if (strlen($username <= 7)) {
header("Location: ../signup.php?error=invalidlengthuname=".$username);
exit();
}
// We check for an invalid e-mail.
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?error=invalidmail&uname=".$username);
exit();
}
// We check if the repeated password is NOT the same.
else if ($password !== $passwordRepeat) {
header("Location: ../signup.php?error=passwordcheck&uname=".$username."&mail=".$email);
exit();
}
else {
$sql = "SELECT username FROM student WHERE username = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error we send the user back to the signup page.
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $username);
// Then we execute the prepared statement and send it to the database!
mysqli_stmt_execute($stmt);
// Then we store the result from the statement.
mysqli_stmt_store_result($stmt);
// Then we get the number of result we received from our statement. This tells us whether the username already exists or not!
$resultCount = mysqli_stmt_num_rows($stmt);
// Then we close the prepared statement!
mysqli_stmt_close($stmt);
// Here we check if the username exists.
if ($resultCount > 0) {
header("Location: ../signup.php?error=usertaken&mail=".$email);
exit();
}
else {
$sql = "INSERT INTO student (firstName, lastName, username, email, pwd) VALUES (?, ?, ?, ?, ?);";
// Here we initialize a new statement using the connection from the db.php file.
$stmt = mysqli_stmt_init($conn);
// Then we prepare our SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error we send the user back to the signup page.
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
// If there is no error then we continue the script!
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sssss", $firstName, $lastName, $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
// If the user tries to access this page an inproper way, we send them back to the signup page.
header("Location: ../signup.php");
exit();
}
signup.php:
<?php
// The index homepage includes the header
require 'header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Homepage</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta charset="utf-8">
<!-- CSS STYLING -->
<link href="./style.css" type="text/css" rel="stylesheet">
</head>
<body>
<!-- The start of my Foldy Grids -->
<section id="content">
<div class="container">
<section id="grid" class="clearfix">
<div class="cf show-grid">
<div class="row">
<div class="grid-1">grid-1</div>
<div class="grid-4">
<?php
// Here we create an error messages if the user made an error trying to sign up.
if (isset($_GET["error"])) {
if ($_GET["error"] == "emptyfields") {
echo '<p class="signuperror">Fill in all fields!</p>';
}
else if ($_GET["error"] == "invalidunamedmail") {
echo '<p class="signuperror">Invalid username and email!</p>';
}
else if ($_GET["error"] == "invaliduname") {
echo '<p class="signuperror">Invalid username!</p>';
}
else if ($_GET["error"] == "invalidmail") {
echo '<p class="signuperror">Invalid email!</p>';
}
else if ($_GET["error"] == "passwordcheck") {
echo '<p class="signuperror">Your passwords do not match!</p>';
}
else if ($_GET["error"] == "usertaken") {
echo '<p class="signuperror">Username is already taken!</p>';
}
else if ($_GET["error"] == "invalidlengthuname") {
echo '<p class="signuperror">Username must be at least 8 characters long!</p>';
}
}
// Here we create a success message if the new user was created.
else if (isset($_GET["signup"])) {
if ($_GET["signup"] == "success") {
echo '<p class="signupsuccess">Signup successful!</p>';
}
}
?>
<form action="scripts/signup-script.php" method="post">
<div class="signupContainer">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<?php
if (!empty($_GET["first-name"])) {
echo '<label for="first-name"><b>First Name</b></label>
<input type="text" placeholder="First Name" name="first-name" value="'.$_GET["first-name"].'">';
} else {
echo '<label for="first-name"><b>First Name</b></label>
<input type="text" placeholder="First Name" name="first-name">';
}
if (!empty($_GET["last-name"])) {
echo '<label for="last-name"><b>Last Name</b></label>
<input type="text" placeholder="Last Name" name="last-name" value="'.$_GET["last-name"].'">';
} else {
echo '<label for="last-name"><b>Last Name</b></label>
<input type="text" placeholder="Please Enter Last Name" name="last-name">';
}
if (!empty($_GET["username"])) {
echo '<label for="username"><b>Username</b></label>
<input type="text" placeholder="Username" name="username" value="'.$_GET["username"].'">';
} else{
echo '<label for="username"><b>Username</b></label>
<input type="text" placeholder="Username" name="username">';
}
if (!empty($_GET["email"])) {
echo '<label for="email"><b>Email</b></label>
<input type="text" placeholder="Email" name="email" value="'.$_GET["email"].'">';
} else {
echo '<label for="email"><b>Email</b></label>
<input type="text" placeholder="Email" name="email">';
}
?>
<label for="pwd"><b>Password</b></label>
<input type="password" placeholder="Password" name="pwd">
<label for="pwd-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="pwd-repeat">
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="submit" class="signupBtn" name="signup-submit">Sign Up</button>
</div>
</div>
</form>
</div>
<div class="grid-1">grid-1</div>
</div>
</div>
</section>
</div>
</section>
<!-- The end of my Foldy Grids above -->
</body>
</html>
<?php
require 'footer.php';
?>
Corrected if (strlen($username < 7)) { you might need to put ! (not) in front of strlen.
To me your codes should look like this.
UPDATE had to specify second parameter in url &uname= and correct some double checks in your codes and tested its working fine:
$error '';
if (isset($_POST['signup-submit'])) {
require 'db.php';
$firstName = $_POST['first-name'];
$lastName = $_POST['last-name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
// We check for any empty inputs.
if (empty($firstName) || empty($lastName) || empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
$error = 'error';
header("Location: ../signup.php?error=emptyfields&uname=".$username."&mail=".$email);
exit();
}
// We check for an invalid username. In this case ONLY letters and numbers.
if (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
$error = 'error';
header("Location: ../signup.php?error=invaliduname&uname=".$username);
exit();
}
// We check for minimum amount of characters in username.
if(strlen($username) < 8){
$error = 'error';
header("Location: ../signup.php?error=lenuname&uname=".$username);
exit();
}
// We check for an invalid e-mail.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = 'error';
header("Location: ../signup.php?error=invalidmail&mail=".$email);
exit();
}
// We check if the repeated password is NOT the same.
if ($password !== $passwordRepeat) {
$error = 'error';
header("Location: ../signup.php?error=passwordcheck&password=".$passwordRepeat);
exit();
}
if(empty($error)){
$sql = "INSERT INTO student (firstName, lastName, username, email, pwd) VALUES (?, ?, ?, ?, ?);";
// Here we initialize a new statement using the connection from the db.php file.
$stmt = mysqli_stmt_init($conn);
// Then we prepare our SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error we send the user back to the signup page.
header("Location: ../signup.php?error=sqlerror");
exit();
}else {
// If there is no error then we continue the script!
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sssss", $firstName, $lastName, $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
Your signup.php
<?php
// Here we create an error messages if the user made an error trying to sign up.
if (isset($_GET["error"])) {
if ($_GET["error"] == "emptyfields") {
echo '<p class="signuperror">Fill in all fields!</p>';
}
if ($_GET["error"] == "invalidunamedmail") {
echo '<p class="signuperror">Invalid username and email!</p>';
}
if ($_GET["error"] == "invaliduname") {
echo '<p class="signuperror">Invalid username!</p>';
}
if ($_GET["error"] == "invalidmail") {
echo '<p class="signuperror">Invalid email!</p>';
}
if ($_GET["error"] == "passwordcheck") {
echo '<p class="signuperror">Your passwords do not match!</p>';
}
if ($_GET["error"] == "usertaken") {
echo '<p class="signuperror">Username is already taken!</p>';
}
if ($_GET["error"] == "lenuname") {
echo '<p class="signuperror">Username must be at least 8 characters long!</p>';
}
}
// Here we create a success message if the new user was created.
if (isset($_GET["signup"])) {
if ($_GET["signup"] == "success") {
echo '<p class="signupsuccess">Signup successful!</p>';
}
}
?>
<form action="scripts/signup-script.php" method="post">
<div class="signupContainer">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<?php
if (!empty($_GET["first-name"])) {
echo '<label for="first-name"><b>First Name</b></label>
<input type="text" placeholder="First Name" name="first-name" value="'.$_GET["first-name"].'">';
} else {
echo '<label for="first-name"><b>First Name</b></label>
<input type="text" placeholder="First Name" name="first-name">';
}
if (!empty($_GET["last-name"])) {
echo '<label for="last-name"><b>Last Name</b></label>
<input type="text" placeholder="Last Name" name="last-name" value="'.$_GET["last-name"].'">';
} else {
echo '<label for="last-name"><b>Last Name</b></label>
<input type="text" placeholder="Please Enter Last Name" name="last-name">';
}
if (!empty($_GET["username"])) {
echo '<label for="username"><b>Username</b></label>
<input type="text" placeholder="Username" name="username" value="'.$_GET["username"].'">';
} else{
echo '<label for="username"><b>Username</b></label>
<input type="text" placeholder="Username" name="username">';
}
if (!empty($_GET["email"])) {
echo '<label for="email"><b>Email</b></label>
<input type="text" placeholder="Email" name="email" value="'.$_GET["email"].'">';
} else {
echo '<label for="email"><b>Email</b></label>
<input type="text" placeholder="Email" name="email">';
}
?>
<label for="pwd"><b>Password</b></label>
<input type="password" placeholder="Password" name="pwd">
<label for="pwd-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="pwd-repeat">
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="submit" class="signupBtn" name="signup-submit">Sign Up</button>
</div>
</div>
</form>
See screenshot
Very simple in my point of view:
In the URL you are expecting the error parameter to return invalidlengthuname
Meaning $_GET['error'] = 'invalidlengthuname', though as I see in your example and in your redirection, the $_GET['error'] is equal to invalidlengthuname=ttttttt.
You should remove the second = along with the "ttttttt" or create a second URL parameter so you can track which username the user has posted: ?error=invalidlengthuname&input=ttttttt. Note the & sign.
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();
}
my form action is php_self so that it can validate the form...
what i want to do is after the form is submited, then the data is connect and send to sql....
i already import my sql table and it have a few data recorded inside the table....
so how can i connect to the sql??
and also where i should write my connect sql code in???
here is my php form code....
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = $checkErr ="";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
if(empty($_POST['agree']) || $_POST['agree'] != 'agree') {
$checkErr ="Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy";
}
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}
} else{
//user did not submit form!
}
//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"> <?php echo $postalAddressErr;?></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" 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;?>">
<span class="error"> </span> <?php echo $emailErr;?> </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" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="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="terms" id="terms" onchange="activateButton(this)">
I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</fieldset>
</form>
</div>
</body>
</html>
the userdetail.php is the page that shows the information that user submit...
so where and how i can insert the data in to sql....
You should write your SQL code within $valid.
Let me illustrate below:
Note: I've used default credentials: Hostname = localhost, username = root, password = '', database name = my_database.
You may refer to this: mysqli_connect()
if($valid){
echo "Valid data<br/>"; // Debugging code
echo '</pre>';
print_r($_POST);
exit;
/* SQL code starts */
$con = mysqli_connect("localhost", "root", "", "my_database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO...."; // Your insert query
$query = mysqli_query($con,$sql) or die(mysqli_error($con));
/* SQL code ends */
if ($query) { // Add this condition. Session should be written only when SQL query is successful
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
..........
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
} else {
echo "Unable to insert";
}
} else{
echo "Invalid data<br/>"; // Debugging code
echo '</pre>';
print_r($_POST);
exit;
}
Hope this helps.
Validation doesn't work on my form
I want validation to run in my form and show errors
here's my code for Contact Form.php
<p><span class="error"> * required field(s)</span></p>
<form action="user_input.php" method="post">
<table>
<tr>
<td><label>Name: <span class="error"> *<?php echo $nameErr;?> </span></label></td></tr>
<td><input name="name" type="text" placeholder="Type your name" value="<?php echo $name;?>"></td>
<tr><td><label>Email: <span class="error"> *<?php echo $emailErr;?> </span></label></td></tr>
<td><input name="email" type="email" placeholder="Type your email" value="<?php echo $email;?>"></td>
<tr><td><label>Address: <span class="optional"> Optional</span></label></td></tr>
<td><input name="address" type="text" placeholder="Type your location" value="<?php echo $address;?>"></td>
<tr><td><label>Phone: <span class="error"> * <?php echo $phoneErr;?></span></label></td></tr>
<td><input name="phone" type="tel" placeholder="Type your phone number" value="<?php echo $phone;?>"></td>
<tr><td><label>Message: <span class="error"> * <?php echo $messageErr;?> </span></label></td></tr>
<td><textarea name="message" row="5" cols="40" placeholder="Type your message here" value="<?php echo $message;?>"></textarea></td>
</table>
<input type="submit" value="Submit">
and my code for user_input.php
<?php
$nameErr = $emailErr = $addressErr = $phoneErr = $messageErr = "";
$name = $email = $address = $phone = $message = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["name"])) {
$nameErr = "Name required";
header("location: contact_form.php");
} else {
$name = input($_POST["name"]);
}
if(empty($_POST["email"])) {
$emailErr = "Email required";
header("location: contact_form.php");
} else {
$email = input($_POST["email"]);
// check if email is valid
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email";
header("location: contact_form.php");
}
}
if(empty($_POST["address"])) {
$addressErr = "Invalid Address";
header("location: contact_form.php");
} else {
$address = input($_POST["address"]);
}
if(empty($_POST["phone"])) {
$phoneErr = "Phone number required";
header("location: contact_form.php");
} else {
$phone = input($_POST["phone"]);
if(!preg_match("/^[0-9]+$/", $phone) || strlen($phone) > 20) {
$phoneErr = "Invalid phone number";
header("location: contact_form.php");
}
}
if (empty($_POST["message"])) {
$messageErr = "Message required";
header("location: contact_form.php");
} else {
$message = input($_POST["message"]);
}
}
I don't know where I have errors it should be able to output errors and validating.
I want only php not jquery or javascript
You should store the error messages in a session.
What you do now is setting a variable that is limited to the runtime. As soon as the user changes the page (what he does with location header) they will be flushed. Sessions are not flushed and can be used on per user basis and will be viable for 30 minutes default I think (config can change the duration)
Just add errors like
session_start();
$_SESSION['errors'][] = 'Name required';
On the page you can now access them like foreach($_SESSION['errors'] as $error){... and then delete them unset($_SESSION['errors']);
Remove header() function from error condition and also use an array for storing your errors. instead of multiple variables.