registration form in php - 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>';
}

Related

PHP Sign-up Form Issues with Validation and Insertion

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.

How to put my validation block of codes into Function PHP

How can I put my validation codes into a function? How am I going to return it and call it? I am trying to call put them in just one code and then call them in a function for my forms. Any idea?
Here's my codes:
function validate(){
$errors = array();
//empty array to collect errors
//VALIDATION CODES (NEED TO BE INSIDE A FUNCTION)
if(empty($_POST['email']) AND filter_var($email, FILTER_VALIDATE_EMAIL) != false)
{
$errors[] = "email cannot be blank";
}
if(empty($_POST['first_name']))
{
$errors[] = "First Name cannot be blank";
}
if(empty($_POST['last_name']))
{
$errors[] = "Last Name cannot be blank";
}
if(empty($_POST['password']))
{
$errors[] = "Password cannot be blank";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(!isset($_POST['date']) || strtotime($_POST['date']) === false)
{
$errors[] = "Birth Date cannot be blank";
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = $errors;
//redirect your user back using header('location: ')
header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
//redirect your user to the next part of the site!
}
}
So when I call this this wont work:
echo validate();
Hope you can help. Thanks!
So you're saying something like:
class Validation {
public static function emailFilter($input) {
global $_POST;
return empty($_POST['email']) AND filter_var($input,
FILTER_VALIDATE_EMAIL) != false ? "email cannot be blank" : false;
}
}
Or are you looking to do something else?
EDIT 1
Okay, how about:
function filter ($input, $type) {
if (!$input OR !$type) {
switch ($type) {
case "email":
// Check email
if (empty($_POST['email']) AND filter_var($input, FILTER_VALIDATE_EMAIL)) {
return "email cannot be blank";
}
break;
case "first_name":
if(empty($_POST['first_name']))
{
return "First Name cannot be blank";
}
break;
// And so on.
}
}
}
You could call it then by:
filter($_POST['email'], 'email');
So then:
if (!filter($_POST['email'], 'email')) {
// The email checks out.
} else {
$error[] = filter($_POST['email'], 'email');
}
There are will be more elegant solutions available, but this is based on what I think you want.
Let's say that the user clicks the button after filling-up the required fields, in your $_POST['submit'] or whatever name of your button, just add your codes, and print the error beside the html textbox by adding or if you want, just print $error below the textboxes of your html registration page. And if the errors return zero value, then you can add everything in the database then redirect to your desired page in the else block of your error checking codes.
I would do this like so:
function validate(){
$errors = array();
//empty array to collect errors
//VALIDATION CODES (NEED TO BE INSIDE A FUNCTION)
if(empty($_POST['email']) AND filter_var($email, FILTER_VALIDATE_EMAIL) != false)
{
array_push($errors, "Email cannot be blank");
}
if(empty($_POST['first_name']))
{
array_push($errors, "First Name cannot be blank");
}
if(empty($_POST['last_name']))
{
array_push($errors, "Last Name cannot be blank");
}
if(empty($_POST['password']))
{
array_push($errors, "Password cannot be blank");
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
array_push($errors, "Please enter matching password");
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
array_push($errors, "Please enter matching password");
}
if(!isset($_POST['date']) || strtotime($_POST['date']) === false)
{
array_push($errors, "Birth Date cannot be blank");
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = implode("|", $errors);
//redirect your user back using header('location: ')
return 0;
/*
Can't use both return & redirect, but return is more flexible.
*/
//header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
return array("email" => $email, "first_name" => $first_name,
"last_name" => $last_name, "password" => $password,
"birth_date" => $birth_date);
// so now you have your results in an associative array.
// you can use print_r(validate()); to see the results, or use
// $r = validate(); if ($r != false) { /*go places!*/}
//redirect your user to the next part of the site!
}
}

php: best way to validate POST

I have been using the code below to validate my user input by $_POST:
if(isset($_POST['name']) && !empty($_POST['name'])) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
This code checks whether 'name' was actually set, which is obvious and clear and needed.
Secondly, it checks whether user typed something in textfield to give a value for name.
However, if user gives SPACE " " as input it accepts it because it is not empty it has SPACE.
I found one way of doing it right:
if(isset($_POST['name'])) {
$n = trim($_POST['name']);
if(empty($n)) {
$errors[] = "Please give a name";
}
}
else {
$errors[] = "Please give a name";
}
But here I am repeating same error message twice, so how can it be optimized?
if(isset($_POST['name']) && trim($_POST['name']) !== "") {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
Remove the empty, and just do the trim.
To be honest, you don't even need the isset unless you have notices turned on:
if(trim($_POST['name']) !== "") {
If you don't need the trimmed string, you can move the trim itself to the if-clause:
if(isset($_POST['name']) && (trim($_POST['name']) != '') ) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
If you further need it, you could modify the input before checking:
$_POST['name'] = trim( $_POST['name'] );
if(isset($_POST['name']) && !empty($_POST['name'])) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
Try like this
if(trim(isset($_POST['name']))) {
$n = trim($_POST['name']);
}
else {
$errors[] = "Please give a name";
}
try
if(isset($_POST['name'])) {
$n = trim($_POST['name']);
}
if(empty($n) or !isset($_POST['name'])) {
$errors[] = "Please give a name";
}
Just change your above code to this
if(trim(isset($_POST['name'])))
{
$n = trim($_POST['name']);
}
else
{
$errors[] = "Please give a name";
}
Try using this
if(isset($_POST['name']) && trim($_POST['name']) != false) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
Finally I came to use the following code. It is better because here I can even control minimum number of characters.
if(isset($_POST['name']) && strlen(trim($_POST['name'])) > 1) {
$block->name = trim($_POST['name']);
}
else {
$errors[] = "Please give a name. It should be at least two characters";
}

Having difficulties with my PHP registration script

This script seems to get hung up when it hits the series of "if" statements checking the email and password length. If I remove these statements, it properly inserts the data into the db.
<?php
ob_start();
session_start();
if (!empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['confirmpassword'])) {
$email = strip_tags($_POST['email']);
$password = md5(strip_tags($_POST['password']));
$confirmpassword = md5(strip_tags($_POST['confirmpassword']));
$errors = array();
if (strlen($email) < 6) {
$errors[] = "Email too short.";
}
if (strlen($email) > 25) {
$errors[] = "Email too long.";
}
if (strlen($password) < 2) {
$errors[] = "Password too short.";
}
if (strlen($password) > 25) {
$errors[] = "Password too short.";
}
if ($password !== $confirmpassword) {
$errors[] = "Passwords do not match.";
}
if (count($errors) == 0) {
// Include database config file then connect to database
require('db_config.php');
$connection = mysql_connect(DB_HOST,DB_USERNAME,DB_PASSWORD) or die("Database Connection Error");
$database = mysql_select_db(DB_NAME) or die("No Database");
// Create query
$query = "INSERT INTO bah_register VALUES ('','$email','$password')";
// Query database and
mysql_query($query);
// Success message
echo "Thanks for signing up!";
} else {
foreach ($errors as $error) {
echo $error . "<br />";
}
}
}
?>
Your issue is that you are md5ing the password before you check the length. This puts the password at 32 characters, which is greater than your limit and producing an error.
You are checking strlen($password) > 25 and your password is md5 hashsum which is longer than 25 symbols. You probably wanted to check original value of password
i don't know what is wrong with your code, but for your email you might consider using something like this :
if(!preg_match('/^[^#]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $email)){
$errors[] = "Email is not valid.";
}
many emails are longer than 25 characters.
The foreach with the error array can easly be replaced with following code
echo implode('<br />', $errors);
Proper email validation can be done with the filter_var function
The strip_tags function can have undesired effects on the password, probably parts of it will be deleted. Think of the following password: «<my>super!password»

Problem with my PHP server-side validation code

I have a form in a file register.php, and it posts to registerPost.php. Inside registerPost.php, I check against a few validation rules, then if any of them are flagged, I return to the first page and print the errors. In theory, that should work. But the validation goes through with no problems, even when I leave everything blank.
Here's the code in question:
$_SESSION["a"] = "";
$_SESSION["b"] = "";
$_SESSION["c"] = "";
$_SESSION["d"] = "";
$_SESSION["e"] = "";
$_SESSION["f"] = "";
$_SESSION["g"] = "";
if(empty($userEmail))
{
$_SESSION["a"] = "You must enter your email.";
}
if(!validEmail($userEmail))
{
$_SESSION["a"] = "Improper Email Format";
}
if(empty($password))
{
$_SESSION["b"] = "You must enter a password.";
}
if(strlen($password) < 5 || strlen($password) > 0)
{
$_SESSION["b"] = "Password must be at least 5 characters.";
}
if($password != $confPassword)
{
$_SESSION["c"] = "Passwords do not match";
}
if(empty($firstName))
{
$_SESSION["d"] = "First Name Required";
}
if(empty($lastName))
{
$_SESSION["e"] = "Last Name Required";
}
if(mysql_num_rows(mysql_query("SELECT * FROM users WHERE email = '$email'")) > 0)
{
$_SESSION["f"] = "This email address already exists in our database.";
}
if(!empty($_SESSION["a"]) || !empty($_SESSION["b"]) || !empty($_SESSION["c"]) || !empty($_SESSION["d"]) || !empty($_SESSION["e"]) || !empty($_SESSION["f"]))
{
header('Location: register.php');
}
Perhaps there is a more straightforward way to do this?
I like this way of registering all errors:
$errors = array();
if (empty($foo1))
$errors[] = "foo1 can't be left blank!";
else if (!preg_match(' ... ', $foo1))
$errors[] = "foo1 was not filled out correctly!";
if (empty($foo2))
$errors[] = "foo2 can't be left blank!";
// ...
if (empty($errors)) {
// do what you need
} else {
// notify the user of the problems detected
}
Do you really need to change the page by header?
I tried your code and it works for me.
Guessing from $username,$email and so on, I think you're doing some sanitizing on the $_POST data. If so, you should dump the $username, etc. to see, if that procedure is putting something in these variables.
Anyway, I like this way of validation better:
$errors = array();
if(empty($username))
{
$errors['username'] = 'Username cannot be empty!';
}
...
$_SESSION['errors'] = $errors;
if(count($errors) > 0) //Redirect...

Categories