I am trying to validate my form using php. Upon validation it will give a welcome message.Or else it will redirect to the index page. I have used session to save the variable. But the problem is nothing happen's when I submit the form, Here's my script
<?php session_start();
$_SESSION['reg'] = array();
$name = $_POST['name'];
$email = $_POST['email'];
$passwd = $_POST['passwd'];
$repasswd = $_POST['repasswd'];
if(empty($_POST)){
header("location:register.php");
}
else
{
if(empty($name)){
$_SESSION['reg']['name'] = "Please enter name";
}
if(empty($email)){
$_SESSION['reg']['email'] = "Please enter email";
}
if (empty($passwd)) {
$_SESSION['reg']['passwd'] = "please enter a password";
}
elseif (strlen(passwd)>16) {
$_SESSION['reg']['passwd'] = "At most 16 chars";
# code...
}
if ($passwd != $repasswd) {
$_SESSION['reg']['repasswd'] = "Passwords don't match";
}
if (empty($_SESSION['reg'])) {
header("location:welcome.php");
}
else
{
$_SESSION['data'] = array();
foreach($_POST as $id=>$val)
{
$_SESSION['data'][$id] = $val;
}
header("location:register.php");
}
?>
when I submit the form, It shows a blank page.
The problem is that you are not storing your post variables into the session if they are NOT empty prior to checking
if (empty($_SESSION['reg'])) {
I would highly suggest doing some sql injection prevention prior to putting post variables into the session scope.
UPDATE: So if you want the variable in the session scope, instead of checking if(empty($name)){ and setting an error message in the session, I would do this:
if( !empty($name) ){
$_SESSION['reg']['name'] = $name;
} else {
// error handling
}
this will set the session variable if the posted value is NOT empty. Now when you check your session variable later on, it will have the name value in it and won't be empty.
Related
I'm looking to create a sign-up page for a large-scale website which means I'm using a lot more layers of validation then I would normally do, given this should be common practice but in this particular case more than any other situation it is imperative.
I've already written most of the code required and formatted it in an order which I believed wouldn't lead to any undefined variable errors, however, upon form submission it doesn't create a new SQL row and doesn't return any errors under the error handling areas of the form validation. In all fairness, the error handling is quite simple at this point and is not a final version, just what I put in place to help me debug and troubleshoot any issues which should arise.
Here's the PHP code, and the snippet of the piss-poor error handling that is supposed to output an error message if an error occurs, to re-state, this error handling isn't final.
$conn = mysqli_connect('localhost', 'root2', '123', 'db');
$signupConditionsMet = "0";
if (isset($_POST["email"]) && isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["passwordCheck"]) && isset($_POST["birthdate"])) {
$signupConditionsMet = "1";
$birthGood = true;
$passGood = false;
$nameGood = false;
$emailGood = false;
}
$usernameSearch = $conn->prepare("SELECT * FROM users WHERE username = ?");
$userInsertion = $conn->prepare("INSERT INTO users (username, passwd, birthdate, email) VALUES (?,?,?,?)");
$nameErr = $emailErr = $passErr = $birthErr = "";
$name = $email = $pass = $birth = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["username"];
$email = $_POST["email"];
$pass = $_POST["password"];
$birthdate = $_POST["birthdate"];
$passCheck = $_POST["passwordCheck"];
}
if ($signupConditionsMet === "1"){
function test_input($name) {
if (!preg_match("/^[a-z\d_]{2,15}$/i",$name)) {
$nameErr = "Only letters and white space allowed";
} else {
$nameGood = true;
return $name;
echo "did name ez";
}
}
function test_input2($email){
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
} else {
$emailGood = true;
return $email;
echo "did email ez";
}
}
function test_input3($password){
if (!preg_match("/^[a-z\d_]{2,15}$/",$pass)) {
$passErr = "Invalid password format";
} else if (!preg_match("/^[a-z\d_]{2,15}$/",$passCheck)){
$passErr = "Invalid password check format";
} else if ($_POST["password"] !== $_POST["passwordCheck"]){
$passErr = "Passwords do not match";
} else {
$passwd2 = AES_ENCRYPT($_POST["password"], 'mysecretstring');
$passwdGood = true;
return $passwd2;
echo "did pass ez";
}
}
}
if (($signupConditionsMet === "1") && ($birthGood === true) && ($nameGood === true) && ($passwdGood === true) && ($emailGood === true)) {
if ($usernameSearch->execute(array($_POST['username']))) {
while ($row = $usernameSearch->fetch()) {
if (!empty($row['id'])) {
$creationError = "This username is already taken";
} else {
$userInsertion->bindParam(1, $name);
$userInsertion->bindParam(2, $passwd2);
$userInsertion->bindParam(3, $birthdate);
$userInsertion->bindParam(4, $email);
$userInsertion->execute();
header('Location: userlanding.php');
}
}
}
}
/* PHP inside the HTML to output errors */
<?php if ($signupConditionsMet === "1") { echo "all inputs received"; echo $_SERVER["REQUEST_METHOD"];} else { echo "drats, they weren't all there"; echo $name; echo $email; echo $birthdate; echo $pass; echo $passCheck;}?>
<?php if ($passErr) { echo $passErr;} else if ($nameErr) { echo $nameErr;} else if ($emailErr) { echo $emailErr;} else if ($birthErr) { echo $birthErr;} ?>
Disregarding the previously admitted terrible error handling, I can't seem to wrap my head around why it doesn't work in its current form. It returns (from the client-side reporting) that all inputs were received and there isn't any fatal errors thrown from running the PHP code. In addition, the second client-side code which prints any errors doesn't print anything either, implying that all functions operated correctly, however, the echos at the bottom of the input tests don't echo the strings they've been assigned, implying those didn't work, but there was no errors. Hmm. Perhaps I'm missing something blatantly obvious regarding my syntax but I don't see why it wouldn't work. Any help would be appreciated.
I'm creating a system that the header will show 'login' if the user is not logged in, and if they are, it'll display logout. I've simplified it for now, just showing if the user is logged in or not. With "Login!" meaning they need to login, and "Welcome!" if they are logged in. I used the PHP Code Checker website (https://phpcodechecker.com/) and it couldn't find any errors. I also searched stackoverflow, and everyone else's seems to work.
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
echo "Login!";
} else {
echo "Welcome!";
}
?>
is the code that checks if the user is logged in or not.
My login page works for EVERYTHING else, for my homepage is shows that the user is logged in, but here is the code anyway. (This is only the PHP code, there is HTML for the submit button, ect.)
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: index.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($name)){
$error = true;
$nameError = "Please enter your username.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT userId, userEmail, userPass FROM users WHERE
userName='$name'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if email/pass correct it returns must be
1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['userId'];
header("Location: dashboard.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
It connects to the database fine, and i'm certain there is no problems with the database, since it works on my other pages.
I've spent a long-while trying to figure this out, and can't.
Thanks!
In your code
if ( isset($_SESSION['user'])!="" ) {
you are comparing true|false != ""
change it to if (isset($_SESSION['user'])) {
or
if (isset($_SESSION['user']) && ($_SESSION['user']!="")) {
I currently have a form that checks if the username and password exist and logs you and redirects you to the homepage. However if you leave the email and password section blank, you also are able to log into the site. I'm looking to add some sort of validation to avoid someone from just using empty input variables.
This is what I have...
<?php
session_start();
include_once 'config.php';
$email ="";
$userpassword ="";
$errors = 0;
$emailError ="";
$passwordError ="";
if(isset($_SESSION['user'])!="")
{
header("Location: home.php");
}
if(isset($_POST['loginBtn']))
{
if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
{
$emailError = "Email is not valid";
$errors = 1;
}
if(!empty($_POST["password"])) {
$passwordError = "Please enter a Password";
$errors = 1;
}
$email = mysql_real_escape_string($_POST['email']);
$userpassword = mysql_real_escape_string($_POST['password']);
$result=mysql_query("SELECT * FROM users WHERE emailAddress='$email'");
$row=mysql_fetch_array($result);
if($row['password']==md5($userpassword))
{
$_SESSION['user'] = $row['user_id'];
header("Location: home.php");
}
else
{
?>
<script>alert('First time visitors, please create an account to play'); </script>
<?php
}
}
?>
Client Side validation such as JavaScript and HTML5 can be turned off or directly edited via the browser. Always use server side validation as the final authority.
Also, When checking login credentials you need to do a combination check in the where clause.
WHERE username ='$u_user' AND password = '$u_pass'
This is especially the case when allowing the reuse of controlling columns (username, email). Passwords are not always unique.
In the OP's case the lookup on the email only could return multiple results.
<?php
session_start();
include_once('config.php');
IF (isset($_SESSION['user'])!="") { header("Location: home.php"); }
IF (isset($_POST['loginBtn'])) { // the form was submitted
$err = ""; // default error as empty
$email= trim($_POST['email']);
$password = trim($_POST['password']);
// validation
IF (empty($email)) { $err .= "Email is empty<br>";
}ELSE{
IF (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$err .= "Email is not valid<br>";
}
}
IF (empty($password)) { $err .= "Password is empty<br>"; }
IF (!empty($err)) {
// there are errors
echo("<p>".$err."</p>");
}ELSE{
// No errors
$uemail = mysql_real_escape_string($email);
$upass = mysql_real_escape_string(md5($password));
$result = mysql_query("SELECT * FROM users WHERE emailAddress='$uemail' && password = '$upass'");
IF ($result) {
// set session
$row = mysql_fetch_array($result);
$_SESSION['user'] = $row['user_id'];
}ELSE{
echo("<p>Email address and or your password was incorrect.<br>If you do not have an account please create one.</p>");
}
// Close DB connection
mysql_close($Your_db_connection);
// redirect if session is set
IF (isset($_SESSION['user'])) { header("Location: home.php"); }
}
}ELSE{
// form not submitted
}
?>
You can use html5 validation for login form use required attributes for blank input field validation this validation is very easy and user friendly please use this way
This if statement is not working. I am trying to make it so that all the things must contain a value for the first statement to be shown, but it works when only one value is selected.
<?php
if ((isset($_POST["FirstName"]))&&(isset($_POST['SecondName']))
&&(isset($_POST['email']))&&(isset($_POST["submit"]))) {
echo "You've given all your details";
}
else {
echo "Please enter all your details";
}
?>
Even if the input is not filled it will be set. you need to check if it is set and if it contains input.
Try making a function to do just that:
function issetWithInput(&$va){
return (isset($va) && !empty($va));
//checks that it is set and contains input.
}
Then you can do something like:
if(issetWithInput($_POST["FirstName"])&&issetWithInput($_POST['SecondName'])..) {
Try this
<?php
if (isset($_POST['FirstName']) &&
isset($_POST['SecondName']) &&
isset($_POST['email']) &&
isset($_POST['submit']) &&
!empty($_POST['SecondName']) &&
!empty($_POST['FirstName']) &&
!empty($_POST['email'])) {
echo "You've given all your details";
}
else {
echo "Please enter all your details";
}
?>
this is what i do when checking my form
<?php
$firstname= $_POST['FirstName'];
$secondname = $_POST['SecondName'];
$email = $_POST['email'];
$submit = $_POST['submit'];
if ($submit)
{
if ($firstname&&$secondname&&$email)
{
echo "You've given all your details";
}
else
echo "Please enter all your details";
}
?>
but i may have miss understood what you are tying to do :), please do ignore this if this makes no sense at all (im still rather new to php)
$error1='';
$error2='';
$error3='';
$error4='';
$error5='';
$error6='';
$yourname='';
$email='';
$email2='';
$password='';
$password2='';
$country='';
if (isset($_POST['Registerme']))
{
$_POST['yourname']=$yourname;
$_POST['email']=$email;
$_POST['email2']=$email2;
$_POST['password']=$password;
$_POST['password2']=$password2;
$_POST['country']=$country;
if($yourname==''){
$error1='name required';
}
if($email==''){
$error2='email required';
}
if($email2==''){
$error3='required field';
}
if($password==''){
$error4='password required';
}
if($password2==''){
$error5='required field';
}
if($country==''){
$error6='country required';
}
if(empty($error1) && empty($error2) && empty($error3) && empty($error4) && empty($error5) && empty($error6))
{echo 'mysql query goes here and add the user to database';}
}///main one
else {$error1='';
$error2='';
$error3='';
$error4='';
$error5='';
$error6='';}
this is a registration validation script. in my registration form there are two email and password filelds.second fields are for confirmation.i want to check weather user typed same information in that both field.if i want to do that in this script should i use another if statement? or i should use else if? i am confused about that step...
Some comments:
You MUST sanitize input! Take a look at best method for sanitizing user input with php.
Your assignments: Instead of "$_POST['yourname']=$yourname;" it should be "$yourname=$_POST['yourname'];".
You're using a lot of variables for error control, and after that if all went well you simply forget the error messages in the last else block. Use some kind of array for error strings, and use it!
Are you sure you aren't validating usernames/passwords to not contain spaces or weird characters, or emails to be valid?
Some sample code...:
// Simple sanitize function, complete it
function sanitize_input ($inputstr) {
return trim(mysql_real_escape_string($inputstr));
}
if (isset ($_POST['Registerme']) {
// array of error messages to report
$error_messages = array();
$isvalid = true;
// Assignment
$yourname = sanitize_input ($_POST['yourname']);
$email = sanitize_input ($_POST['email']);
$email2 = sanitize_input ($_POST['email2']);
$password = sanitize_input ($_POST['password']);
$password2 = sanitize_input ($_POST['password2']);
$country = sanitize_input ($_POST['country']);
// Validation
if (empty ($yourname)) {
$error_messages[] = "You must provide an username";
}
if (empty ($password)) {
$error_messages[] = "You must provide a password.";
}
elseif ($password !== $password2) {
$error_messages[] = "Passwords do not match.";
}
// Same for email, you caught the idea
// Finally, execute mysql code if all ok
if (empty($error_messages)) {
// Execute mysql code
isvalid = true;
}
}
// After form processing, use isvalid which is false if there are errors
// and the error_messages array to report errors
add additional conditions to your second if statement.
e.g.
if($email=='' || $email != $email2){
...
Just add simple checks. I wouldn't combine the check with the general password check - as I can imagine you would like to tell the user what went wrong exactly.
if ($password1 !== $password2) {
// Add an specific error saying the passwords do not match.
}
I would replace the user of loose errors to an array like:
$aErrors = array();
if ($password1 !== $password2) {
$aErrors[] = 'Another specific error!';
}
if (empty($password1) || empty($password2)) {
$aErrors[] = 'Another specific error';
}
if (empty($aErrors)) {
// Process the form!
}
There are lots of issues with your code.
1. You are assinging $_POST['key'] = $somevalue, while I think you mean $somevar = $_POST['key']
2. Use an array for all error messages as it'll make your life a bit easier ..
3. To compare password use something like
if ($password1 !== $password2) {
}
so .....
$errors = array();
so you'd check something like ..
if ($password1 !== $password2) {
$errors[] = 'Password dont match';
}
if(count($errors) > 0) { //if there are errors
foreach($errors as $err) {
echo $err.' <br />';
}
} else {
// whatever you want to do if no error
}
I'll also suggest to sanitise the $_POST values before you use them in your queries.
I hope it helps.
I think you mean to do this:
$yourname = $_POST['yourname'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$country = $_POST['country'];
Second this make use of an errors array:
$errors = array();
Third use nested ifs(just a suggestion)
if (!empty($_POST['password1'])) {
if ($_POST['password1'] != $_POST['password2']) {
$errors[] = '<font color="red">The 2 passwords you have entered do not match.</font>';
} else {
$password = $_POST['password1'];
}
} else {
$errors[] = '<font color="red">Please provide a password.</font>';
}