How would I make this work, I asked before and didn't get a correct answer. This code is the user login, so when they log in I want username and avatar to be trackable through out the site. So far I just have username. I have tried methods and have failed every time.
$username = $_POST['username'];
$password = sha1($_POST['password']);
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
$count=mysqli_num_rows($result);
if ($count == 1)
{
$row = mysqli_fetch_array($result);
while ($_SESSION['username'] = $row['username'])
{
session_start();
header('Location: index.php');
}
}
else
{
echo 'Invalid Logins';
}
mysqli_close($conn);
?>
Supposing you have avatar stored in the avatar field in the database:
if ($count == 1)
{
session_start();
$row = mysqli_fetch_array($result);
$_SESSION['username'] = $row['username'];
$_SESSION['avatar'] = $row['avatar'];
header('Location: index.php');
}
else
{
echo 'Invalid Logins';
}
Related
So im having problem with code in php, it drives me crazy..
The thing is, i am making login page, and i have index.php, login.php and dashboard.php.
Login form is in index.php, in login.php it checks if user is in database, and if it is redirect user to dashboard.php, but when i type right user and pass, it redirects me to index.php instead of dashboard.php??
login.php
<?php
session_start();
include($_SERVER['DOCUMENT_ROOT'] . "/new_cms/includes/db.php");
$username = $_POST['username'];
$password = $_POST['password'];
$btn = $_POST['submit'];
if(isset($btn)){
if(empty($username) || empty($password)){
echo "You must fill all fields";
}else{
$sql = "SELECT * FROM admins WHERE username = '$username' AND password = '$password'";
$query = mysqli_query($dbconn, $sql);
$rows = mysqli_num_rows($query);
if($rows > 0){
$_SESSION['usr'] = $rows['password'];
header("Location: dashboard.php");
}else{
echo "Invalid login";
}
}
}
?>
dashboad.php
<?php
session_start();
include($_SERVER["DOCUMENT_ROOT"] . "/new_cms/includes/db.php");
include($_SERVER["DOCUMENT_ROOT"] . "/new_cms/admin/login.php");
if(!isset($_SESSION['usr'])){
header("Location: index.php");
}else{
echo "Welcome";
}
?>
What am i doing wrong?
$rows is just a number, not an array, since you used mysqli_num_rows. Still you try to get $rows['password'].
instead, fetch the first row of the result and use this to assign to the session variable.
if(isset($btn)){
if(empty($username) || empty($password)){
echo "You must fill all fields";
}else{
$sql = "SELECT * FROM admins WHERE username = '$username' AND password = '$password'";
$query = mysqli_query($dbconn, $sql);
$rows = mysqli_num_rows($query);
if($rows > 0){
$user = mysqli_fetch_assoc($query);
$_SESSION['usr'] = $user['password'];
header("Location: dashboard.php");
}else{
echo "Invalid login";
}
}
}
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';
}
?>
Well I am trying to create kind of a social network but there is a problem with my session. So I am not able to visit other users profile. This is my code for loginwebsite1.php
<?php
ob_start();
session_start();
$connection = mysqli_connect('localhost', 'root', '123456789', 'register');
if (isset($_POST['email1'])) {
$email = mysqli_real_escape_string($connection, htmlentities($_POST['email1']));
}
if (isset($_POST['password1'])) {
$password = mysqli_real_escape_string($connection, htmlentities($_POST['password1']));
}
if (!empty($email) && !empty($password)) {
$query = "select id from register where email='$email' and password='$password'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if ($row > 0) {
$_SESSION['id'] = $row;
$_GET['id'] = $row;
header('location: new.php');
} else {
echo "sorry but the email-id or password is wrong";
}
} else {
echo "please enter your email-id or password or there";
}
?>
My session code goes like this:
<?php
ob_start();
session_start();
if (isset($_SESSION['id']) && !empty($_SESSION['id'])) {
$id = $_SESSION['id'];
foreach ($id as $fn)
$connection = mysqli_connect('localhost', 'id', 'password', 'register');
$query = "select firstname,lastname from register where id='$fn'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
} else {
header('location: loginwebsite1.php');
}
?>
But when I try to enter like profile.php?id=9 it still opens the profile of the user who is logged in.
$id=$_SESSION['id'];
This line is where you problem is I believe. Here you get the ID number for the profile page to load from the $_SESSION variable when you should be getting it from the $_GET variable.
It should read:
$id=$_GET['id'];
you should also check if the $_GET['id'] is also set like this
$connection=mysqli_connect('localhost','id','password','register');
if(isset($_SESSION['id']) && !empty($_SESSION['id']) || !empty($_GET['id']))
{
$id=!empty($_GET['id'])? $_GET['id']: $_SESSION['id'];
foreach($id as $fn){
$query="select firstname,lastname from register where id='$fn'";
$result=mysqli_query($connection,$query);
$row=mysqli_fetch_array($result);
$firstname=$row['firstname'];
$lastname=$row['lastname'];
}
}else{
header('location: loginwebsite1.php');
}
also set your $connection variable to connect only once to your database.
I have the PHP code as below:
<?php
if(isset($_POST["tbn_submit"])){
$userName = $_POST["text_username"];
$pass = $_POST["text_password"];
//$sql = "SELECT * FROM tbluser WHERE username='".$userName."' AND password='".$pass."'";
$sql = "SELECT * FROM tbluser";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res)>0){
while($row= mysql_fetch_array($res)){
$username=$row['username'];
$userpas = $row['password'];
$user_id=$row['userId'];
$user_role=$row['possition'];
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if($userName == $username && $pass == $userpas){
if($user_role=="Admin"){
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}else{
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else if($userName == $username && $pass != $userpas){
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
else if($userName != $username && $pass != $userpas){
//In this point I got insert multi time so I want it insert only 1 time to database
$query = "INSERT INTO tbluser(userId,username,password,possition,user_status) VALUES('','".$userName."','".$pass."','',1)";
$result = mysql_query($query) or die(mysql_error());
$id = mysql_insert_id();
if($result){
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
}
}else {
echo "re";
}
}
?>
This is my login page submission. When the user inputs their username and password, if the username and password are already in the database it will go to test some case like in code, but if the username is in the database but the password does not match it should display wrong password..
If the username and password don't exist in the database, the program should create username and password and go to other page. I have an error with this last case - I have inserted a lot of records in the database with the same data. I know it's because I wrote these entries in a while loop in my code but I don't know any other way of doing this. How can I populate my database with individual records and not write duplicate entries in my while loop?
All your logic is wrong:
there's no need to retrieve ALL the users to check if the user exists,
tbluser should restrict username to be UNIQUE to avoid duplicated entries,
passwords should be hashed,
the INSERT query uses unescaped variables,
inserting non matching user names will lead to have typos stored at the db,
mysql_* family of functions are deprecated
Using PDO
Login user
<?php
$dbh = new PDO('mysql:host=localhost;dbname=some_database_name', $user, $pass);
if (isset($_POST["login"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
$statement = $dbh->prepare("SELECT * FROM tbluser WHERE username=:user");
$statement->bindParam(':user',$user);
$statement->execute();
/**
* Returns FALSE in case nothing is found
*/
$res = $statement->fetch(PDO::FETCH_ASSOC);
if ($res) {
$username = $res['username'];
$password = $res['password'];
$user_id = $res['userId'];
$user_role = $res['possition'];
if ($pass == $password) {
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if ($user_role == "Admin") {
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}
else {
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong username.</span>";
}
}
Register user
<?php
$dbh = new PDO('mysql:host=localhost;dbname=some_database_name', $user, $pass);
if (isset($_POST["register"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
$check = $_POST["passcheck"];
$statement = $dbh->prepare("SELECT * FROM tbluser WHERE username=:user");
$statement->bindParam(':user',$user);
$statement->execute();
/**
* Returns FALSE in case nothing is found
*/
$res = $statement->fetch(PDO::FETCH_ASSOC);
if ($res) {
echo "<span style='text-align:center;color:red;'>Username exists.</span>";
}
else if ($pass != $check) {
echo "<span style='text-align:center;color:red;'>Password check doesn't match.</span>";
}
else {
$statement = $dbh->prepare("INSERT INTO tbluser (userId, username, password, position, user_status) VALUES ('', :user, :pass, '' , 1)");
$statement->bindParam(':user',$user);
$statement->bindParam(':pass',$pass);
$statement->execute();
echo "<span style='text-align:center;color:red;'>Username registered.</span>";
}
}
Using mysql_query (deprecated)
To validate any user:
<?php
if (isset($_POST["login"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
/**
* This line had the right idea!
*/
$sql = "SELECT * FROM tbluser WHERE username='".mysql_real_escape_string($user)."'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
$username = $row['username'];
$password = $row['password'];
$user_id = $row['userId'];
$user_role = $row['possition'];
if ($pass == $password) {
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if ($user_role == "Admin") {
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}
else {
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong username.</span>";
}
}
To register some user:
<?php
if (isset($_POST["register"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
/**
* Ask the user to type its password twice
*/
$check = $_POST["passcheck"];
$sql = "SELECT * FROM tbluser WHERE username='".mysql_real_escape_string($user)."'";
$res = mysql_query($sql) or die('The application found a problem and cannot process your request'); // die(mysql_error());
if (mysql_num_rows($res) > 0) {
echo "<span style='text-align:center;color:red;'>Username exists.</span>";
}
else if ($pass != $check) {
echo "<span style='text-align:center;color:red;'>Password check doesn't match.</span>";
}
else {
$query = "INSERT INTO tbluser (userId, username, password, possition, user_status) VALUES ('','".mysql_real_escape_string($user)."','".mysql_real_escape_string($pass)."','',1)";
$res = mysql_query($sql) or die('The application found a problem and cannot process your request'); // die(mysql_error());
echo "<span style='text-align:center;color:red;'>Username registered.</span>";
}
}
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;