Need advice / guidance on makin registration form - php

<!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"]) {....}

Related

Unable to throw error Message

registration_form
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Name:
<input type="text" name="name">
<br/> <br/>
Username:
<input type="text" name="username">
<br/> <br/>
Password:
<input type="password" name="password">
<br/> <br/>
Email:
<input type="text" name="email">
<br/> <br/>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
<?php
require('connect.php');
require('validation.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users
(`id`,`name`,`username`, `password`, `email`) VALUES ('','".$name."',
'".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
validation.php
<?php
// define variables and set to empty values
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
connect.php
<?php
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
?>
I'm developing a simple Registration from with four inputs i.e., Name, username, password, email.when the user fills out the form and click submit button then all the filled data should go n save in data base which is working fine in my case, but when the user wont fill any data and if user simply clicks a submit button then error message should be shown like "ALL FIELDS ARE NECESSARY", but where in my case even if i click submit button without entering any values the mesage i'm getting as success and all the null values are getting stored in the data base which should not happen, my output should be if i fill the forms n click submit button then all the data should be stored in database and if i click submit button without filling out any value then error should throw that "all field to be filled" and no null value should be stored in data base, please can any one guide me what changes i should do so that to get my desired output.
You do
require('validation.php');
setting and checking alot of variables e.g.
$name = test_input($_POST["name"]);
$nameErr = "Only letters and white space allowed";
come back from require and overwrite $name with original posted values and do nothing with $nameErr
$name = $_POST['name'];
check the errors after the require
e.g.
require('validation.php');
$lsError = $nameErr . $emailErr . $userErr . $passwordErr;
if(trim($lsError) != '') {
echo $lsError ."<BR>";
echo "ALL FIELDS ARE NECESSARY";
}
else {
//rest of your insert
}

how to throw validation error

registration_from.php
<!DOCTYPE HTML>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
Name:
<input type="text" name="name">
<br/> <br/>
Username:
<input type="text" name="username">
<br/> <br/>
Password:
<input type="password" name="password">
<br/> <br/>
Email:
<input type="text" name="email">
<br/> <br/>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
<?php
require('connect.php');
require('validation.php');
$name = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(isset($_POST["submit"])){
if($query = mysqli_query($connect,"INSERT INTO users
(`id`,`name`,`username`, `password`, `email`) VALUES ('','".$name."',
'".$username."', '".$password."', '".$email."')")){
echo "Success";
}else{
echo "Failure" . mysqli_error($connect);
}
}
?>
validation.php
<?php
// define variables and set to empty values
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
connect.php
<?php
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
?>
I'm developing a simple Registration from with four inputs i.e., Name, username, password, email.when the user fills out the form and click submit button then all the filled data should go n save in data base which is working fine in my case, but when the user wont fill any data and if user simply clicks a submit button then error message should be shown like "ALL FIELDS ARE NECESSARY", but where in my case even if i click submit button without entering any values the mesage i'm getting as success and all the null values are getting stored in the data base which should not happen, my output should be if i fill the forms n click submit button then all the data should be stored in database and if i click submit button without filling out any value then error should throw that "all field to be filled" and no null value should be stored in data base, please can any one guide me what changes i should do so that to get my desired output.
If you don't mind adding a little more code, you code do like:
In your registration_form.php
<?php
require('validation.php'); // Require first to do validation before queries
require('connect.php');
// Remove the part where you set variables to $_POST params
// Variables are already set inside validation.php
/**
* Then, I recommend moving queries to **connect.php**
* to have all your sql functions inside one file.
* Also moving the inserting of data to a function for easy grouping/calling
*/
if (isset($_POST["submit"]) {
// Check if validation does not fail
if ($emailErr == "" || $nameErr == "" || $userErr == "" || $passwordErr == "") {
// Call to insert function
doInsert($name, $email, $username, $password);
} else {
echo $emailErr . " " . $nameErr . " " . $userErr . " " . $passwordErr;
}
}
?>
In your connect.php
function doInsert($name, $email, $username, $password) {
$connect = mysqli_connect("localhost", "root", "","php_forum")
or die("Error " . mysqli_error($connect));
$sql = "INSERT INTO users(`id`,`name`,`username`, `password`, `email`)
VALUES ('','".$name."', '".$username."', '".$password."', '".$email."')";
$query = mysqli_query($connect, $sql);
if ($query) {
echo "Success";
} else {
echo "Failure " . mysqli_error($connect);
}
}
Please add error in session and print session in form file.
In validation.php
$nameErr = $emailErr = $userErr = $passwordErr = "";
$name = $email = $username =$password = "";
if (isset($_POST['submit'])) {
$name = $_POST["name"];
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
if($name == '' || $email == '' || $username == '' || $password == "")
{
echo "ALL FIELDS ARE NECESSARY";
exit();
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["username"])) {
$userErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password is required";
} else {
$password= test_input($_POST["password"]);
}
}
registration_from.php
if(isset($_SESSION['error]) && !empty($_SESSION['error])){
echo $_SESSION["error"]
}
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

How to validate a form in PHP, then redirect to an external page

I'm trying to validate a registration form using HTML and PHP, and insert the data into an SQL database. Upon registration, I'd like for my user to be directed to their personal dashboard. I can get everything to work except for the redirect upon form submission.
Here is the PHP at the start of the page:
<?php
// define variables and set to empty values
$emailErr = $passErr = $confirmErr = $email = $pass = $confirm = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["pass"])) {
$passErr = "You must have a password";
} else {
$pass = test_input($_POST["pass"]);
}
if (empty($_POST["confirm"])) {
$confirmErr = "You must confirm your password";
} else {
$confirm = test_input($_POST["confirm"]);
}
if ($pass != $confirm) {
$confirmErr = "Your passwords must match";
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = test_input($_POST["email"]);
$pass = test_input($_POST["pass"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
And my HTML form:
<div class="container">
<form class="form-signin" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<h2 class="form-signin-heading">Register below:</h2>
<span class="error"><?php echo $emailErr;?></span>
<input type='email' class="form-control" placeholder="enter email..." name='email'/>
<span class="error"><?php echo $passErr;?></span>
<input type='password' class="form-control" placeholder="enter password" name='pass'/><span class="error"><?php echo $confirmErr;?></span>
<input type='password' class="form-control" placeholder="confirm password" name='confirm'/>
<input type='submit' class="btn btn-success btn-block" name="submit" value="submit">
<h5>Already have an account? Log in.</h5>
</form>
</div>
Note the use of
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
on
<form action="">
param. Using this function I can't get a redirect.
I've included my SQL entries following the HTML, and the entries are working just fine, but the header(); tag doesn't seem to work. See here:
<?php
$email = $_POST['email'];
$pass = md5($_POST['pass']);
// Database connection
require 'database.php';
$sql = "SELECT email FROM users WHERE email = '".$email."'";
$result = $conn->query($sql);
$row_count = $result->num_rows;
if ($row_count == 1) {
// user already exists
header('Location: login.php');
} elseif ($row_count > 1) {
// just to double check multiple entries aren't input into the DB
echo 'There are too many records with that name!';
} else {
// enter user into DB
$sql = "INSERT INTO users (email, pass)
VALUES ('".$email."', '".$pass."')";
if ($conn->query($sql) === TRUE) {
header('Location: dashboard.php');
exit();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
}
?>
Any ideas what I'm doing wrong?
hi i have seen you code in your code you are using login.php for redirecting from header tag.
and in html file you are using login.html file for checking account is exists or not.
Please check file extension for your login file.
you can use following link for header function details:
PHP header(Location: ...): Force URL change in address bar
If I understand it right, what you can do is redirect back to your page with the link :
<form name="form-lignin" method="post" action="this-php-page.php">
On the same page you can then create a section that will show up only if the form has been submitted and the form will be hidden. The section can be personalised for each user then as well.
You can do this by adding a hidden field to your form.
<input type='hidden' name='submission' value="something"/>
Then you can add this php :
if ($_POST["submission"]=="something") {
*Dashboard content?*
} else {
*The actual form...*
}
Hope this helped :)
1.you need ensure the code has run
if ($conn->query($sql) === TRUE) {
echo 'is run!';exit;
header('Location: dashboard.php');
exit();
}
and you can use if ($conn->query($sql)) instand if ($conn->query($sql) === TRUE)
2.notice ,if the "exit;" code run ,"mysqli_close($conn);" will useless。
You first need to put all your php code above the html so that the html output will be sent to the browser after execution of the validation script.
Then
1 Capture form values
2 Validate form values
3 If Every thing is ok. Then sanitize the input and insert it into the database.
4 if insert successful, Redirect it to another page, Using header('location:http://example.com');
Thats it

undefined index for validation

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.

php form validation and header location

I have a form submitting to intself. If the post variables are set, then I want them to be redirected to employee_profile.php. Currently the header location does not work even when the post variables are set. Any ideas?
<?php
$email_error = $password_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$email_error = "Missing Email";
} else {
$email = $_POST["email"];
}
if (empty($_POST["password"])) {
$password_error = "Missing Password";
} else {
$email = $_POST["email"];
$password = $_POST["password"];
header ('Location: employee_profile.php');
}
}
?>
The form:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
Email: <input type="text" name="email" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $email_error;?></span><br />
Password: <input type="password" name="password">
<span class="error"><?php echo $password_error;?></span><br />
<input type="submit" value="Submit">
</form>
The PHP header (using HTTP/1.1) redirect requires an absolute URL.
Try the following:
<?php
// from PHP documentation, see http://php.net/manual/de/function.header.php
$host = $_SERVER['HTTP_HOST'];
// or:
// $host = $_SERVER['SERVER_NAME'];
$email_error = $password_error = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["email"])) {
$email_error = "Missing Email";
} else {
$email = $_POST["email"];
}
if(empty($_POST["password"])) {
$password_error = "Missing Password";
} else {
$password = $_POST["password"];
}
// some additional fixes: finally check if both is valid
if($email_error == $password_error) {
header("Location: http://$host/employee_profile.php");
}
}
?>
you can try some thing like this. currently in your script even when the email is not set but password is set, header function is called.
$email = (isset($_POST['email']) && !empty($_POST['email'])) ? $_POST['email'] : "Missing Email";
$password = (isset($_POST['password']) && !empty($_POST['password'])) ? $_POST['password'] : "Missing Password";
if($email != "Missing Email" && $password != "Missing Password"){
header ('Location: employee_profile.php');
}
(warning: here any values passed as email and password will get the user to employee_profile)
also see if you are printing some thing or some htmls before calling header.
is it throwing any error, if so can you also print the error here?

Categories