After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;
Related
I want to create a login page for admin and super admin in one PHP page. Currently, I do login page for admin and super admin separately but use the same database table.
Below is my current code for admin and super admin login
admin_login.php
<?php
include("config/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$Email = mysqli_real_escape_string($link,$_POST['Email']);
$Pwd = mysqli_real_escape_string($link,$_POST['Pwd']);
$sql = "SELECT staff.Email FROM staff WHERE Email = '$Email' AND Pwd ='$Pwd' AND staff.Role = 'admin'";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = $Email;
header("location: pages/dashboard/dashboard_admin.php");
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
super_admin_login.php
<?php
include("config/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$Email = mysqli_real_escape_string($link,$_POST['Email']);
$Pwd = mysqli_real_escape_string($link,$_POST['Pwd']);
$sql = "SELECT staff.Email FROM staff WHERE Email = '$Email' AND Pwd ='$Pwd' AND staff.Role = 'super_admin'";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = $Email;
header("location: pages/dashboard/dashboard_super_admin.php");
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
can anyone help me? Really appreciate
What you are doing now is to check if there is any username and password with the specific role, why not checking username and password and after that check the role of it to redirect to correct place ?
You can merge them, What you should do is to first check username and password and after that check the role to see if it is Admin or Super Admin to redirect to correct dashboard.
<?php
include("config/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$Email = mysqli_real_escape_string($link,$_POST['Email']);
$Pwd = mysqli_real_escape_string($link,$_POST['Pwd']);
$sql = "SELECT staff.Email,staff.Role FROM staff WHERE Email = '$Email' AND Pwd ='$Pwd'"; // Remember You do not need to check role here so you can accept both
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = $Email;
if($row["Role"] == "admin"){ //Check the role here
header("location: pages/dashboard/dashboard_admin.php");
}else{ // If you want to be more specific you can write a else-if here too.
header("location: pages/dashboard/dashboard_super_admin.php");
}
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
PS: NEVER STORE PLAIN PASSWORD AND USE PREPARED STATEMENTS TO PREVENT SQL INJECTION
You are approaching this from slightly the wrong perspective. Every user should login through the same script. User presents a UserId (Email in your case) and Password, you check they are correct and THEN you pick up the staff.Role to know what kind of user they are, and treat them accordingly
I have also changed your code to use a prepared, parameterised and bound query
<?php
include("config/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
//$Email = mysqli_real_escape_string($link,$_POST['Email']);
//$Pwd = mysqli_real_escape_string($link,$_POST['Pwd']);
$sql = "SELECT Pwd, Role
FROM staff
WHERE Email = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param('s',$_POST['Email']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($result->num_rows == 1 )
// this should really be using `password_verify()`
// but as that requiesa change to the way you save the password
// I cannot just add it here
if ( $_POST['Pwd'] == $row['Pwd'] ){
$_SESSION['login_user'] = $Email;
// might be useful to put the role in the session for later use as well
$_SESSION['Role'] = $row['Role'];
if ($row['Role'] == 'admin')
header("location: pages/dashboard/dashboard_admin.php");
exit;
}
if ($row['Role'] == 'super_admin')
header("location: pages/dashboard/dashboard_super_admin.php");
exit;
}
} else {
$error = "Your Login Name or Password is invalid";
}
}
}
?>
Additional reading to change your code to use the more secure password_hash() and pasword_verify()
I imneed to display logged in/authenticated user's id in html page. My sign in script is below followed by the display script. I've been on it for quite a while. I need to display logged in user's id from the mysql database to html.
<?php
session_start();
include_once('server.php');
$error = false;
if(isset($_POST['btn-login'])){
$username = trim($_POST['username']);
$username = htmlspecialchars(strip_tags($username));
$password = trim($_POST['password']);
$password = htmlspecialchars(strip_tags($password));
if(empty($username)){
$error = true;
$errorUsername = 'Please Input Username';
}
if(empty($password)){
$error = true;
$errorPassword = 'Please Input Password';
}elseif(strlen($password)< 6){
$error = true;
$errorPassword = 'Password must be at least six characters';
}
if(!$error)
{
$password = md5($password);
$sql = "select * from users where username = '$username'";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
if($count==1 && $row['password'] == $password){
$_SESSION['username'] = $row['username'];
header('location: loggedin.php');
}else{
$errorMsg = 'Invalid Username or Password';
}
?>
//display script
<?php
session_start();
echo 'welcome user'.$_SESSION['id'];
?>
You need to set session like this.
$_SESSION['id'] = row['id'];
You are not getting the id value because $_SESSION['id'] is null.
to display the loged user
change this:
echo 'welcome user'.$_SESSION['id'];
to this:
echo 'welcome user'.$_SESSION['username'];
because $_SESSION['id'] is not set and you most probably dont want to show it in the html page so just use the user name or set it to somthing more natural like actual name if it exists in your db row.
So I am trying to create a simple login structure, and im not sure why it does not work, I appreciate there are many examples on here, and please do not mark this for duplication, I just really need some help I have tried and tried but I can not see what I have done wrong.
<?php
session_start();
include 'databaseconnection.php';
$email = strip_tags($_POST['email']);
$pwd = strip_tags($_POST['pwd']);
$sql = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd'];
$hash = password_verify($pwd, $hash_pwd);
if ($hash == 0) {
header("Location: error.php")
exit();
} else {
$sql = "SELECT * FROM user WHERE email='$uid' AND pwd ='$hash_pwd'";
$result = mysqli_query($conn, $sql);
if (!row = mysqli_fetch_assoc($result)); {
echo "your email address or password is incorrect!";
} else {
$_SESSION['id'] = $row['id'];
}
header("Location: profile.php")
If someone could simply suggest what changes I should make, I would really appreciate it.
There you go simple code
<?php
session_start();
include 'databaseconnection.php';
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$sql = "SELECT * FROM user WHERE email = '$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd']; // password from database
// if password is valid start session and redirect to profile.php
if (password_verify($pwd, $hash_pwd))
{
$_SESSION['id'] = $row['id'];
header('Location: profile.php');
}
else
{
header("Location: error.php")
exit();
}
?>
You have not closed the "} else {"... section.
First check request second filter input third use pdo
<?php
session_start();
include 'databaseconnection.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = filter_input(INPUT_POST, 'email',FILTER_VALIDATE_EMAILL); //filter input
$pwd = filter_input(INPUT_POST, 'pwd',FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_HIGH); //filter input
$hashed = sha1($pwd);
$sql= $conn->prepare( "SELECT * FROM user WHERE email ? AND password = ?"); //use pdo here
$sql->execute(array($email, $pwd));
$row = $sql->fetch();
if($row['email'] !== $email || $row['password'] !== $hashed){
header("Location: error.php");
exit();
} else {
$_SESSION['id'] = $row['id'];
header("Location: profile.php");
}
}else {
echo 'error';
}
?>
I have realized why i can't actually access userdata (after i am logged) old way to find the username is $_SESSION['username']; (assuming there is a row as 'username' in MySQL database)
So as i have a test account as "good25" (reason to choose numbers was to see if Alphanumeric inputs works fine.. its just checkup by me.. nevermind)
Problem :
assuming, i have rows in a table as 'username' and all of his information.. such as 'password', 'email', 'joindate', 'type' ...
On net i found out how to snatch out username from Session
<?php session_start(); $_SESSION('username'); ?>
successful!!
i had an idea to check if session is actually registering or no??
after a log on start.php i used this code
if(isset($_SESSION['username'])) { print_r($_SESSION['username']); }
the result was "1" (while i logged in using this username "good25")
any suggestions?
index.php (lets say, index.php just holds registration + Login form + registration script.. in login form, action='condb.php')
<?php
require 'condb.php';
if (isset($_POST['btn-signup']))
{
//FetchInputs
$usern = mysqli_real_escape_string($connection,$_POST['username']);
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$repassword = mysqli_real_escape_string($connection,$_POST['repassword']);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
//SearchUser
$searchusr = "SELECT username FROM $user_table WHERE username='$usern'";
$usersearched = mysqli_query($connection, $searchusr);
$countuser = mysqli_num_rows($usersearched);
//SearchEmail
$searcheml = "SELECT email FROM $user_table WHERE email='$email'";
$emlsearched = mysqli_query($connection, $searcheml);
$counteml = mysqli_num_rows($emlsearched);
//RegisteringUser
if ($countuser == 0)
{
if ($counteml == 0)
{
$ctime = time();
$cday = date("Y-m-d",$ctime);
$aCode = uniqid();
$adduser = "INSERT INTO $user_table(username, email, password, realname, activationcode, verified, joindate, type, points) VALUES ('$usern','$email','$password','$name','$aCode','n','$cday','Free',$signPoints)";
if (mysqli_query($connection, $adduser))
{
?><script>alert('You have been registered');</script><?php
}
else {
?><script>alert('Couldnt Register, please contact Admin<br><?mysqli_error($connection);?>');</script><?php
}
} else {
?><script>alert('Email already exists!');</script><?php
}
} else {
?><script>alert('Username already exists!');</script><?php
}
}
?>
condb.php
$connection = mysqli_connect($db_server, $db_user, $db_pass);
mysqli_select_db($connection, $db_name);
if(!$connection) {
die ("Connection Failed: " . mysqli_connect_error);
}
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($connection,$_POST['uname']);
$upass = mysqli_real_escape_string($connection,$_POST['upass']);
//FindUser
$finduser = "SELECT * FROM $user_table WHERE username='$uname' AND password='$upass'";
$findinguser = mysqli_query($connection,$finduser);
$founduser = mysqli_num_rows($findinguser);
//ConfirmPassword
if ($founduser > 0)
{
session_start();
$_SESSION['username'] = $username;
$_SESSION['username'] = true;
if ($findinguser != false)
{
while ($fetchD = mysqli_fetch_array($findinguser, MYSQLI_ASSOC))
{
$fetchD['username'] = $usernn;
$fetchD['email'] = $email;
$fetchD['userid'] = $uid;
$fetchD['realname'] = $rlnm;
$fetchD['points'] = $pts;
$fetchD['type'] = $membertype ;
}
header("Location: start.php");
} else {
echo mysqli_error();
}
} else {
header("Location: index.php");
?><script>alert('Wrong details, please fill in correct password and email');</script><?php
}
}
I am not asking you to build a script.. just little help please? (Thank you so so so so so much, as i am a self-learner, you don't have to say everything.. just a clue is enough for me)
may be you can try this code
<?php
require_once 'require.inc.php';
//session_start();
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($_POST['uname']);
$upass = mysqli_real_escape_string($_POST['upass']);
$search = mysqli_query($connection, "SELECT username, userid, password from $user_table WHERE username='$uname' AND password='$upass'");
$match = mysqli_fetch_assoc($search);
if ($match == 1 and $match['password'] == md5($upass))
{
$_SESSION['username'] = $match['userid'];
} else {
?>
<script>alert('Password or E-mail is wrong. If you havent registered, Please Register');</script>
<?php
}
}
if (isset($_SESSION['username']) or isset($match['userid'])){
header("Location:start.php");
}
if (isset($_POST['btn-signup']))
{
$name = mysqli_real_escape_string($_POST['name']);
$usern = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$repassword = mysqli_real_escape_string($_POST['repassword']);
$name = trim($name);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
$query = "SELECT email FROM $user_table WHERE email='$email'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
$querytwo = "SELECT username FROM $user_table WHERE username='$usern'";
$resulttwo = mysqli_query($connection, $querytwo);
$counttwo = mysqli_num_rows($resulttwo);
if ($count == 0 AND $counttwo == 0)
{
if ($password == $repassword) {
if (mysqli_query($connection, "INSERT INTO $user_table(username, email, password, realname) VALUES ('$usern','$email','$password','$name')"))
{
?>
<script> alert ('Successfully registered'); </script>
<?php
}
}else {
?>
<script> alert ('The Password you entered, doesnt match.. Please fill in the same password'); </script>
<?php
}
}
else {
?>
<script> alert('Username or E-mail already exist'); </script>
<?php
}
}
?>
and this is for require.inc.php
<?php
global $username;
//require 'dconn.php';
session_start();
$_SESSION["username"] = $username;
$connection = mysqli_connect("localhost","root","", "test") or die(mysqli_error());
// Check Login
if (isset($_SESSION['username']) and isset ($match['userid']))
{
$Selection = "SELECT * FROM $user_table WHERE username='$username'";
$selectQuery = mysqli_query($connection, $Selection);
if ($selectQuery != false)
{
while ($fetchD = mysqli_fetch_assoc($selectQuery))
{
$usernn = $fetchD['username'];
$email = $fetchD['email'];
$uid = $fetchD['userid'];
}
} else {
echo mysqli_error();
}
}
?>
#suggestion, create session after user login and authorized then for each page start session and take session which you created and perform SQL queries using that session variable.
for example :
$_SESSION['user_name']=$row['username'];
for each page:
session_start();
$user_name=$_SESSION['user_name'];
SQL query
mysqli_query($con,"SELECT * FROM users where column_name='$user_name'");
I think you need to include dconn.php file in all files where you want to perform the mysql operation. If you have included it only in require.inc.php then you you it in all your other files.
This is my auth file
i got a db with
username
password
email
positief(here is a "1" or a "0", a "1" if you got admin rights)
I want my code to recognize the "1" and give you acces to a page if you have the 1""
if you dont you can't enter it.
<html>
<body>
<?php
session_start(); // Create the session, Ready for our login data.
$username = $_POST['username']; // Gets the username from the login.php page.
$password = $_POST['password']; // Gets the plain text password.
$database = "cmict_test";
// Connect to your database
mysql_connect("","","") or die(mysql_error());
mysql_select_db("$database");
$query = "SELECT * FROM users WHERE password = '$password' LIMIT 1";
$username = mysql_real_escape_string($username); // just to be sure.
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$resusername = $row['username']; // username from DB
$respassword = $row['password']; // password from DB
$resemail = $row['email']; // email from db
$admin = $row['positief'];
}
// Are they a valid user?
if ($resusername == $username && $respassword == $password) {
// Yes they are.
// Lets put some data in our session vars and mark them as logged in.
$_SESSION['loggedin'] = "1";
$_SESSION['email'] = $resemail;
$_SESSION['username'] = $resusername;
header("location:navigra.php");
}else{
// No, Lets mark them as invalid.
$_SESSION['loggedin'] = "0";
echo "Sorry, Invalid details.<br>";
die ('klik hier om opnieuw te proberen.');
}
if ($admin == 1) {
$_SESSION['logadmin'] = "1";
} else {
$_SESSION['logadmin'] = "0"
echo "You are no admin";
die ('klik hier');
}
?>
</body>
</html>
and this is what i put on top of the page
to check if you are loggedin and if you got admin rights
<?php
session_start(); // Start the session
$loggedin = $_SESSION['loggedin']; // Are they loggedin?
$logadmin = $_SESSION['logadmin']; // Are they admin?
// They are not logged in, Kill the page and ask them to login.
if ($loggedin != "1") {
die('Sorry you are not logged in, please click Here to
login');}
if ($logadmin != "1") {
die ('You have no POWER here');}
?>
Can someone help me with this? i would appreciate it alot.
Thank you in advance!
Greetings,
DTcodedude
<html>
<body>
<?php
session_start(); // Create the session, Ready for our login data.
$username = addslashes($_POST['username']); // Gets the username from the login.php page.
$password = addslashes($_POST['password']); // Gets the plain text password.
$database = "cmict_test";
// Connect to your database
mysql_connect("","","") or die(mysql_error());
mysql_select_db("$database");
$query = "SELECT * FROM users WHERE username = '$username' and password = '$password' LIMIT 1";
$username = mysql_real_escape_string($username); // just to be sure.
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$resusername = $row['username']; // username from DB
$respassword = $row['password']; // password from DB
$resemail = $row['email']; // email from db
$admin = $row['positief'];
}
// Are they a valid user?
if ($resusername == $username && $respassword == $password) {
// Yes they are.
// Lets put some data in our session vars and mark them as logged in.
$_SESSION['loggedin'] = "1";
$_SESSION['email'] = $resemail;
$_SESSION['username'] = $resusername;
$_SESSION['logadmin'] = $admin;
header("location:navigra.php");
}else{
// No, Lets mark them as invalid.
$_SESSION['loggedin'] = "0";
echo "Sorry, Invalid details.<br>";
die ('klik hier om opnieuw te proberen.');
}
?>
</body>
</html>
EDIT :
-added check on username in sql query (as suggested by Jason)
-added addslashes for basic protection against SQL injection.