Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I've been teaching myself PHP out of a couple of books, from the W3Schools site and using a whole bunch of posts of Stack Overflow.
To try and put something into practice I'm trying to make a small image gallery that implements a user authentication system. Users have a security access that determines wether they have read, read write access or can administrate other users etc. I've only gotten as far as the login and add user stuff.
I've modelled it off my work, where everyone has a unique employee ID and 8 digit email ID.
I know this is a long shot, but I'm just wondering if anyone would be able to take a look and tell me if my code is heading down the right track? It's so different putting something 'real world' like this together from the basic examples provided in books. Any comments and suggestions would be appreciated....
login.php
<!DOCTYPE html>
<?php
// Connect to the database
include('./helpers/db.php');
include('./helpers/general.php');
// Check if the user has submitted their details.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$loginId = htmlspecialchars(($_POST['userId']));
$loginPass = htmlspecialchars(sha1($_POST['password']));
// Check if they've submitted blank details.
if (!checkLoginId($loginId) || (!checkPassword($_POST['password']))) {
$errorMsg = "Please enter a valid username or password!";
}
else {
// Select the details we want for the session info.
$stmt = $dbh->prepare("SELECT firstName, lastName, securityLevel FROM
userDetails WHERE registeredNumber = :loginId
AND password = :loginPass" );
$stmt->bindParam(':loginId', $loginId);
$stmt->bindParam(':loginPass', $loginPass);
$stmt->execute();
// Make sure the user is found, and that there security level is 1 or more.
if ($stmt->rowCount() > 0) {
$userDetails = $stmt->fetch();
if ($userDetails['securityLevel'] < 1) {
$errorMsg = "Insufficient access for this user.";
}
else {
// Start a new session and set up the regularly used info.
session_start();
$_SESSION['loggedIn'] = 1;
$_SESSION['userID'] = $loginId;
$_SESSION['fname'] = $userDetails['firstName'];
$_SESSION['lname'] = $userDetails['lastName'];
$_SESSION['security'] = $userDetails['securityLevel'];
header("Location: ./browser/");
}
}
else {
$errorMsg = "Invalid User ID or Password!";
}
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<style type="text/css">
body {font-family:sans-serif;}
.warning {color:red;font-weight:bold;}
#login {margin-left:auto;margin-right:auto;width:200px;border-style:solid;border-width:1px;padding:20px;}
</style>
<body>
<!-- Display the login form -->
<div id="login">
<form action="login.php" method="POST">
<?php
if (isset($errorMsg)) {
echo '<span class="warning">'. $errorMsg . '</span>';
}
?>
<p><label for="userId">User Name:</label><br />
<input type="text" maxlength="5" name="userId"
title="Enter your User ID:">
</p>
<p><label for="pasword">Password:</label><br/>
<input type="password" maxlength="12" name="password"
title="Enter your password:"/>
</p>
<p><input id="submit" type="submit" name="submit" value="Submit"></p>
</form>
</div>
</body>
db.php
<?php
$hostname = 'localhost';
$dbname = 'dam';
$dbuser = 'root';
$dbpass = '****';
// Try and connect to the database and catch the error if it doesn't work.
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
echo "Connected to Database<br/>";
}
catch (PDOException $e)
{
print "Error! " . $e->getMessage() . '<br/>';
die();
}
?>
general.php
<?php
// Checks wether the loginID/Registered Number is valid
function checkLoginId($login) {
if ($login == '' || $login == NULL || (!is_numeric($login))) {
return 0;
}
else return 1;
}
// Checks whether the password is valid
function checkPassword($password) {
if ($password == '' || $password == NULL) {
return 0;
}
else return 1;
}
function verifyNewUser($userID, $upass, $fname, $lname, $email) {
$hasErrors = 0;
$errorMsg = array();
if ($userID == '' || $userID == NULL || (!is_numeric($userID)) || (strlen($userID) != 5)) {
$hasErrors++;
$errorMsg[] = "User ID is either missing, or does not have 5 digits";
}
if ($upass == '' || $upass == NULL || (strlen($upass) < 6)) {
$hasErrors++;
$errorMsg[] = "Password is either missing, or does not meet minimum length of six";
}
if ($fname == '' || $fname == NULL || empty($fname)) {
$hasErrors++;
$errorMsg[] = "First name is missing.";
}
if ($lname == '' || $lname == NULL || empty($lname)) {
$hasErrors++;
$errorMsg[] = "Last name is missing.";
}
if ($email == '' || $email == NULL || empty($email) || (strlen($email) != 8)) {
$hasErrors++;
$errorMsg[] = "Check email id, should be 8 characters.";
}
if ($hasErrors == 0) {
return 1;
}
else {
echo "Returning with errors<br/>";
return $errorMsg;
}
}
?>
adduser.php
include ("./helpers/general.php");
include('./helpers/db.php');
session_start();
// If the user isn't logged in, send them away...
if (!(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] != '')) {
header("Location: ./login.php");
exit();
}
// Get the users full name so we can politely tell them to rack off if they
// don't have sufficient access to add users.
$uname = $_SESSION['fname'] . ' ' . $_SESSION['lname'];
// Check if the user has the security clearence to add a new user:
if ($_SESSION['security'] != 4) {
echo "Sorry $uname, only level 4 administrators can manage users.<br/>";
echo 'Back to Browser';
exit();
}
// Check if they have submitted the form and validate the input
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$userID = htmlspecialchars($_POST['registeredNumber']);
$upass = htmlspecialchars($_POST['password']);
$fname = ucfirst(htmlspecialchars($_POST['firstName']));
$lname = ucfirst(htmlspecialchars($_POST['lastName']));
$email = htmlspecialchars($_POST['emailID']);
$secLev = $_POST['securityLevel'];
$creator = $_SESSION['userID'];
$valid = verifyNewUser($userID, $upass, $fname, $lname, $email);
if ($valid == 1) {
// Encrypt the password
$upass = sha1($upass);
// Create the array to feed the SQL statement.
$data = array($userID, $upass, $fname, $lname, $email, $secLev, date('Y-m-d H:i:s'), $creator);
$dbh->beginTransaction();
$stmt = $dbh->prepare("INSERT INTO userDetails VALUES('', ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute($data);
$dbh->commit();
if ($stmt->rowCount() > 0) {
echo "Success, new user $fname $lname added!<br/>";
echo "Email ID: $email<br/>";
echo "Security Level: $secLev<br/>";
}
}
else if (isset($valid)) {
foreach($valid as $error) {
echo '<span style="color:red;font-weight:bold">' . $error . "<span><br/>";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add A New User</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="adduser.php" method="post">
<table>
<tr>
<td><label for="registeredNumber">Registered Number:</label></td>
<td><input type="text" maxlength="5" name="registeredNumber"/></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" maxlength="12" name="password"/></td>
</tr>
<tr>
<td><label for="firstName">First Name:</label></td>
<td><input type="text" maxlength="20" name="firstName"/></td>
</tr>
<tr>
<td><label for="lastName">Last Name:</label></td>
<td><input type="text" maxlength="20" name="lastName"/></td>
</tr>
<tr>
<td><label for="emailID">Email ID:</label></td>
<td><input type="text" maxlength="8" name="emailID"/></td>
</tr>
<tr>
<td><label for="securityLevel">Security Level:</label></td>
<td>
<select name="securityLevel">
<option value="0" selected="selected">0 - No Access</option>
<option value="1">1 - Read Access</option>
<option value="2">2 - Read/Write Access</option>
<option value="3">3 - Read/Write/Delete Access</option>
<option value="4">4 - User Administrator</option>
</select>
</td>
</tr>
</table>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
logout.php
<?php
// Destroy the session and go to the login screen.
session_start();
session_destroy();
header("Location: login.php");
?>
There are serious security problems with your approach.
The biggest problem is you are storing the password in the database. You do not need to store the password in the database, that is a terrible idea that could be grounds for someone to sue your pants off in court.
There are a variety of encryption and hashing options to let you build a system like this without storing the password in the database, and it is standard procedure to use one of them. Anybody who doesn't is asking for problems in future (google search for "PSN password leak").
One good option is PBKDF2 http://en.wikipedia.org/wiki/PBKDF2
However, that is just the most obvious problem. There are some other things you're not doing perfectly and this really is something you need to learn how to do properly, or you should not attempt it at all. Even if you're using PBKDF2 you still need to learn how to use it properly.
I recommend listening to almost every episode of Security Now before attempting to write your own authentication system. http://www.grc.com/securitynow.htm
Related
This question already has answers here:
PHP password_hash(), password_verify()
(2 answers)
Closed 3 years ago.
I am trying to login users that are added by an admin, but when I press login, nothing happens, just a blank page with the header login.php.
Here is the code I use to add users:
<?php
include "connection.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>Add students</title>
<link rel="stylesheet" type="text/css" href="boosttrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="adduser.php" method="POST">
<div>
<h2>
Username will be generated automatically
</h2>
<br/>
<label>Password</label>
<input type="password" name="s_password" class="form-control" placeholder="Enter new passowrd">
<br/>
<label>Name</label>
<input type="text" name="s_name" class="form-control" placeholder="Enter name">
<br/>
<label>Surname</label>
<input type="text" name="s_surname" class="form-control" placeholder="Enter surname">
<br/>
<label>Date of birth</label>
<input type="date" name="s_dob" class="form-control" placeholder="Enter Date of birth">
<br/>
<label>Year group</label>
<select name ="s_yeargroup">
<option selected = "true" disabled="disabled"> Select one from below...</option>
<option value=1 >7</option>
<option value=2> 8</option>
<option value=3> 9</option>
<option value=4> 10</option>
<option value=5> 11</option>
</select>
<br/>
<button type="sumbit" name="btnAddUser" class="float" value ="Login">Create New User</button>
</div>
</form>
Logout
</body>
<?php
if(isset($_POST["btnAddUser"])){
$hashed_password = password_hash($_POST['s_password'], PASSWORD_DEFAULT);
$name = $_POST["s_name"];
$surname = $_POST["s_surname"];
$dob = $_POST["s_dob"];
$yeargroup = $_POST["s_yeargroup"];
$usernamenew = substr($name, 0, 1);
$usernamenew1 = substr($surname, 0, 4);
$usernamenew3= $usernamenew.$usernamenew1;
$sql = "INSERT INTO tbluser (Username, Password, Role) VALUES ('$usernamenew3', '$hashed_password', 'Student')";
if(!mysqli_query($conn,$sql))
{
echo "Error with Username or password";
}
else
{
echo "Username and password created successfully. The username is ".$usernamenew3.".";
}
$sql4= "SELECT ID FROM tbluser WHERE Username = '$usernamenew3'";
$result1= mysqli_query($conn,$sql4);
$row= mysqli_fetch_assoc($result1);
$userid=$row['ID'];
$sql1 = "INSERT INTO student (name, surname, dob, yeargroup_id, tbluser_ID) VALUES ('$name','$surname','$dob','$yeargroup','$userid')";
if(!mysqli_query($conn,$sql1))
{
echo "Error with Student info";
}
else
{
echo " \r\nStudent has been added successfully.";
}
}
?>
And here is my code that I use to login users
<?php
session_start();
require_once "connection.php";
$message = "";
$role = "";
if(isset($_POST["btnLogin"]))
{
$password = $_POST["password"];
$stmt=$conn->prepare("SELECT Username, Password FROM tbluser WHERE Username = ? ");
$stmt-> bind_param("s",$_POST["username"]);
$stmt->execute();
$result = $stmt->get_result();
if(mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
if(password_verify($password, $row["Password"]))
{
if($row["Role"] == "Admin")
{
$_SESSION['AdminUser'] = $row["Username"];
$_SESSION['adminid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: admin/admin.php');
}
elseif($row["Role"] == "Teacher")
{
$_SESSION['ProfUser'] = $row["Username"];
$_SESSION['teacherid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: teacher/prof.php');
}
elseif($row["Role"] == "Student")
{
$_SESSION['StudentUser'] = $row["Username"];
$_SESSION['studentid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: student/student.php');
}
else
echo "Role is not recognised";
}
}
}
}
If anyone could find my mistake, I would appreciate it. Thank you
My database in case you need it.
Your use of password_hash() and password_verify() is fine.
You're only selecting the Username and Password columns from the table. So $row["Role"] won't be set and none of the if conditions will succeed. You should be getting the error Role is not recognized as a result.
Change it to:
$stmt=$conn->prepare("SELECT Username, Password, Role, ID FROM tbluser WHERE Username = ? ");
Also, add else statements so you know which if condition is failing when the login fails.
<?php
if(isset($_POST["btnLogin"]))
{
$password = $_POST["password"];
$stmt=$conn->prepare("SELECT Username, Password FROM tbluser WHERE Username = ? ");
$stmt-> bind_param("s",$_POST["username"]);
$stmt->execute();
$result = $stmt->get_result();
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
if(password_verify($password, $row["Password"]))
{
if($row["Role"] == "Admin")
{
$_SESSION['AdminUser'] = $row["Username"];
$_SESSION['adminid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: admin/admin.php');
}
elseif($row["Role"] == "Teacher")
{
$_SESSION['ProfUser'] = $row["Username"];
$_SESSION['teacherid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: teacher/prof.php');
}
elseif($row["Role"] == "Student")
{
$_SESSION['StudentUser'] = $row["Username"];
$_SESSION['studentid']= $row["ID"];
$_SESSION['role'] = $row["Role"];
header('Location: student/student.php');
}
else
echo "Role is not recognised";
} else {
echo "Password incorrect";
}
} else {
echo "Username not found";
}
} else {
echo "Form not submitted correctly";
}
You don't need a while loop when fetching the row, since usernames are unique; there's just one row.
From the password_hash documentation, password_hash with PASSWORD_BCRYPT, produces a string 60 characters long and other algorithms might produce even longer. Your Password field in the database is only 45 characters.
As per recommendation from the documentation, you should increase the field size to 255.
having a bit of trouble with my login / reg forms
Basically when i register (create new user) it takes me to the login.php script and not the register script.
The login form is in the "header.php" page so its at the top of every page including the register form. But dont think that would be an issue?
Register form
<?php
include("config.php");
include("header.php");
?>
<div id="contentwrap">
<form name="myuserform" method="POST" action="register.php" onsubmit="return validateForm();">
<tr class='alt'>
<td>email address: <td><input type="text" name="email">
<tr class='alt'>
<td>Password: <td><input type="password" name="password">
<tr class='alt'>
<td>Your name: <td><input type="text" name="username">
<tr class='alt'>
<td><input type="submit" name="adduser" value="Sign me up!">
</form>
</div>
Register.php
<?php
if (isset($_POST['adduser']))
{
$error = "";
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$md5_pass = md5($password);
$email = mysqli_real_escape_string($connection, $_POST['email']);
if (!isset($username) || empty($username) ||
!isset($password) || empty($password) ||
!isset($email) || empty($email))
{
$error = "All fields must be filled out";
}
else if (user_exists($connection, $username))
{
$error = "Username already registered";
}
else if (strlen($password) < 6)
{
$error = "Password must be at least 6 characters";
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // check if email looks valid
{
$error = "Please enter a valid email";
}
if ($error == "")
{
//$query = "INSERT INTO users (email, password, username) VALUES ('{$email}','{$md5_pass}','{$username}')";
$query = "INSERT INTO users (username, password, email) VALUES ('{$username}','{$md5_pass}','{$email}')";
$result = mysqli_query($connection, $query);
if ($result)
echo " <b>Registered successfully!</b><br/>Please return to the <a href='index.php'>index</a> to login.";
else
$error = "Unable to create new user";
}
if ($error != "") // redo error string check since the last block may have set it
{
echo "Error: {$error}. Please return to the previous page.";
}
exit();
}
?>
Login.php
<?php
include("config.php");
if (isset($_POST['username']) && !empty($_POST['username']) &&
isset($_POST['password']) && !empty($_POST['password']))
{
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = md5($_POST['password']);
$query = "SELECT * FROM users WHERE username='{$username}' AND password='{$password}'";
$res = mysqli_query($connection, $query);
if (mysqli_num_rows($res) >= 1)
{
$row = mysqli_fetch_array($res);
if($row['rank'] == "banned")
{
echo "You have been banned from the site.";
exit();
}
$_SESSION['uid'] = $row['userid'];
$_SESSION['username'] = $row['username'];
if($row['rank'] == "admin")
$_SESSION['is_admin'] = true;
header("Location: index.php");
exit();
}
else
{
echo "Username/password invalid. Return to the <a href='index.php'> home </a>page";
exit();
}
}
echo "Something went wrong, try again"; <--- this is the result im getting
?>
here is the login form (apart of header.php)
<?php
if (!isset($_SESSION['uid']) || empty($_SESSION['uid']))
{
echo "<form action='login.php' method='post'>
Username: <input type='text' name='username' Placeholder='Username' style='width:100px;'/>
Password: <input type='password' name='password' Placeholder='Password' style='width:100px;' />
<input type='submit' name='submit' value='Log In' />";
echo "<div id='freeman'>
<a href='signup.php'> <img src='images/register.jpg' width='60px' height='60px' /> </a>
</div>";
} else {
echo "You are logged is as {$_SESSION['username']} • <a href='logout.php'>Logout</a>";
}
?>
The problem that when you register your not opening a session to consider the user as logged and acquire a session for him.
The other issue your not checking in your login script if the user already have a session which implies that he is already logged in
I am making php login function and I have come across a problem. In one part of the script I am testing whether all of the info is inserted in html form that is fed to the script via $_POST variable. And in one part, the script correctly evaluates whether only username is not entered or only password, and it correctly evaluates whether password is wrong BUT when I enter correct user/pass, it activates error "Username and password not entered". I can't figure it out. Is it possible that FLASE && FALSE equals TRUE?
---Edit----
Ok, I see now that I should included all of the relevant files in this question. So here they are:
index.php
<?php
session_start();
if (isset($_SESSION['login_message'])) {
$message = $_SESSION['login_message'];
unset($_SESSION['login_message']);
}
?>
<html>
<head>
<?php
require_once("include/head.php");
?>
</head>
<body>
<form action="auth/login.php" method="post">
<table>
<tr>
<td>
<img src="graphics/znak_hrz.png" alt="Znak HRZ" style="height: 200px; padding: 10px;">
</td>
<td>
<table style="padding: 10px;">
<tr>
<td><?php if (isset($message)) {echo "<td>" . $message . "</td>";}?></td>
</tr>
<tr>
<td>
<label for="username">Username:</label>
<input id="username" type="text" name="username" />
</td>
</tr>
<tr>
<td>
<label for="password">Password:</label>
<input id="password" type="password" name="password" />
</td>
</tr>
<tr>
<td style="text-align: center;">
<input type="submit" name="login" value="Login" />
</td>
</tr>
</table>
</td>
<td>
<img src="graphics/znak_eskadrile.png" alt="Znak eskadrile" style="height: 200px; padding: 10px;">
</td>
</tr>
</table>
</form>
</body>
</html>
login.php
<?php
session_start();
// This script will deny access if following conditions are met in that order:
// - Username not entered
// - Password not entered
// - Username and password not entered
// - User doesn't exist in the database
// - User is deactivated in the database
// - The password is wrong
// Upon successful login, it will redirect user to secure/index.php and
// upon unsuccessful login it will return him to index.php for another try.
// If username is not set, set an error message
if (empty($_POST['username']) && !empty($_POST['password'])) {
$_SESSION['login_message'] = "Username missing";
}
// If password is not set, set an error message
if (empty($_POST['password']) && !empty($_POST['username'])) {
$_SESSION['login_message'] = "Password missing.";
}
//If username AND password are not set, set an error message
if (empty($_POST['username']) && empty($_POST['password'])) {
$_SESSION['login_message'] = "Username and password empty.";
}
// Check if the username exists in the database and if the password is correct
if (!isset($_SESSION['login_message']) && !empty($_POST['username']) && !empty($_POST['password'])) {
require_once("database.php");
// Sanitize incoming username and password
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
// Determine whether an account exists matching this username and password
$stmt = $auth_db->prepare("SELECT uid, pid, password, access_category, last_log, active FROM " . TBL_USERS . " WHERE username = ?");
// Bind the input parameters to the prepared statement
$stmt->bind_param('s', $username);
// Execute the query
$stmt->execute();
// Assign results of query to temporary variables
$stmt->bind_result($uid, $pid, $db_password, $access_category, $last_log, $active);
$stmt->fetch();
// If user doesn't exist in the database, deny login
if (!isset($uid)) {
$_SESSION['login_message'] = "User doesn't exist.";
}
// If user is deactivated, deny login
if (isset($uid) && !$active) {
$_SESSION['login_message'] = "User is deactivated.";
}
// If the password is wrong, deny login
if (isset($uid) && $active && $db_password != md5($password)) {
$_SESSION['login_message'] = "Wrong password.";
}
if (!isset($_SESSION['login_message'])) {
// Close previous statement
$stmt->close();
// Update the account's last_login column
$stmt = $auth_db->prepare("UPDATE " . TBL_USERS . " SET last_log = NOW() WHERE username = ?");
var_dump($stmt);
$stmt->bind_param('s', $username);
$stmt->execute();
// Set session variable
$_SESSION['username'] = $username;
$_SESSION['uid'] = $uid;
$_SESSION['pid'] = $pid;
$_SESSION['last_log'] = $last_log;
$_SESSION['active'] = $active;
$_SESSION['access_category'] = $access_category;
}
}
if (!isset($_SESSION['login_message'])) {
header('Location: ../secure/index.php');
} else if (isset($_SESSION['login_message'])) {
header('Location: ../index.php');
}
?>
secure/index.php
<?php
session_start();
require_once("../auth/login.php");
?>
<html>
<head>
<?php
#if($_SESSION['access_category'] == '0') {
# header('Location: eth93sl/');
#}
?>
</head>
<body>
<?php
echo "uid:" . $_SESSION['uid'] . "<BR>";
echo "username: " . $_SESSION['username'] . "<BR>";
echo "active: " . $_SESSION['active'] . "<BR>";
echo "last_log: " . $_SESSION['last_log'] . "<BR>";
echo "access_category: " . $_SESSION['access_category'] . "<BR>";
?>
</body>
</html>
The problem was that the login.php script was executing twice because of the line three in secure/index.php, a remnant line from another login system I was experimenting with. And second time that the script got called, it had no $_POST data, hence no username and no password so the apropriate conditional got activated.
Reminded me that when I come across a problem, it is always good to broaden my view to other files as well.
So I have two files, one is index.php and register.php. Index is the form and register is the PHP handling the form. So here's index.php
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<form class="form-signin" role="form" action="register.php" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
<input type="password" class="form-control" placeholder="Password" name="password">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
</body>
</html>
And my register.php
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
exit($e->getMessage());
}
//Post
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
//Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1))
{
echo "Complete all fields";
}
// Password match
if ($password != $password1)
{
echo $passmatch = "Passwords don't match";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo $emailvalid = "Enter a valid email";
}
// Password length
if (strlen($password) <= 6){
echo $passlength = "Choose a password longer then 6 character";
}
if(empty($passmatch) && empty($emailvalid) && empty($passlength)) {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
?>
But here's what I want to do, I want to display the PHP errors alongside the form instead of having them displayed on register.php But I also want to use two separate files. Instead of combining the two files together. Any ideas?
I seriously don't understand your use of server side to do all these validations. It is wise and economical to do this in the client side itself. There are a hell lot of plugins for client side form validation, if that's the case for you.
A few scripts would be:
jQuery Form Validator
jQuery Validation Plugin
jQuery plugin: Validation
10 jQuery Form Validation Techniques and Tutorials
Find the last link to do the work yourself.
In your case, please try to separate the view and logic. It is also wise to follow Model-View-Controller architecture that is followed in many of the PHP Web Applications and JavaScript Apps now-a-days.
Or if you somehow need the logic to be done in server side, separate the form by putting the HTML inside form.php. And in your validation, do a small change, by including a flag, which is set to false, when the form is not validated.
Now, if the validation is not successful, i.e., the flag $valid = false, then you include the form.inc, else include success.inc.
if ($valid)
include 'success.inc';
else
include 'form.inc';
And since it is going to be in the same file, in the form.inc, add this line:
if (!$valid)
echo '<p class="error">You have errors in your form! Please correct them!</p>';
At the bottom of register.php simply call:
include 'index.php';
And your form will be displayed.
Add a line to display errors in your index.php:
<?php if (!empty($error)) { ?>
<?php echo "error occured: ".$error; ?>
<?php } ?>
This is a style of MVC programming (Model-View-Controller). The idea is not to echo things all over the place within register.php, instead you build up an application state in a model and then the view (index.php) reads from the model.
Try this out:
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<?php
if(isset($_POST['submit'])){
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
exit($e->getMessage());
}
//Post
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
//Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1))
{
echo "Complete all fields";
} if ($password != $password1)
{
echo $passmatch = "Passwords don't match";
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo $emailvalid = "Enter a valid email";
} else if (strlen($password) <= 6){
echo $passlength = "Choose a password longer then 6 character";
} if(empty($passmatch) && empty($emailvalid) && empty($passlength)) { // You don't need this line, you already checked above if these POST variables were empty.
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
}
?>
<form class="form-signin" role="form" action="" method="post">
<h2 class="form-signin-heading">Please sign up</h2>
<input type="text" class="form-control" placeholder="Name" name="name" autofocus style="border-color:#<?php ?>;">
<input type="text" class="form-control" placeholder="Username" name="username" autofocus>
<input type="text" class="form-control" placeholder="Email" name="email" autofocus>
<input type="password" class="form-control" placeholder="Password" name="password">
<input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
<button class="btn btn-lg btn-primary btn-block" name='submit' type="submit">Sign up</button>
</form>
</div>
</body>
</html>
Few notes:
Leaving the action value blank will cause the form to post back to
itself.
I will fix the spacing when I get home, I don't have my editor with me.
The errors should be displayed underneath the container. I made it so that only one error is display at a time, do let me know if you
want to display all the errors at once.
I wouldn't recommend doing the registration form this way, it's way too messy. However, if this is your learning process, then all the power to you.
register.php
<?php
//Connections
try {
$handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
exit($e->getMessage());
}
//Post shit
$name = $_POST['name'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];
$error = null;//set it to null
//Verifcation
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)){
$error .= "Complete all fields\n";
}
// Password match
if ($password != $password1){
$error .= "Passwords don't match\n";
}
// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error .= "Enter a valid email\n";
}
// Password length
if (strlen($password) <= 6){
$error .= "Choose a password longer then 6 character\n";
}
if(!isset($error)){
//no error
$sthandler = $handler->prepare("SELECT username FROM users WHERE username = :name");
$sthandler->bindParam(':name', $username);
$sthandler->execute();
if($sthandler->rowCount() > 0){
error .= "exists! cannot insert\n";
} else {
//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';
$query = $handler->prepare($sql);
$query->execute(array(
':name' => $name,
':username' => $username,
':email' => $email,
':password' => $password,
':ip' => $ip
));
}
}else{
error .= "error occured: ".$error;
}
if(!isset($error)){
header( 'Location: index.php' ) ;
}
else {
header( 'Location: register.php?err='.$error ) ;
}
To display the error on your form place this code:
if(isset($_GET['err'])){
$error = $_GET['err'];
echo "error: $error";
}
I'm using this code to validate my my html form and I now need to add the form data into a table in mysql. How do I proceed I know the basics of creating a connection and sql databases but since I've already used the form's submit button i don't know how to get the data to a place where I can insert it again
<?php
// define variables and initialize with empty values
$nameErr = $passErr = $emailErr =$cpassErr="";
$name = $pass = $cpass = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$nameErr = "Enter Username";
}
else {
$name = $_POST["username"];
}
if (empty($_POST["password"])) {
$passErr = "Enter password";
}
else {
$pass = $_POST["password"];
}
if (empty($_POST["cpassword"])) {
$cpassErr = "Retype password";
}
else {
$cpass= $_POST["cpassword"];
}
if (empty($_POST["email"])) {
$emailErr = "Enter email";
}
else {
$email = $_POST["email"];
}
}
?>
<html>
<head>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table border="0" cellspacing="20">
<tbody>
<tr>
<td>Username:</td>
<td><input type="text" name="username" accept="" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="password" accept="" value="<?php echo htmlspecialchars($pass);?>">
<span class="error"><?php echo $passErr;?></span></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="text" name="cpassword" accept=""value="<?php echo htmlspecialchars($cpass);?>">
<span class="error"><?php echo $cpassErr;?></span></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" accept="" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span></td></td>
</tr>
</tbody>
</table>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Code for the connection
<?php
$host="localhost";
$username="root";
$password="root";
$db_name="LSDB";
$con=mysqli_connect("$host","$username","$password","$db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
var_dump($_POST);
$u=$_POST['username'];
$p=$_POST['password'];
$e=$_POST['email'];
$ph=$_POST['phone'];
$sql="INSERT INTO register (username,password,email,phone)
VALUES
('$u','$p','$e','$ph')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
first off i would suggest you escaping the inputs.
also worth noting you could use prepared statements and object oriented way of mysqli as most of the documents on OO are clearer than the procedural way.
like :
<?php
$u=striptags($_POST['username']);
$p=striptags($_POST['password']);
$e=filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$ph=(int)$_POST['phone'];
$mysqli = new mysqli($host,$username,$password,$db_name);
$query = "INSERT INTO register (username,password,email,phone) VALUES (?,?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssi", $u, $p, $e, $ph);
$stmt->execute();
$mysqli->close();
?>
it would not also hurt using hash on your password like :
<?php
$salt = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
$passh = crypt($pass, '$6$'.$salt);
?>
do note that you will need to store the salt in mysql also so you can compare it later
so with these your passwords are safer and if your database gets stolen the passwords will remain hashed.
When the user submits the form, if the validation was successful, then you should execute a process function, where you can place as much instructions as you need, including storing the data in a database, or printing it in an auto-generated webpage. Everything you need.
In another order of things, looks like that code of you is too simple and hence vulnerable to cross-site scripting. You should not only validate if the fields are empty or not, but also you should use some regular expressions and the function preg_match( ) to filter which characters are entered. The best protection is to allow the user enter only the characters that are needed in each field, and not any others than those.
Example on how to handle the logic of the form:
if ($_POST['_submit_check']) {
// If validate_form() returns errors, pass them to show_form()
if ($form_errors = validate_form()) {
show_form($form_errors);
} else {
// The data sent is valid, hence process it...
process_form();
}
} else {
// The form has not been sent, hence show it again...
show_form();
}