undefined index for validation - php

I am trying build a simple registration form with validation. When I leave a field blank and submit my form I keep getting this error undefined index email or undefined index password.For eg I fill in all fields except lastname I will get a notice saying email is undefined and if i fill all the fields I get username ,email and password is undefined. I googled it and the sugesstions i could get was isset , I tried using isset but it still does not work. Can anyone please help?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sign Up</title>
<style>
label{
width:100px;
float:left;
}
</style>
</head>
<body>
<?php
session_start();
$Firstname=isset($_SESSION['Firstname']);
$Lastname=isset($_SESSION['Lastname']);
$username=isset($_SESSION['username']);
$email=isset($_SESSION['email']);
$password=isset($_SESSION['password']);
if(isset($_SESSION['error']))
{
echo '<p>'.$_SESSION['error']['Firstname'].'</p>';
echo '<p>'.$_SESSION['error']['Lastname'].'</p>';
echo '<p>'.$_SESSION['error']['username'].'</p>';
echo '<p>'.$_SESSION['error']['email'].'</p>';
echo '<p>'.$_SESSION['error']['password'].'</p>';
unset($_SESSION['error']);
}
?>
<div class="signup_form">
<form action="registerUser.php" method="post" >
<p>
<label for="Firstname">First Name:</label>
<input name="Firstname" type="text" id="Firstname" size="30"/>
</p>
<p>
<label for="Lastname">Last Name:</label>
<input name="Firstname" type="text" id="Lastname" size="30"/>
</p>
<p>
<label for="username">User Name:</label>
<input name="username" type="text" id="username" size="30"/>
</p>
<p>
<label for="email">E-mail:</label>
<input name="email" type="text" id="email" size="30"/>
</p>
<p>
<label for="password">Password:</label>
<input name="password" type="password" id="password" size="30 "/>
</p>
<p>
<input name="submit" type="submit" value="Submit"/>
</p>
</form>
</div>
<p>Login</p>
</body>
</html>
Here is registeruser.php
<?php
session_start();
include('dbconnect.php');
if(isset($_POST['submit']))
{
//whether the username is blank
if($_POST['FirstName'] == '')
{
$_SESSION['error']['Firstname'] = " FirstName is required.";
}
if($_POST['LastName'] == '')
{
$_SESSION['error']['Lastname'] = " LastName is required.";
}
//whether the email is blank
if($_POST['email'] == '')
{
$_SESSION['error']['email'] = "E-mail is required.";
}
else
{
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$personcon=$conn;
$sql1 = "SELECT * FROM TBLUSERS WHERE email = '$email'";
$personinfo=oci_parse($personcon,$sql1);
oci_execute($personinfo);
oci_free_statement($personinfo);
if (oci_num_rows($personinfo) > 0)
{
$_SESSION['error']['email'] = "This Email is already used.";
}
}
else
{
//this error will set if the email format is not correct
$_SESSION['error']['email'] = "Your email is not valid.";
}
}
//whether the password is blank
if($_POST['password'] == '')
{
$_SESSION['error']['password'] = "Password is required.";
}
if($_POST['username'] == '')
{
$_SESSION['error']['username'] = "username is required.";
}
if(isset($_SESSION['error']))
{
header("Location: index.php");
exit;
}
else
{
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$email = $_POST['email'];
$username=$_POST['$username'];
$password = $_POST['password'];
$sql2 = "INSERT INTO TBLUSERS (FirstName,LastName,email, username,password) VALUES ('$FirstName', $LastName, '$email', '$username','$password')";
$personinfo2=oci_parse($personcon,$sql2);
oci_execute($personinfo2);
oci_free_statement($personinfo2);
if($personinfo2)
{
/* $from=praveen.mohan#students.mq.edu.au */
$to = $email;
$subject = "Confirmation from TutsforWeb to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail)
{
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
else
{
echo "Cannot send Confirmation link to your e-mail address";
}
oci_close($personcon);
}
}
}
?>

When you do not fill a field, its index will not exist in the $_POST associative array. You need to check with isset whether it exists like this:
<?php
session_start();
include('dbconnect.php');
$_SESSION['error'] = array();
if(isset($_POST['submit'])) {
//whether the username is blank
if((!isset($_POST['FirstName'])) || ($_POST['FirstName'] == '')) {
$_SESSION['error']['Firstname'] = " FirstName is required.";
if((!isset($_POST['LastName'])) || ($_POST['LastName'] == '')) {
$_SESSION['error']['Lastname'] = " LastName is required.";
if((!isset($_POST['email'])) || ($_POST['email'] == '')) {
$_SESSION['error']['email'] = "E-mail is required.";
} else {
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email'])) {
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$personcon=$conn;
$sql1 = "SELECT * FROM TBLUSERS WHERE email = '$email'";
$personinfo=oci_parse($personcon,$sql1);
oci_execute($personinfo);
oci_free_statement($personinfo);
if (oci_num_rows($personinfo) > 0) {
$_SESSION['error']['email'] = "This Email is already used.";
}
} else {
//this error will set if the email format is not correct
$_SESSION['error']['email'] = "Your email is not valid.";
}
}
//whether the password is blank
if((!isset($_POST['password'])) || ($_POST['password'] == '')) {
$_SESSION['error']['password'] = "Password is required.";
}
if((!isset($_POST['username'])) || ($_POST['username'] == '')) {
$_SESSION['error']['username'] = "username is required.";
}
if(isset($_SESSION['error'])) {
header("Location: index.php");
exit;
} else {
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$email = $_POST['email'];
$username=$_POST['$username'];
$password = $_POST['password'];
$sql2 = "INSERT INTO TBLUSERS (FirstName,LastName,email, username,password) VALUES ('$FirstName', $LastName, '$email', '$username','$password')";
$personinfo2=oci_parse($personcon,$sql2);
oci_execute($personinfo2);
oci_free_statement($personinfo2);
if($personinfo2) {
/* $from=praveen.mohan#students.mq.edu.au */
$to = $email;
$subject = "Confirmation from TutsforWeb to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn";
$sentmail = mail($to,$subject,$message,$header);
if($sentmail) {
echo "Your Confirmation link Has Been Sent To Your Email Address.";
} else {
echo "Cannot send Confirmation link to your e-mail address";
}
oci_close($personcon);
}
}
}
?>
For example
((!isset($_POST['FirstName'])) || ($_POST['FirstName'] == ''))
will be true if there is no 'FirstName' in $_POST or it is an empty string. The trick is that the second operand will not be checked if the first is true, preventing the problem you have mentioned in the question.
Further observations:
your code assumes that there is a $_SESSION['error'] element. You might get errors if this is not properly initialized
your code is vulnerable to SQL injection
your code is not properly structured, which makes it difficult to maintain
your code mixes up sql with php, which is not elegant

The first issue is that your HTML input names don't match the PHP names you expect.
if($_POST['FirstName'] == '') //Upper case N
While in the markup you use <input name = "Firstname" ... with lower case N
Another issue with the markup is two inputs are named Firstname:
<label for="Lastname">Last Name:</label>
<input name="Firstname" type="text" id="Lastname" size="30"/> <!--Firstname should be Lastname-->
Finally one more problem lies within the index.php file where you try to flash the session variable which comes back from the registerUser.php. Either there should be only one $SESSION["error"] or isset(SESSION["error"]["field"]) must be used just like with the $POST["field"] in registerUser.php.
The flashing code would look like this after the change:
if(isset($_SESSION['error']))
{
if (isset($_SESSION['error']['Firstname'])) echo '<p>'.$_SESSION['error']['Firstname'].'</p>';
if (isset($_SESSION['error']['Lastname'])) echo '<p>'.$_SESSION['error']['Lastname'].'</p>';
if (isset($_SESSION['error']['username'])) echo '<p>'.$_SESSION['error']['username'].'</p>';
if (isset($_SESSION['error']['email'])) echo '<p>'.$_SESSION['error']['email'].'</p>';
if (isset($_SESSION['error']['password'])) echo '<p>'.$_SESSION['error']['password'].'</p>';
unset($_SESSION['error']);
}
I would also suggest looking up a good resource on the topic. Login/Register systems are hard to get right for the first time.

Related

How to check if the email has already been used

I am made a form validation using PHP. If the error happens, the error msg will show around each input column. I would like to check if the email is used or not. So, I used error code to define if input email addr is used, then showing the error message for "The email has been used". However, the result becomes whatever I input, it only shows "The email has been used". Could some help me for this issue? Thanks!
<?php
require_once('./conn.php');
$errorMsgs = array('nickname'=>'', 'email'=>'', 'password'=>'');
if(isset($_POST['submit'])) {
if(empty($_POST['nickname'])) {
$errorMsgs['nickname'] = "Please enter your nickname";
}
$email = $_POST['email'];
$password = $_POST['password'];
// checking the email is valid or empty
if(empty($_POST['email'])) {
$errorMsgs['email'] = "Please enter your email";
} else {
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorMsgs['email'] = "Please enter a valid email";
}
}
$errorCode = $conn->errno;
if($errorCode === 1062) {
$errorMsgs['email'] = "The email has been used";
}
// checking the password is valid or empty
if(empty($_POST['password'])) {
$errorMsgs['password'] = "Please enter your password";
} else {
if(!preg_match('/\w{8,}/', $password)) {
$errorMsgs['password'] = "Please enter at least 8 characters";
}
}
if(!array_filter($errorMsgs)) {
$sql = sprintf("INSERT INTO member (nickname, email, password) values ('%s', '%s', '%s')", $_POST['nickname'], $_POST['email'],$_POST['password']);
$result = $conn->query($sql);
if($result) {
header("Location: index.php");
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" />
<title>Message Board - Sign Up</title>
</head>
<body>
<div class="container__signup">
<h1 class="title">Create Account</h1>
<form class="signup" method="POST" action="signup.php">
<div>
<i class="far fa-user"></i>
<input type="text" placeholder="Name" name="nickname">
</div>
<p class="warning__msg"><?php echo $errorMsgs['nickname'];?></p>
<div>
<i class="far fa-envelope"></i>
<input type="text" placeholder="Email" name="email">
</div>
<p class="warning__msg"><?php echo $errorMsgs['email'];?></p>
<div>
<i class="fas fa-lock"></i>
<input type="password" placeholder="Password" name="password">
</div>
<p class="warning__msg"><?php echo $errorMsgs['password'];?></p>
<input type="submit" value="SIGN UP" name="submit">
</form>
</div>
</body>
</html>
You have to check if the email exists in your user table.
something like this.
<?php
require_once('./conn.php');
$errorMsgs = array('nickname'=>'', 'email'=>'', 'password'=>'');
if(isset($_POST['submit'])) {
if(empty($_POST['nickname'])) {
$errorMsgs['nickname'] = "Please enter your nickname";
}
$email = $_POST['email'];
$password = $_POST['password'];
// checking the email is valid or empty
if(empty($_POST['email'])) {
$errorMsgs['email'] = "Please enter your email";
} else {
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorMsgs['email'] = "Please enter a valid email";
}
else{
//you should use sql parameter binding
$email = $_POST['email'];
$checkDuplicate= $conn->query("SELECT email FROM user_table where email = '$email'");
if(!empty($checkDuplicate)) {
$errorMsgs['email'] = "The email has been used";
}
}
}
// checking the password is valid or empty
if(empty($_POST['password'])) {
$errorMsgs['password'] = "Please enter your password";
} else {
if(!preg_match('/\w{8,}/', $password)) {
$errorMsgs['password'] = "Please enter at least 8 characters";
}
}
if(empty($errorMsgs)) { //you need to check if there's any error
$sql = sprintf("INSERT INTO member (nickname, email, password) values ('%s', '%s', '%s')", $_POST['nickname'], $_POST['email'],$_POST['password']);
$result = $conn->query($sql);
if($result) {
header("Location: index.php");
}
}
}
?>

How to make login system with password_verify to work?

I am working on PHP/MYSQL register/login system for like a week and iam truly having issue with php password_hash and password_verify function...The register worked and the login with password_verify keeps failing and i do not understand why..Could somebody help out? i really am desperate.
Login part..what i am trying to achieve 1-its check if email is empty or not and if is valid email..2--its check if password is empty or not. 3-if both $email and $password are ok..it makes connection to db.. then a-it checks if the email exists in table users, if not it requires to register..b-if the user exists in db, then it verify if the $password is same as passsword in db...if it is valid password..it echoes "valid"..and if not valid password..it echoes "invalide email/password"...that is what i am trying to achieve...
Here i am posting the full code:
db design
user_id(auto_increment/primary key)
email(unique, varchar)
password(varchar, 255)
register.php
<?php
$email=$password="";
$emailErr=$passwordErr="";
if (isset($_POST['submit'])) {
if (empty($_POST['email'])) {
$emailErr="Enter your email";
}
elseif (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === FALSE) {
$emailErr = "Invalid email";
}
else
{
$email= trim($_POST['email']);
}
if (empty($_POST['password'])) {
$passwordErr = "Enter your password";
}
elseif (strlen($_POST['password']) < 3) {
$passwordErr = "password must 4 length least";
}
else
{
$password = trim($_POST['password']);
}
// if everything is filled correct connect
if ($email && $password)
{
include_once'connect.php';
$sql = "SELECT COUNT(users.email) FROM users WHERE email = :email";
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->execute();
$result = $s->fetch(PDO::FETCH_NUM);
$resultvalue = $result[0];
//if email exist, stop the script
if ($resultvalue > 0) {
echo "Email already exist";
exit();
}
// if email not exist insert it
else
{
$sql = "INSERT INTO users (email,password) VALUES (:email, :password)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':password', password_hash($password, PASSWORD_DEFAULT));
$stmt->execute();
if ($stmt) {
echo "Values inserted";
exit();
}
else
{
echo "Insert values failed";
exit();
}
}
}
//if everything is not filled correct connect
else
{
$proceedErr = "Could not proceed";
}
}//submit
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Register page</title>
<style type="text/css">
form p label
{
display: block;
}
em
{
color: red;
font-style: normal;
}
</style>
</head>
<body>
<?php
if (isset($proceedErr)) {
echo $proceedErr;
}
?>
<form method="POST" action="">
<p>
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="Enter your email" value/><em><?php if(isset($emailErr)) echo $emailErr;?></em>
</p>
<p>
<label for="email">Password :</label>
<input type="password" name="password" id="password" placeholder="Enter your password" value/><em><?php if(isset($passwordErr)) echo $passwordErr;?></em>
</p>
<input type="submit" name="submit" id="submit" value="Register" />
</form>
</body>
</html>
login.php
<?php
$emailErr=$passwordErr="";
$email=$password="";
if (isset($_POST['submit'])) {
if (empty($_POST['email'])) {
$emailErr="Enter your email";
}
elseif (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === FALSE) {
$emailErr = "Enter valid email";
}
else
{
$email = trim($_POST['email']);
}
if (empty($_POST['password'])) {
$passwordErr="Enter your password";
}
else
{
$password= trim($_POST['password']);
}
if ($email && $password)
{
include_once'connect.php';
$sql = "SELECT user_id,email, password FROM users WHERE email = :email";
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->execute();
$result = $s->fetch(PDO::FETCH_ASSOC);
$resultvalue = count($result['email']);
print_r($result);
//if email do not exist, stop the script
if ($resultvalue < 1) {
echo "Your email do not exist, please register";
exit();
}
elseif (password_verify($password, $result['password'])) {
echo "valide password / email";
exit();
}
else
{
echo "InValid email / password";
exit();
}
}
else
{
echo "Email / password do not match";
}
}// end submit
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Login page</title>
<style type="text/css">
form p label
{
display: block;
}
em
{
color: red;
font-style: normal;
}
</style>
</head>
<body>
<form method="POST" action="">
<p>
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="Enter your email" value/><em><?php if(isset($emailErr)) echo $emailErr;?></em>
</p>
<p>
<label for="email">Password :</label>
<input type="password" name="password" id="password" placeholder="Enter your password" value/><em><?php if(isset($passwordErr)) echo $passwordErr;?></em>
</p>
<input type="submit" name="submit" id="submit" value="login" />
</form>
</body>
</html>
Tested the same scripts here and it worked.
I've received as answer "valide password / email", so this conditional statement "(password_verify($password, $result['password']))" returned true (line 51 within login.php).
Do you receive any error message or warning?

Inserting data into a mysql database using a form

I'm trying to insert data into the 'riders' table in the 'poo12104368' database using a form. Currently I am having problems with my 'if' statements because they are not working as they should be. For example, if a user was to only type in a last name and an email address, it would let them create an account. When the user does create an account by entering their correct details into the feilds it should take them to 'newaccount.php'. Can anybody help? Thanks
Code:
$firstnameErr = $lastnameErr = $suemailErr = "";
$firstname = $lastname = $suemail = "";
if(isset($_POST['submit2'])){
if(empty($_POST["firstname"])||(empty($_POST["lastname"]))||(empty($_POST["suemail"]))){
echo "Something is wrong";
if($_POST['firstname'] == null){
$firstnameErr = "First Name is required";
}else{
$firstname =($_POST["firstname"]);
}
if($_POST['lastname'] == null){
$lastnameErr = "Last Name is required";
}else{
$lastname = ($_POST["lastname"]);
}
if($_POST['suemail'] == null){
$suemailErr = "Email is required";
}else{
$suemail = ($_POST["suemail"]);
}
if($_POST['firstname'] == null){
echo "<b>Please enter a first name</b>";
}
else if($_POST['lastname'] == null){
echo "<b><p>Please enter a last name</p></b>";
}
else if($_POST['suemail'] == null){
echo "<b><p>Please enter an email</p></b>";
}
$dblink = mysql_connect("localhost", "root", "" )
or die (mysql_error());
mysql_select_db("poo12104368");
// Query the database to see if the email that the user has entered is already in use
$rs2 = mysql_query("SELECT * FROM riders WHERE Email = '".$_POST['suemail']."'");
if($row = mysql_fetch_assoc($rs2)){
$dbEmail = $row['Email'];
if($row['Email'] == $_POST['suemail']){
echo "<p><b>Email already used. Please use another</b></p>";
}
}
else{
// Insert query to insert the data into the riders table if their data meets the required inputs
$sql = "
INSERT INTO riders (FirstName, LastName, Email) VALUES('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['suemail']."')";
mysql_query($sql);
// The web page that the user will be taken to
header('Location:http://localhost/newaccount.php');
}
}
}
?>
<h2><p> Sign Up </p></h2>
<p><span class="error">* required field.</span></p>
<!-- Form that the users enters their data in -->
<form name = "suform" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First Name:<input type="text" name="firstname" style="width:20%"/>
<span class="error">*<?php echo $firstnameErr;?></span></p></br>
<p>Last Name:<input type="text" name="lastname" style="width:20%"/>
<span class="error">*<?php echo $lastnameErr;?></span></p></br>
<p>Email Address:<input type="text" name="suemail" style="width:20%"/></p>
<span class="error">*<?php echo $suemailErr;?></span></br>
<p><br><input type="submit" name="submit2" value="Submit"/></br></p>
<h2>Our Links</h2>
<!-- Links to the various mediums for Bewdley Motorcycle Club -->
<p>YouTube:BewdleyMCCOffcial<p>
<p>Website:www.bewdleymotorcycleclub.co.uk</p>
Try this it will work :
Use flag to handle the validation errors in the form use this $error as a flag.
Code :
$firstnameErr = $lastnameErr = $suemailErr = "";
$firstname = $lastname = $suemail = "";
if(isset($_POST['submit2'])){
$error = 0;
if(empty($_POST["firstname"])||(empty($_POST["lastname"]))||(empty($_POST["suemail"]))){
$msg = "something going wrong";
$error = 1;
}
if($_POST['firstname'] == null){
$firstnameErr = "First Name is required";
$error = 1;
}else{
$firstname =($_POST["firstname"]);
}
if($_POST['lastname'] == null){
$lastnameErr = "Last Name is required";
$error = 1;
}else{
$lastname = ($_POST["lastname"]);
}
if($_POST['suemail'] == null){
$suemailErr = "Email is required";
$error = 1;
}else{
$suemail = ($_POST["suemail"]);
}
if($_POST['firstname'] == null){
$msg = "Please enter a first name";
$error = 1;
}
else if($_POST['lastname'] == null){
$msg = "Please enter a last name";
$error = 1;
}
else if($_POST['suemail'] == null){
$msg = "Please enter an email";
$error = 1;
}
if($error == '0')
{
$dblink = mysql_connect("localhost", "root" , "")
or die (mysql_error());
mysql_select_db("poo12104368");
// Query the database to see if the email that the user has entered is already in use
$rs2 = mysql_query("SELECT * FROM riders WHERE Email = '".$_POST['suemail']."'");
if($row = mysql_fetch_assoc($rs2)){
$dbEmail = $row['Email'];
if($row['Email'] == $_POST['suemail']){
echo "<p><b>Email already used. Please use another</b></p>";
}
}
else{
// Insert query to insert the data into the riders table if their data meets the required standards
$sql = "
INSERT INTO riders (FirstName, LastName, Email) VALUES('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['suemail']."')";
mysql_query($sql);
// The web page that the user will be taken to
header('Location:http://localhost/newaccount.php');
}
}
else
{
echo $msg;
}
?>
<h2><p> Sign Up </p></h2>
<p><span class="error">* required field.</span></p>
<!-- Form that the users enters their data in -->
<form name = "suform" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First Name:<input type="text" name="firstname" style="width:20%"/>
<span class="error">*<?php echo $firstnameErr;?></span></p></br>
<p>Last Name:<input type="text" name="lastname" style="width:20%"/>
<span class="error">*<?php echo $lastnameErr;?></span></p></br>
<p>Email Address:<input type="text" name="suemail" style="width:20%"/></p>
<span class="error">*<?php echo $suemailErr;?></span></br>
<p><br><input type="submit" name="submit2" value="Submit"/></br></p>
<h2>Our Links</h2>
<!-- Links to the various mediums for Bewdley Motorcycle Club -->
<p>YouTube:BewdleyMCCOffcial<p>
<p>Website:www.bewdleymotorcycleclub.co.uk</p>
I hope it will work for you.

Need advice / guidance on makin registration form

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color:red;}
</style>
</head>
<body>
<?php
$username = $password = $email = "";
$usernameerr = $passworderr = $emailerr = "";
if ($_SERVER["REQUEST_METHOD"]=="POST") {
if (empty($_POST["username"])) {
$usernameerr = "Please fill username";
} else {
$username = test_input($_POST["username"]);
if(!preg_match("/^[a-zA-Z]*$/",$username)) {
$usernameerr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailerr = "Please fill e-mail";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$emailerr = "not a valid e-mail";
}
}
if (empty($_POST["password"])) {
$passworderr = "Cannot be blank";
} else {
$password = test_input($_POST["password"]);
if(!preg_match("/^[a-zA-Z]*$/",$password)) {
$pasworderr = "Must be Letters";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con = mysqli_connect('localhost','root','','my_db');
if (mysqli_connect_errno()) {
echo "Fail to connect :".mysqli_connect_error();
}
$username = mysqli_real_escape_string($con, $_POST["username"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$sql = "INSERT INTO register(Username, Password, Email)
VALUES ('$username','$password','$email')";
if (!mysqli_query($con,$sql)) {
die ('Error: '.mysqli_error($con));
}
echo "Registration successful";
mysqli_close($con);
?>
<h2>Register</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username :<input type="text" name="username" value="<?php echo $username;?>">
<span class="error">*<?php echo $usernameerr;?></span>
<br><br>
Password :<input type="text" name="password" value="<?php echo $password;?>">
<span class="error">*<?php echo $passworderr;?></span>
<br><br>
E-mail :<input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailerr;?></span>
<br><br>
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
Hi, I am a newbie, and I need advice on making registration form. So here is the code for my registration form, the validation code works and it submit data to mysql database too. But, the problem is, it will submit data to database every time it loads (even if it is blank). What line of codes should I add to prevent the form submitting data when it is not filled completely / filled with the right format.
Thx in advance.
You have to check if there's any data in the fields.
Just add this line before your sql executes, after $email = mysqli_real_escape_string($con, $_POST["email"]); :
if ($username != "" && $password != "" && $email != "")
{
//your sql and rest of the script goes here
}
else
{
//don't save the data if it's not completed well
//do whatever you want in that case no valid data was completed
}
Notes: I answered only to your question but be careful, you have some implementation mistakes. You should just use a flag that by default is 1 and, if an error is found in any of your validation functions, the falg should be set to 0 and you should check the value of the flag before the sql instead of checking the content of the $_POST variables again.
Edit: BETTER SOLUTION FOR YOUR CODE
Add this block before the sql:
if ($usernameerr == "" && $passworderr == "" && $emailerr == "")
{
//no errors, all fine we can add to the database
}
else
{
//we have errors, do something but don't add the data
}
Please outsource your DB-Connection and your DB-Insert in some seperate files and speak to them per ajax-request..
your db-insert-query should be taken place after you validation and at the end of the
if ($_SERVER["REQUEST_METHOD"]=="POST") {
block
You did not close the $_SERVER["REQUEST_METHOD"]=="POST" block properly.
Also inside the if ($_SERVER["REQUEST_METHOD"]=="POST") { block you can add another
if condition as if(!empty($_POST["username"] && !empty($_POST["email"] && !empty($_POST["password"]) {....}

Register.php redirected to a blank page

I am trying to create a registration page in PHP with MYSQL . My index.php page has a form which I have to fill in , and upon registration , it is supposed to show the status of registration , whether it is successful or not , and whether confirmation link is being sent to the email. However , when I click register , it redirects to register.php where nothings is being shown - all i see is a blank page no matter what info i key in. Furthermore , upon checking my table (user) in database (users) , I realized that no data is being input. My database connection is correct since I have verified it and i suspect that the error is in register.php . can anyone take a look at it and guide me on what I might be doing wrong? Thanks in advance.
my index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sign Up</title>
<style>
label{
width:100px;
float:left;
}
</style>
</head>
<body>
<?php
session_start();
if(isset($_SESSION['error']))
{
echo '<p>'.$_SESSION['error']['username'].'</p>';
echo '<p>'.$_SESSION['error']['email'].'</p>';
echo '<p>'.$_SESSION['error']['password'].'</p>';
echo '<p>'.$_SESSION['error']['mail_add'].'</p>';
unset($_SESSION['error']);
}
?>
<div class="signup_form">
<form action="register.php" method="post" >
<p>
<label for="username">User Name:</label>
<input name="username" type="text" id="username" size="30"/>
</p>
<p>
<label for="email">E-mail:</label>
<input name="email" type="text" id="email" size="30"/>
</p>
<p>
<label for="password">Password:</label>
<input name="password" type="password" id="password" size="30 "/>
</p>
<p>
<label for="mail_add">Mailing:</label>
<input name="mail_add" type="text" id="mail_add" size="30"/>
</p>
<p>
<input name="submit" type="submit" value="Submit"/>
</p>
</form>
</div>
</body>
</html>
My register.php
<?php
session_start();
include('configdb.php');
if(isset($_POST['submit']))
{
//whether the username is blank
if($_POST['username'] == '')
{
$_SESSION['error']['username'] = "User Name is required.";
}
if($_POST['mail_add'] == '')
{
$_SESSION['error']['mail_add'] = "Mailing address is required.";
}
//whether the email is blank
if($_POST['email'] == '')
{
$_SESSION['error']['email'] = "E-mail is required.";
}
else
{
//whether the email format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//if it has the correct format whether the email has already exist
$email= $_POST['email'];
$sql1 = "SELECT * FROM user WHERE email = '$email'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
if (mysqli_num_rows($result1) > 0)
{
$_SESSION['error']['email'] = "This Email is already used.";
}
}
else
{
//this error will set if the email format is not correct
$_SESSION['error']['email'] = "Your email is not valid.";
}
}
//whether the password is blank
if($_POST['password'] == '')
{
$_SESSION['error']['password'] = "Password is required.";
}
//if the error exist, we will go to registration form
if(isset($_SESSION['error']))
{
header("Location: index.php");
exit;
}
else
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$mail_add = $_POST['mail_add'];
$com_code = md5(uniqid(rand()));
$sql2 = "INSERT INTO user (username, email, password, com_code , mail_add) VALUES ('$username', '$email', '$password', '$com_code', '$mail_add')";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
if($result2)
{
$to = $email;
$subject = "Confirmation from TutsforWeb to $username";
$header = "TutsforWeb: Confirmation from TutsforWeb";
$message = "Please click the link below to verify and activate your account. rn";
$message .= "http://www.yourname.com/confirm.php?passkey=$com_code";
$sentmail = mail($to,$subject,$message,$header);
echo "Records finally inserted into table.";
if($sentmail)
{
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
else
{
echo "Cannot send Confirmation link to your e-mail address";
}
}
else {
echo "Cannot insert into table";
}
}
}
?>
Thanks in advance.
Try:
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error($mysqli));
Enjoy your code

Categories