I am having problem in when I building the registration form with php and mysq.
I have two files, contactus.php and home.php.
The code for contactus.php is below:
<?php
session_start();
$db = mysqli_connect("localhost", "wadca2user", "password123", "p1514432db");
if(isset($_POST['register_btn'])){
session_start();
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['password2']);
if($password == $password2){
$password = md5($password); // stored before
$sql = "INSERT INTO users(username,email,password) Values('$username','$email','$password')";
mysqli_query($db, $sql);
$_SESSION['message'] = "Your are now logged in";
$_SESSION['username'] = $username;
header("location: home.php");
}else{
$_SESSION['message'] = "The two passwords do not match";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link href="css/maincss.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="header">
<h1>Register</h1>
</div>
<form method="post" action="contactus.php">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" class="textInput"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="email" name="email" class="textInput"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" class="textInput"></td>
</tr>
<tr>
<td>Password again:</td>
<td><input type="password" name="password2" class="textInput"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="register_btn" value="Register"></td>
</tr>
</table>
</form>
</body>
</html>
The code for home.php is below:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<link href="css/maincss.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="header">
<h1>Register</h1>
</div>
<h1>Home</h1>
<div>
<h3>Welcome<?php echo $_SESSION['username']; ?></h3>
</div>
</body>
</html>
After I click on submit, it is supposed to go to home.php. However, it does not succeed. I am not sure where is my problem.
Here is mysql 'users' table
Use PDO, this (below) should do the job, it's secure against sql injection (check prepared request for more).
You must not use MD5, it's deprecated, try sha1() or sha256().
Edit : you also have password_hash() which is quite nice.
<?php
session_start();
$servername = "localhost";
$username = "wadca2user";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=p1514432db", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(isset($_POST['register_btn']) && !is_null($conn)){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if($password === $password2){
$password = md5($password); // stored before
$request = $conn->prepare("INSERT INTO users (username,email,password) VALUES (:username, :email, :password)");
$request->bindParam(':username', $username);
$request->bindParam(':email', $email);
$request->bindParam(':password', $password);
$request->execute();
$_SESSION['message'] = "Your are now logged in";
$_SESSION['username'] = $username;
header("location: home.php");
}else{
$_SESSION['message'] = "The two passwords do not match";
}
}
?>
Related
I have 3 pages, I am trying to create a simple member login system using session .
In my first page ( index.php) I have database connection, session setup and this following login from :
<form action="index.php" method="POST">
<table>
<tr>
<td><label>Username</label></td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td><label>Password</label></td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submitbtn" value="Login" /></td>
</tr>
</table>
</form>
In member's profile page (member.php), I have a table to fetch data from database of that specific member logged in :
<table>
<?php $members=getMember(); ?>
<?php while($member = $members->fetch_assoc()) : ?>
<tr><td><label>Name</label></td><td><?php echo $member['name'];?></td></tr>
<tr><td><label>Age</label></td><td><?php echo $member['age'];?></td></tr>
<?php endwhile; ?>
</table>
and at dbconnection.php page I have this function :
<?php
function getMember(){
$db_conn = getConnection();
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
if(!$db_conn) return false;
$sql = "SELECT * FROM member WHERE username ='$username' AND password='$password'";
$result = $db_conn->query($sql);
$db_conn->close();
return $result;
}
The code of session setup are :
<?php
$username="";
$password="";
$success=true;
$_SESSION['username']=$username;
if(isset($_POST['username']) && isset($_POST['password']))
{
$username=$_POST['username'];
$password=$_POST['password'];
if(check_in_db($username,$password)){
$_SESSION['logged_in']=1;
$_SESSION['username']=$username;
header("Location: adminPanel.php");
}
else{
$success=false;
}
}
?>
But when I am logging in, data ( name and age ) is not fetching ( displaying) there in member.php page ( I can't add image, since my reputation is under 10 ).
Thank you for your time .
I would suggest you take a look at php type comparisons for how isset() works. To let you know how php session works and how users persist in different pages, you have to digg into php session. I would recommend you use PDO and its prepare method when you're dealing with user data. Here you would get a very simple example of it.
The following code is working. So please take a look at them how they are constructed:
dbconnection.php
<?php
function getConnection() {
$servername = "localhost";
$username = "root";
$password = "12345";
$dbname = "db_test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
function check_in_db($username, $password) {
$db_conn = getConnection();
if (!$db_conn) {
return false;
}
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $db_conn->query($sql);
return $result->num_rows > 0;
}
function getMember($username, $password) {
$db_conn = getConnection();
if (!$db_conn) {
return false;
}
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = $db_conn->query($sql);
return $result;
}
index.php
<?php
session_start();
require_once('./dbconnection.php');
$success = true;
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(check_in_db($username, $password)) {
$_SESSION['logged_in'] = 1;
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header("Location: adminPanel.php");
}
else{
$success=false;
}
}
?>
<form action="index.php" method="POST">
<table>
<tr>
<td><label>Username</label></td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td><label>Password</label></td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submitbtn" value="Login" /></td>
</tr>
</table>
</form>
and member.php
<?php
session_start();
require_once('./dbconnection.php');
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$members = getMember($username, $password);
?>
<table>
<?php while($member = $members->fetch_assoc()) : ?>
<tr><td><label>Name</label></td><td><?php echo $member['name'];?></td></tr>
<tr><td><label>Age</label></td><td><?php echo $member['age'];?></td></tr>
<?php endwhile; ?>
</table>
I am trying to set up a login system but the page is not doing the validation of the user and passwors. I know is connecting to the database but it doesn't show any results after the for each statement.
I have two files one for the login form(login.php) and one for the login to the database(process.php).
Here is my code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Login Page</title>
</head>
<body>
<div>
<form action="process.php" method="POST">
<p>
<label>Username:</label>
<input type="text" id="user" name="user">
</p>
<p>
<label>Password:</label>
<input type="password" id="pass" name="pass">
</p>
<p>
<label>Username:</label>
<input type="submit" id="btn" value="Login">
</p>
</form>
</div>
</body>
</html>
Process.php
<?php
//Get values from login.php file
$username = $_POST['user'];
$password = $_POST['pass'];
//Stop SQL injection
/* $username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);*/
//Connect to the server and select database
$domainsn = 'mysql:host=localhost;dbname=login';
$username = 'root';
$password = 'costarica';
try {
$db = new PDO ($domainsn, $username, $password);
echo "Connected";
} catch (Exception $e) {
$error_message = $e->getMessage();
echo "Coudn't connect due to $error_message";
}
$query = "SELECT * FROM users WHERE username = '$username' AND password ='$password'";
$result = $db->query($query);
//echo "$result";
foreach ($result as $results) {
echo "$results";
echo $users['id'];
if ($results['username'] == $username && $results['password'] == $password) {
echo "Login success!!! Welcome ".$results['username'];
} else {
echo "failed try {} catch ( $e) {}";
}
}
?>`enter code here`
You can use this i hope it will help.
$query = "SELECT * FROM users WHERE username = '".$username."' AND password ='".$password."' ";
$result = $db->query($query);
if($result->num_rows>0){
// User exists
}else{
// User not exists.
}
I need to redirect users to different pages based on the roles given to them in the database. Only the username and password is submitted on the login page. I have to fetch the role from the database which looks like this:
username | password | role
admin1 admin1 admin
alex12 alex12 (nothing to normal users)
Here is the code:
<?php
session_start();
// conectare la baza de date
$db = mysqli_connect("localhost", "root", "", "inregistrare");
if (isset($_POST['login_btn'])) {
$username = mysqli_real_escape_string($db,$_POST['username']);
$password = mysqli_real_escape_string($db,$_POST['password']);
$password = md5($password); // parola cryptata
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 1) {
$_SESSION['message'] = "Te poti Conecta!";
$_SESSION['username'] = $username;
header("location: clasa.php"); //spre o pagina
}else{
$_SESSION['message'] = "Parola gresita!";
}
}
?>
<head>
<title>Conectare</title>
<link rel="stylesheet" type="text/css" href="./css/index-style.css">
</head>
<body>
<?php
if (isset($_SESSION['message'])) {
echo "<div id='error_msg'>".$_SESSION['message']."</div>";
unset($_SESSION['message']);
}
?>
<form method="post" action="clasa.php"> <!-- modifica si aici cand modifici mai sus la php-->
<table align="center">
<tr>
<th id="titlu" class="titlu" colspan="2">Conectare</th>
</tr>
<tr>
<td class="border">Username:</td>
<td class="border"><input type="text" name="username" class="text-input" size="20"></td>
</tr>
<tr>
<td class="border">Password:</td>
<td class="border"><input type="password" name="password" class="text-input" size="20"></td>
</tr>
<tr>
<td class="spatiu"></td>
<td class="spatiu"></td>
</tr>
<tr>
<td><button class="register" type="submit" formaction="./register.php">Inregistrare</button></td>
<td><button class="connect" type="submit" name="login_btn">Conectare</button></td>
</tr>
</table>
</form>
</body>
</html>
You should check the user role. Here is an example how you can check it.
P.S the adminfile.php and anotherfile.php is where you should redirect the user and can be whatever you want.
if (mysqli_num_rows($result) == 1) {
$_SESSION['message'] = "Te poti Conecta!";
$_SESSION['username'] = $username;
$user = mysql_fetch_assoc($result);
if($user['role'] == 'admin'){
header("location: adminfile.php");
}else{
header("location: anotherfile.php");
}
}else{
$_SESSION['message'] = "Parola gresita!";
}
Use mysqli_fetch_row
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_row($result)) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
I can see that you've already got the answer from #leli.1337 But I thought I should give you same example in more secured way than the one you have above, bellow I'm using PDO prepared statements to prevent sql injections, and also There's no need to store success message /error message on a session variable.
Bellow is my code.
<?php
session_start();
// conectare la baza de date
$host_name = "localhost";
$u_name = "root";
$u_pass = "";
try {
$db = new PDO("mysql:host=$host_name;dbname=inregistrare", $u_name, $u_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $ex) {
error_log($ex);
}
$loginMessage = ""; //will fill this at a later stage.
if (isset($_POST['login_btn'])) {
$username = UserInput($_POST['username']);
$password = UserInput($_POST['password']);
try {
$stmt = $db->prepare("SELECT username,password, role FROM users where username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($result) > 1) { // username corerct
foreach ($result as $row) { // now lets validate password
if (password_verify($password, $row['password'])) {
$loginMessage = "<p style=\"color:green;\">Te poti Conecta!</p>"; //We don't really need to store the success on a session.
$_SESSION['username'] = $row['username'];
if ($row['role'] === "admin") {
//admin user
header("location:admin.php");
} elseif ($row['role'] === "") {
header("location: clasa.php"); //spre o pagina
}
} else {
// password incorrect
$loginMessage = "<p style=\"color:#f00\">Parola gresita!</p>";
}
}
}
}
catch (PDOException $e) {
error_log($e);
}
}
function UserInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<head>
<title>Conectare</title>
<link rel="stylesheet" type="text/css" href="./css/index-style.css">
</head>
<body>
<?php
echo $loginMessage;
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table align="center">
<tr>
<th id="titlu" class="titlu" colspan="2">Conectare</th>
</tr>
<tr>
<td class="border">Username:</td>
<td class="border"><input type="text" name="username" class="text-input" size="20"></td>
</tr>
<tr>
<td class="border">Password:</td>
<td class="border"><input type="password" name="password" class="text-input" size="20"></td>
</tr>
<tr>
<td class="spatiu"></td>
<td class="spatiu"></td>
</tr>
<tr>
<td><button class="register" type="submit" formaction="./register.php">Inregistrare</button></td>
<td><button class="connect" type="submit" name="login_btn">Conectare</button></td>
</tr>
</table>
</form>
</body>
</html>
As you can see I'm using password_verify() to verify the password hash instead of the md5 you used so, on your register.php page
you will need to hash the password like this:
$password = $_POST['password'];
// Now lets hash the password
$hash = password_hash($password, PASSWORD_DEFAULT);
instead of: $password= md5($_POST['password'];
So in your database you will store the $hash value
Thanks, Hope you find this more useful.
I've tried debuggind this issue for almost 4 hours with no luck. No error messages, $stmt -> execute() gives false for whatever reason that I do not know of.
register.php
<?php
session_start();
if( isset($_SESSION['id'])){
header("Location: index.php");
}
require 'database.php';
$message = '';
if(!empty($_POST['user']) && !empty($_POST['password'])):
$pass = $_POST['password'];
$user = $_POST['user'];
$sql = "Insert into user (username, password) values (:user, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':user', $_POST['user']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
//var_dump($_POST['password']);
//var_dump($_POST['user']);
if($stmt -> execute()):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Register Below</title>
</head>
<body>
<?php if(!empty($message)): ?>
<p><?= $message ?></p>
<?php endif; ?>
<h1>Register</h1>
<form class="" action="register.php" method="post">
<input type="text" placeholder="Username" name="user" id="user">
<input type="password" placeholder="and password" name="password" id="password">
<input type="password" placeholder="confirm password" name="confirm_password">
<button type="submit" name="button">Register</button>
</form>
home
</body>
</html>
database.php
<?php
$server = 'localhost';
$username ='master';
$password ='master';
$database = 'quiz';
try{
$conn = new PDO("mysql:host=$server;dbname=$database;" , $username, $password);
} catch(PDOException $e){
die ("Connection failed" . $e->getMessage());
}
?>
I know I am ignoring the confirm password, but I want to make sure I can insert into the database first.
Solution: my password length was 15 in my database... hashed password >> 15 characters. Changed the length to 255 and it's all good. Hopefully this will be useful for someone else.
Can anyone help, I have been trying to get this php code to work, with limited success, it seem the else statement in the while statement is being ignored, i have looked at other examples and just can't see what I've done wrong. The code is used within a login form and the part that doesn't work is when a user inputs the wrong password. I am new to PHP and this is for a college assignment. I will include the code for the login page also.
<?php
ob_start();
session_start();
error_reporting(0);
$username = $_POST['username'];
$password = $_POST['password'];
//sanitize username
$username = mysql_real_escape_string($username);
if($username&&$password) {
include 'db.php';
$query = mysql_query("SELECT id, username, password, salt
FROM member
WHERE username = '$username';");
$numrows = mysql_num_rows($query);
$result = mysql_query($query);
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$salt = $userData['salt'];
$hash = hash('sha256', $salt . hash('sha256', $password) );
if ($numrows !=0) {
while ($rows = mysql_fetch_assoc($query))
{
$dbusername = $rows['username'];
$dbpassword = $hash;
if ($username===$dbusername&&$hash===$dbpassword)
{
$_SESSION['username']=$dbusername;
header("location: index.php?remarks=success");
}
else
{
header("location: index.php?remarks=incorrect");
}
}
}
else
header("location: index.php?remarks=register");
}
else
header("location: index.php?remarks=other");
?>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<form method="post" action="code_index.php">
<table width="274" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<td colspan="2">
<div align="center">
<?php
$remarks=$_GET['remarks'];
if ($remarks==null and $remarks=="")
{
echo "Login Here<br/> <a href='registration.php'>Or Click Here to Register.</a>";
}
if ($remarks=='register')
{
echo "That username Does not Exists.<br/><a href='registration.php'>Click Here to register.</a>";
}
if ($remarks=='incorrect')
{
echo "Incorrect Password.<br/>Please Re-enter Password";
}
if ($remarks=='success')
{
echo "Login Successful. <br/> <a href='membersarea.php'>Click Here to go to the Members Area.</a>";
}
if ($remarks=='other') {
echo "Please enter a Username and Password<br/><a href='registration.php'>Or Click Here to register.</a>";
}
?>
</div></td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" name="username" placeholder="Enter your Username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" placeholder="Enter your Password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
You need to assign dbpassword from database
//$dbpassword = $hash; //This is wrong
Do it like this.
$dbpassword = $rows['password'];
if ($username===$dbusername&&$hash===$dbpassword)
Can you try this,
ob_start();
session_start();
error_reporting(0);
$username = $_POST['username'];
$password = $_POST['password'];
//sanitize username
$username = mysql_real_escape_string($username);
if(isset($username) && isset($password)) {
include 'db.php';
$query = mysql_query("SELECT id, username, password, salt
FROM member
WHERE username = '$username' ");
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($rows = mysql_fetch_array($query))
{
$dbusername = $rows['username'];
$salt = $rows['salt'];
$hash = hash('sha256', $salt . hash('sha256', $password) );
$dbpassword = $hash;
if ($username==$dbusername && $hash==$dbpassword)
{
$_SESSION['username']=$dbusername;
header("location: index.php?remarks=success");
}
else
{
header("location: index.php?remarks=incorrect");
}
}
}else{
header("location: index.php?remarks=register");
}
}else{
header("location: index.php?remarks=other");
}