Mysqli Insert not working after i added php validatation [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Goodday house,i'm developing this site that has a registration/login page as my first project and i'm stucked right now.
I added php validation to my registration form but the database insert statement refuses to work after,though all conditional statements were fulfilled,i tried putting a redirect loop immediately after the insert statement but my script automatically (somehow) jumps the "Insert statement" and processes the redirect code..
This is the code below
<!-- Php validation-->
<?php
include 'var.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); // Starts an array to store errors.
//Validation rules involves trimming,validating and sanitizating
$name = trim($_POST['name']);
$strippedname = mysqli_real_escape_string($con, strip_tags($name)) ;
$length = mb_strlen($strippedname, 'utf-8') ;
if ($length < 8 ) {
$errors[]= 'Your full name shouldn\'t be less than 8 letters' ;
} else {
$name = $strippedname ;
}
$email = FALSE ;
if (empty($_POST['email'])) {
$errors[] = 'You didn\'t provide any email address' ;
} // Next is removal of spaces and validation.
if (filter_var((trim($_POST['email'])), FILTER_VALIDATE_EMAIL)) {
$email = mysqli_real_escape_string($con, (trim($_POST['email'])));
}
else {
$errors[] = 'Email address was provided in the wrong format';
}
$pho = trim($_POST['phone']) ; // next line of code removes all characters that aren't digits
$phon = preg_replace('/\D+/', '', ($_POST['phone']));
$strippedphone = mysqli_real_escape_string($con, strip_tags($phon));
$length = mb_strlen($strippedphone, 'utf-8') ;
if ($length <> 11 ) {
$errors[] = 'Phone number should contain only eleven digits';
}
else {
$phone = $strippedphone ;
}
$add = trim($_POST['address']) ;
$strippedadd = mysqli_real_escape_string($con, strip_tags($add)) ;
$length = mb_strlen($strippedadd, 'utf-8') ;
if ($length < 15) {
$errors[]= 'Address should not be lesser than 15 letters' ;
} else {
$address = $strippedadd ;
}
if (empty($_POST['gender'])) {
$errors[] = 'You didn\'t select a gender';
} else {
$gend = trim($_POST['gender']);
}
$user = trim($_POST['username']);
$strippeduser = mysqli_real_escape_string($con, strip_tags($user)) ;
$length = mb_strlen($strippeduser, 'utf-8') ;
if ($length < 6) {
$errors[] = 'Username should contain a minimum of 6 letters and maximum of 18';
} else {
$confirmeduser = $strippeduser ;
}
if (empty($_POST['password'])){
$errors[] ='Please enter a valid password';
}
if(!preg_match('/^\w{10,40}$/', $_POST['password'])) {
$errors[] = 'Invalid password, use 10 to 40 characters without applying spacing.';
} else{
$password = $_POST['password'];
}
if($_POST['password'] == $_POST['confirm_password']) {
$pass = mysqli_real_escape_string($con, trim($password));
$newpass = password_hash($pass, PASSWORD_DEFAULT) ;
}else{
$errors[] = 'passwords don\'t match.';
}
if(empty($errors)) { // If no problems occurred
//Determine whether the email address has already been registered for a user
$query = mysqli_query($con, "INSERT INTO `customer`(`name`, `email`,
`phone`, `address`, `gender`, `username`, `password`) VALUES($name,$email,$phone,
$address,$gend,$confirmeduser,$newpass)") ;
echo "Done";
// end of mysqli_num_Rows
} // End of if (empty($errors))
else{ // Display the errors if any are found.
echo '
<p class="error">The following error(s) were found in the submitted form :<br>';
foreach ($errors as $msg) { // Echo each error
echo " $msg<br>";
}
}
}
?>
This is the html form
<form action="register.php" method="POST" class="form-horizontal" style="margin-top:30px" id="signup">
<fieldset> <div class="form-group">
<legend> Customer Details </legend>
</div>
<div class="form-group">
<label for="name" class="control-label"> Full Name : </label>
<input type="text" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"
name="name" placeholder="Your Full Name" class="required" title="Please type in your name" >
</div>
<div class="form-group">
<label for="email" class="control-label"> Email address </label>
<input type="text" name="email" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>"
placeholder="someone#example.com">
</div>
<div class="form-group">
<label for="phone" class="control-label"> Phone Number :</label>
<input type="tel" name="phone" value="<?php if (isset($_POST['phone'])) echo $_POST['phone']; ?>"
placeholder="08137871320" class="required digits">
</div>
<div class="form-group">
<label for="address" class="control-label"> Contact Address : </label>
<input type="text" name="address" value="<?php if (isset($_POST['address'])) echo $_POST['address']; ?>"
placeholder="No 4,street name,ikeja"
class="required" title="Please type in contact address plus your city's name">
</div>
<!--<div class="form-group">
Drop down menu for selecting a state from the 36 states to be provided
</div>-->
<div class="form-group">
<label for="name">Select Your gender :</label>
<select name="gender" class="form-control">
<option value="male" > Male </option>
<option value="female">Female </option>
</select>
</div>
</fieldset>
<fieldset> <div class="form-group">
<legend> Login Information </legend>
</div>
<div class="form-group">
<label for="username" class="control-label"> Username : </label>
<input type="text" name="username" placeholder="e.g Lords" value="<?php if (isset($_POST['username']))
echo $_POST['username']; ?>">
</div>
<div class="form-group">
<label for="password" class="control-label"> Password : </label>
<input type="password" name="password" id="password" placeholder="Your Password Here">
</div>
<div class="form-group">
<label for="cpassword" class="control-label">Confirm Password : </label>
<input type="password" name="confirm_password" placeholder="Confirm Your Password Here">
</div>
</fieldset>
</div>
</div>
</div>
<div class="form-group" style="text-align:center">
<button type="submit" class="btn btn-success" name="submit"> REGISTER </button>
<button type="reset" id="fat-btn" class="btn btn-danger" data-loading-text="Loading..."> RESET </button> <br>
<p class="lead">
Already a registered user ?,do make use of the
<a href="login.php" class="navbar-link" data-toggle="tooltip" title="When clicked upon,
a page requesting for your username and password is generated,allowing you to book orders">
login page </a>
</p>
</div>
</form>
Thanks a lot for your reply

Since we're more than likely dealing with strings, these variables in your VALUES
($name,$email,$phone,$address,$gend,$confirmeduser,$newpass)
needs to be quoted:
('$name','$email','$phone','$address','$gend','$confirmeduser','$newpass')
Had you checked for errors using or die(mysqli_error($con)) to mysqli_query()
would have signaled the quotes errors.
Sidenote:
You should use prepared statements, or PDO with prepared statements, they're much safer.
Additional note that Barmar spotted:
<?phpinclude 'var.php';
there needs to be a space in there between php and include
<?php include 'var.php';
unless that's a copy/paste error or typo.
and >? again, another spotted error which should be ?>
On the PHP side of things:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.

Related

How could I save on a file .txt with php?

<?php
$fp = fopen("users.txt", "w");
if(!$fp) die ("Errore nella creazione dell'utente");
$fp=fwrite($email $password);
fclose($fp);
$name="";
$surname="";
$email="";
$password="";
$nazionalita="";
$telefono="";
$errors= array();
if($_SERVER["REQUEST_METHOD"]=="POST"){
$name = htmlspecialchars($_POST["name"]);
$surname = htmlspecialchars($_POST["surname"]);
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]);
$nazionalita = htmlspecialchars($_POST["nazionalita"]);
$telefono = = htmlspecialchars($_POST["nazionalita"]);
}
if(empty($name)) {
$errors[] = "Name is required!";
}
if(empty($surname)) {
$errors[] = "Surname is required!";
}
if(empty($email)) {
$errors[] = "Email is required!";
}
if(empty($password)) {
$errors[] = "Password is required!";
}
header("location: index.php");
?>
But of course, this doesn't work.
How can I save to a specific location with PHP?
Then I'll have to do an explode which will only get my email and password. on the login.php page.
Thank you.
I'm not going to fix your code for you, but give you three tips:
Think like a computer. The computer is going to run your program one statement at a time, in the order you've written them; so if you have a line that writes a variable to a file, it needs to come after the line where you've put a value into that variable. It is also going to do exactly what you ask it, not guess what you meant, and not let you get away with typos; read your code back carefully.
Make use of the PHP manual. If you type in https://php.net/ followed by the name of a built-in function, like https://php.net/fwrite, you will get a page that explains what the input and output of that function is. Often, there are examples which show various ways of using the function, which you can use as inspiration for how to write your own code.
Turn on the display_errors setting, or learn where your log file is. Most of the mistakes in the code you show will result in errors or warnings, telling you exactly which line you need to look at. Read the messages carefully, and they'll often point out exactly what you've done wrong.
If you want to write to the file you could do $fpw = fwrite($fp,$email.' : '.$password);
you should pass the $fp to fwrite() method as follow
$fp = fopen('user.txt', 'w+') or die('Unable to open file!');
$fp=fwrite($fp, $email.'~'.$password.'\n'); // make sure to choose whatever seperator suits your need and be careful when choosing it
fclose($fp);
Thanks everyone, I fixed my code!!!
Following the correct code!
<?php
$name="";
$surname="";
$email="";
$password="";
$nazionalita="";
$telefono="";
$errors= array();
//$fp = fopen("users.txt", "w");
//$fpw = fwrite($fp,$dati $email.' : '.$password);
//fclose($fp);
if(isset($_POST["submitPut"])){
$name = htmlspecialchars($_POST["name"]);
$surname = htmlspecialchars($_POST["surname"]);
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]);
$nazionalita = htmlspecialchars($_POST["nazionalita"]);
$telefono = htmlspecialchars($_POST["telefono"]);
$dati= "\n". $name . ",". $surname .",".$email.",". $password . ",". $nazionalita. ",". $telefono;
$file= fopen("users.txt", "a+");
$credenziali=fwrite($file, $dati);
fclose($file);
if(empty($name)) {
$errors[] = "Name is required!";
}
if(empty($surname)) {
$errors[] = "Surname is required!";
}
if(empty($email)) {
$errors[] = "Email is required!";
}
if(empty($password)) {
$errors[] = "Password is required!";
}
}
//header("location: index.php");
?>
<!DOCTYPE html>
<html lang="en">
<?php include_once "views/head.php" ?>
<body>
<?php include_once "views/navbar.php" ?>
<main>
<div class="container my-5">
<h2>Registration user</h2>
<form action="registration.php" method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" >
</div>
<div class="form-group">
<label for="surname">surname:</label>
<input type="text" class="form-control" id="surname" name="surname" placeholder="Enter surname" >
</div>
<div class="form-group">
<label for="email">email:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email" >
</div>
<div class="form-group">
<label for="password">password:</label>
<input type="text" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<div class="form-group">
<label for="nazionalita">nazionalita:</label>
<input type="text" class="form-control" id="nazionalita" name="nazionalita" placeholder="Enter nazionality" >
</div>
<div class="form-group">
<label for="telefono">telefono:</label>
<input type="text" class="form-control" id="telefono" name="telefono" placeholder="Enter phone" >
</div>
<button type="submit"name="submitPut" class="btn btn-primary">Submit</button>
</form>
</div>
</main>
<?php include_once "views/footer.php" ?>
<?php include_once "views/scripts.php" ?>
</body>
</html>

Undefined index when no data entered

Im working on a v2 of signing up.
I added some new input fields in various input types and the one that i use in v1 are now working properly, but the new ones don't. I noticed that it are only like the special input fields (checkboxes, selection menu, radio buttons, ...). I was testing out and when nothing is entered it just gives me this undefined index error (while i tried to define it). Note: the inputs that aren't working are not required fields!
Anyway, here is the PHP code:
// Initializing variables
$username = "";
$email = "";
$errors = array();
// Connect to the database
$conn = mysqli_connect($database['host'], $database['user'], $database['password'], $database['db'], $database['port']);
$email_show = $_POST['emailshow'];
// REGISTER USER
if (isset($_POST['reg_user'])) {
// Receive all input values from the form
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$email_show = mysqli_real_escape_string($conn, $_POST['emailshow']);
$password_1 = mysqli_real_escape_string($conn, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($conn, $_POST['password_2']);
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$fname_show = mysqli_real_escape_string($conn, $_POST['fnameshow']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$lname_show = mysqli_real_escape_string($conn, $_POST['lnameshow']);
$sex = mysqli_real_escape_string ($conn, $_POST['sex']);
$bday = mysqli_real_escape_string($conn, $_POST['bday']);
$country = mysqli_real_escape_string($conn, $_POST['country']);
$private_account = mysqli_real_escape_string($conn, $_POST['privateacc']);
$profile_style = mysqli_real_escape_string($conn, $_POST['profilestyle']);
// Form validation: ensure that the form is correctly filled ...
// By adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if (empty($fname)) { array_push($errors, "Firstname is required"); }
if (empty($lname)) { array_push($errors, "Lastname is required"); }
if (empty($sex)) { array_push($errors, "What is your gender?"); }
if (empty($bday)) { array_push($errors, "When is your birthday?"); }
if (empty($_POST['country'])) { array_push($errors, "Test"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
HTML input:
<div class="box-title"><h1>Sign up</h1></div>
<div class="required-fields"><em>- Required fields are marked with *</em></div>
<div class="account-wrapper">
<div class="account-title">YOUR ACCOUNT</div>
<form method="post" class="accountform" action="/sign-up">
<input type="text" placeholder="Username*" name="username" onfocus="showDesc1()">
<div id="desc1">How others will see you <i id="close" onclick="closeDesc1()" class="fas fa-times-circle"></i></div>
<input type="email" placeholder="Email*" name="email" onfocus="showDesc2()">
<div id="desc2">We need this for important use <i id="close" onclick="closeDesc2()" class="fas fa-times-circle"></i><br><a style="color: blue;"> Read more (soon)</a></div>
<div id="emailshow"><input type="checkbox" id="emailshow-input" name="emailshow" value="showemail"><label style="text-decoration: underline;" data-tooltip="When this option is enabled, other users will be able to see your email on your profile." for="emailshow-input">Show on profile</label></div>
<input id="passwordfield" type="password" placeholder="Password*" name="password_1">
<div onclick="passwordVisb()" class="visb-innerhtml"><i id="visbcon" class="fas fa-eye"></i><label style="cursor: pointer;" id="visb-innerhtml"> Show password</label></div>
<input type="password" placeholder="Confirm password*" name="password_2" onfocus="showDesc3()">
<div id="desc3">Remember the entered password? <i id="close" onclick="closeDesc3()" class="fas fa-times-circle"></i></div>
</div>
</div>
<div class="details-wrapper">
<div class="details-title">YOUR DETAILS</div>
<div class="details-fields1">
<input type="text" placeholder="Firstname*" name="fname" onfocus="showDesc4()">
<div id="desc4">Your firstname <i id="close" onclick="closeDesc4()" class="fas fa-times-circle"></i></div>
<div id="fnameshow"><input type="checkbox" id="fnameshow-input" name="fnameshow" value="1"><label style="text-decoration: underline;" data-tooltip="When this option is enabled, other users will be able to see your firstname on your profile." for="fnameshow-input">Show on profile</label></div>
<input type="text" placeholder="Lastname*" name="lname" onfocus="showDesc5()">
<div id="desc5">Your lastname <i id="close" onclick="closeDesc5()" class="fas fa-times-circle"></i></div>
<div id="lnameshow"><input type="checkbox" id="lnameshow-input" name="lnameshow" value="1"><label style="text-decoration: underline;" data-tooltip="When this option is enabled, other users will be able to see your lastname on your profile." for="lnameshow-input">Show on profile</label></div>
<div class="gendersec">
<input id="genm" type="radio" name="sex" value="male">
<label for="genm">Male</label>
<input id="genf" type="radio" name="sex" required value="female">
<label for="genf">Female</label>
<input id="genc" type="radio" name="sex" value="custom">
<label for="genc" style="text-decoration: underline;" data-tooltip="Select this option if you do not want to tell us what your gender is or if you do have another gender not listed here." data-tooltip-location="top">Custom</label>
</div>
<input type="text" onkeypress="return false;" name="bday" autocomplete="off" placeholder="Birthday*" id="birthdaypicker">
</div>
<div class="details-fields2">
<?php include_once 'C:/xampp2/htdocs/includes/lang-select.php' ?>
<!-- <div id="tags-input">
<span>Socialhub</span>
<input type="text" disabled value="" placeholder="Interests (coming soon)">
</div> !-->
<p style="color: orange;">More options coming soon!</p>
</div>
</div>
<div class="settings-wrapper">
<div class="settings-title">QUICK SETTINGS</div>
<div class="settings-fields1">
<input type="checkbox" id="privateacc-input" name="privateacc" value="privateacctrue"><label for="privateacc-input" style="text-decoration: underline;" data-tooltip="If you enable this option, then the content of your account will be hidden for other users (they can still visit your account but they can't see the content). From your profile picture to your latest post will be hidden.">Private account</label>
<select class="profilestyle" name="profilestyle">
<option selected disabled>Select a style for your profile...</option>
<option value="default">Default (orange & green)</option>
<option value="red">Red</option>
<option value="black">Black</option>
<option disabled>These are coming soon for sure, stay tuned!</option>
<option disabled>Yellow</option>
<option disabled>Blue</option>
<option disabled>Pink</option>
<option disabled>...</option>
</select>
<p style="margin-top: 50px; color: orange;">More settings coming soon!</p>
</div>
</div>
<div class="bottom-wrapper">
<div class="bottom-topframe">
<i class="fas fa-arrow-left"></i> Nevermind!
<div class="agree-wrapper">
<input type="checkbox" id="agreetos-input" name="agreetos" value="tosagreed" onchange="document.getElementById('btnsubmit_reg').disabled = !this.checked;"><label for="agreetos-input">I agree with the Terms of Service (coming soon)</label>
<input type="checkbox" id="verifyage-input" name="verifyage" value="ageverified"><label for="verifyage-input">I am 13 years or older</label>
</div>
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
<button type="submit" disabled name="reg_user" id="btnsubmit_reg" class="btnsubmit_reg">Sign up</button>
</div>
Thanks already. (Sorry for the search, big form)
This will help you, and like #Moayad .AlMoghrabi said you really should use better security also when it is local. Learn yourself always to write secure code.
$email = mysqli_real_escape_string($conn, $_POST['email']);
$email = isset($_POST['email']) ? mysqli_real_escape_string($conn, $_POST['email']) : '';
By checking your post values like this your variable will always have a value or a empty string.
I recommend you in order to fix this issue and to have more security as this code can be used in Mysql Injection easily, You have to escape all values from POST then you have to check if it is empty give it a default values.

Form validation in php - the error and success message display at the same time

I'm learning coding and created a simple form where error messages are
displayed just below each input field. However, when I check the form
the success message appears at the same time as error messages instead
of displaying when all the fields are correctly entered and form
validated. Can you please help. Thank yo in advance. Here is my
code.
</php>
$errorMessage = "";
$successMessage = "";
$emailError = "";
$emailconfirmError = "";
$nameError = "";
$messageError = "";
$servicesError = "";
$name = $email = $emailConfirm = $services = $message = "";
$email = isset($_POST['email']) ? $_POST['email'] : '';
$emailConfirm = isset($_POST['emailConfirm']) ? $_POST['emailConfirm'] : '';
if ($_POST) {
if (!$_POST['email']) {
$emailError .="The email is required";
}
if (!$_POST['emailConfirm']) {
$emailconfirmError .="Please confirm your email <br>";
}
if ($_POST['emailConfirm'] && $email != $emailConfirm) {
$emailconfirmError .="The email addresses do not match <br>";
}
if (!$_POST['name']) {
$nameError .="The name field is required <br>";
}
if (!$_POST['services']) {
$servicesError .="Please select a service required <br>";
}
if (!$_POST['message']) {
$messageError .="The message field is required <br>";
}
if ($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$emailError .= "The email address is invalid.<br>";
}
if ($name = $email = $emailConfirm = $services = $message != "") {
echo $emailError;
echo $emailconfirmError;
echo $name;
echo $services;
echo $message;
}else {
$emailTo = "kamala_guliyeva#hotmail.com";
$services = $_POST['services'];
$message = $_POST['message'];
$headers = "From: ".$_POST['email'];
if (mail($emailTo, $services, $message, $headers)) {
$successMessage = '<div class="alert alert-success" role="alert">Thank you for your message. We\'ll get back to you ASAP!</div>';
} else {
$errorMessage = '<div class="alert alert-danger" role="alert"><p>Your message couldn\'t be sent - please try again</div>';
}
}
}
and HTML
<div id="quote">
<div class="container">
<h2 class="section-title">Request a Quote</h2>
<hr align="left" width="8%" class="style-one">
<br>
<div><? echo $errorMessage.$successMessage; ?></div>
<form id="quoteForm" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="email" name="email" placeholder="Your email">
<label class="error" id="emailError"><?php echo $emailError; ?></label>
</div>
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="emailConfirm" name="emailConfirm" placeholder="Re-type your email">
<label class="error" for="e-mailConfirm" id="emailconfirmError"><?php echo $emailconfirmError; ?></label>
</div>
<div class="form-group">
<input type="name" class="form-control" id="name" style="height:60px" name="name" placeholder="Your Name">
<label class="error" for="name" id="nameError"><?php echo $nameError; ?></label>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<select class="form-control" id="services" name="services" style="height:60px">
<option value="">Select Services</option>
<option value="Installation">Installation</option>
<option value="Repair">Repair</option>
<option value="Service and Maintenance">Service and Maintenance</option>
</select>
<label class="error" for="services" id="servicesError"><?php echo $servicesError; ?></label>
</div>
<div class="form-group">
<textarea class="form-control" id="message" name="message" placeholder="Message" style="height: 163px;" cols="35"></textarea>
<label class="error" for="message" id="messageError"><?php echo $messageError; ?></label>
</div>
</div>
</div>
<div class="form-row text-center">
<div class="col-12">
<button type="submit" style="width:10rem" class="btn quoteButton pt-3 pb-3 text-align-center">Get a Quote</button>
</div>
</div>
</form>
</div>
</div>
You've a few problems there...
So first thing is how you are doing your checks.
if(!$_POST) {
is not a valid way of checking that a post has occurred you need to do something like
if(isset($_POST) && !empty($_POST)) {
would be more appropriate as you are checking if the POST array is actually set and then that it is not empty the && operator is a short circuit operator so if either condition isn't met then the check will fail.
Similarly on your comparisons saying if(!$_POST['email']) { isn't valid because you're effectively asking "if the email part of the post array is not true" where as you need to be asking "if it's not blank and is a valid email address"
You need to be aware of the difference between = == and === operators. You can find some more information here: The 3 different equals
And also the filter_var function here: http://php.net/manual/en/function.filter-var.php
if($_POST['email']!=="" && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
//all good
} else {
//set your error message
}
you can use regular expressions to validate 'name' see preg_match in the manual http://php.net/manual/en/function.preg-match.php
Aside from all of this if you want to have real time monitoring of the fields and the error messages etc you're going to have to look at incorporating Javascript and using AJAX to communicate with your script and then parse the response back into the appropriate div.
Have a look at Rasmus 30 second AJAX tutorial will give you a starting point for this http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html
However it is better practice to do both client and server side validation hope this helps even if it is not a complete answer per sé.

Forgot password reset not displaying correct email address and not updating password if any error made by user during for submission

I am currently working on PHP forgot password reset, which partially doing the job but seeking some assistance to improve it further.
1st issue: It is not displaying the correct email address on the
submission form. It updates the password correctly but doesn't
display correct email address.
2nd issue: Also if the user makes an error while submitting the form on reloading the page doesn't update the password hence the user has to go back to his email to click back on the link.
<?php
include('../config/connection.php');
if(isset($_POST['submit'])){
$password = mysqli_real_escape_string($dbc,$_POST['password']);
$Rpassword = mysqli_real_escape_string($dbc,$_POST['Rpassword']);
$acode=$_POST['encrypt'];
$passmd = md5(SHA1($password));
if (empty($password) OR empty($Rpassword)) {
$error = 'One or either field is missing';
} if ($password != $Rpassword) {
$error = 'Passwords don\'t match';
} if(strlen($password)<6 OR strlen($Rpassword)>20) {
$error = 'Password must be between 6 to 20 characters';
}
else {
$query = mysqli_query($dbc,"select * from users where passreset='$acode'") or die(mysqli_error($dbc));
if (mysqli_num_rows ($query)==1)
{
$query3 = mysqli_query($dbc,"UPDATE users SET password='$passmd',passreset=0 WHERE passreset='$acode'")
or die(mysqli_error($dbc));
$sent = 'Password has been Changed successfully, Please sign in for loging in.';
}
else
{
$error = 'Please click back on the Forgot password link to reset your password ';
}
}
}
?>
<body>
<?php if(!isset($_POST['submit']) OR $error != '' OR isset($error)) { ?>
<?php if(isset($error) AND $error !='')
{
echo '<p style="color:#c43235">'.$error.'</p>';
}
?>
<form action="reset.php" method="post" role="form">
<div class="form-group">
<label for="password">Email</label>
<input type="text" class="form-control" id="email" name="email" value="
<?php
$acode=$_POST['encrypt'];
$query5 = mysqli_query($dbc,"SELECT * FROM users where passreset='$acode'") or die(mysqli_error($dbc));
$list = mysqli_fetch_array($query5); /* Error-----*/
$val = $list['email'];
echo $val;?>" >
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" >
</div>
<div class="form-group">
<label for="password">Re-enter Password</label>
<input type="password" class="form-control" id="password" name="Rpassword" placeholder="Password" >
</div>
<input type="hidden" class="form-control" name="encrypt" value="<?php echo $_GET['encrypt'];?>" >
<button class="btn btn-success" type="submit" name="submit" />Submit</button>
</form>

Undefined Index PHP issue.Please help

I have the following error:
Notice: Undefined index: submit in C:\wamp\www\registration\register.php on line 6
Can't seem to work out whats wrong??? Here's the code::
<?php
//Create registration form (register.php)
include "../includes/db_connect.php";
if(!$_POST['submit']) ///Line 6
{
?>
<html>
<head><link rel="stylesheet" href="style.css"></head>
<div class="divider">
<strong>Register</strong><br/><br/>
<form method="post" action="register.php">
<div class="formElm">
<label for="first">First Name</label>
<input id="first" type="text" name="first">
</div>
<div class="formElm">
<label for="last">Last Name</label>
<input id="last" type="text" name="last">
</div>
<div class="formElm">
<label for="username">Desired Username</label>
<input id="username" type="text" name="username">
</div>
<div class="formElm">
<label for="password">Password</label>
<input id="password" type="password" name="password">
</div>
<div class="formElm">
<label for="pass_conf">Confirm Password</label>
<input id="pass_conf" type="password" name="pass_conf">
</div>
<div class="formElm">
<label for="email">Email</label>
<input id="email" type="text" name="email">
</div>
<div class="formElm">
<label for="about">About</label>
<textarea id="about" cols="30" rows="5" name="about">Tell us about yourself</textarea>
</div>
<input type="submit" name="submit" value="Register">
</form>
or Login
</div>
</html>
<?php
}
else
{
$first = protect($_POST['first']);
$last = protect($_POST['last']);
$username = protect($_POST['username']);
$password = protect($_POST['password']);
$pass_conf = protect($_POST['pass_conf']);
$email = protect($_POST['email']);
$about = protect($_POST['about']);
$errors = array();
$regex = "/^[a-z0-9]+([_\.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+\.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
{
$errors[] = "E-mail is not in name#domain format!";
}
if(!$first || !$last || !$username || !$password || !$pass_conf || !$email || !$about)
{
$errors[] = "You did not fill out the required fields";
}
$sql = "SELECT * FROM `users` WHERE `username`='{$username}'";
$query = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($query) == 1)
{
$errors[] = "Username already taken, please try another";
}
if(count($errors) > 0)
{
echo "The following errors occured with your registration";
echo "<font color=\"red\">";
foreach($errors AS $error)
{
echo "<p>" . $error . "\n";
}
echo "</font>";
echo "Try again";
//we use javascript to go back rather than reloading the page
// so the user doesn't have to type in all that info again.
}
else
{
$sql = "INSERT into `users`(`first`,`last`,`username`,`password`,`email`,`about`)
VALUES ('$first','$last','$username','".md5($password)."','$email','$about');";
$query = mysql_query($sql) or die(mysql_error());
echo "Thank You for registering {$first}! Your username is {$username}";
echo " Click here to Login";
}
}
?>
If there is no POST parameter at all or if there is no parameter named submit then you're trying to access an array index that does not exists, hence the warning. You can simply test if there is such an index/element in the _POST array.
if( isset($_POST['submit']) )
It doesn't check the value (like you original script, which tests if the value of _POST['submit'] equals false, see type juggling), but the mere existence of the index/element should suffice in this case.
see http://docs.php.net/isset
To get rid of this error, it should be:
if(!isset($_POST['submit']))
However, your code is already OK.
What you are getting is not an error, it is a warning, which is caused by having strict warnings enabld. PHP is a dynamic language which does not usually require to define variables and array keys, and most documentation and code will skip this part. So you should consider turning this feature off, as it clutters code and has few additional benefits. Or, switch to a statically compiled language (say asp.net) which will really benefit from defined variables and static typing.
Your $_POST does not exist when you first load your page. Change your check to something like:
if(!isset($_POST["submit"]))
Because you did not post anything yet, there will be no "submit" key in your $_POST array. That's what causes the warning.
For those posting use if(isset($_POST['submit'])), you clearly did not read his code. He has put is there is not a submit write the HTML form else use the fields (backwards righting to me!)
If he wants to keep the structure as is, it should be
if(empty($_POST['submit']))

Categories