Requesting Username & Password In PHP Session - php

i tried to put username & password dynamically but
It doesnt work with stored username & password in DB and stays on same page....
really depressed.
<?php include "../db/db_connection.php";
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
if($_REQUEST['txt_username'] == $username && $_REQUEST['txt_pwd'] == $pwd){
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
header("Location:dashboard.php");
}
else{
header("Location:index.php");
}
?>`

Those lines doesn't nothing..
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
maybe:
$_SESSION['txt_username'] = $user;
$_SESSION['txt_pwd'] = ...;
?

You can try this, I am not sure if this is exactly what you are looking for...
<?php session_start();
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
header("Location:index.php"); // if it stays on the same page remove this line
?>

I restructured your code to look more clean.
Also I suggest you to avoid using mysql and start using mysqli (or PDO) to avoid SQL injection attacks.
<?php session_start();
if(isset($_SESSION['txt_username']) && !empty($_SESSION['txt_username'])) {
//If we enter here the user has already logged in
header("Location:dashboard.php");
exit;
}
if(!isset($_POST['txt_username'])) {
header("location:index.php?err_msg=1");
exit;
}
else if(!isset($_POST["txt_pwd"])) {
header("location:index.php?err_msg=2");
exit;
}
$username = $_POST['txt_username'];
$pwd = $_POST["txt_pwd"];
//We use MYSQL with prepared statements BECAUSE MYSQL IS DEPRECATED
$mysqli = new mysqli('localhost', 'my_bd_user', 'mi_bd_password', 'my_bd');
$sql = "SELECT 1 FROM users WHERE username= ? and password = ?";
$stmt = $mysql->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
if(!empty($result)) {
//IF we enter here user exists with that username and password
$_SESSION['txt_username'] = $username;
header("location:dashboard.php");
exit;
}
else{
header("location:index.php?err_msg=3");
}
Try it.

I checked your code and found everything is correct .I wold like you to add connection file on this.
Like
$username = "root";
$password = "password";//your db password
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("db name",$dbhandle)
or die("Could not select Database");
Thanks

Try below code :
i have reviewed and changed your code :
<?php session_start();
mysqli_connect("locahost","username","password");
mysqli_select_db("database_name");
$username = trim($_POST['txt_username']);
$pwd = trim($_POST["txt_pwd"]);
if($username == ''){
header("location:index.php?err_msg=1");
exit;
}
if($pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT `username`,`password` FROM users WHERE `username`= '".$username."' and password= '".$pwd."'";
$result = mysqli_query($sql);
if(mysqli_num_rows($result)>0){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
?>

Related

Can't fetch data from MySQL (php) (Re-edited)

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.

Login not working very well

I trying to get work my new login system, I made a simple password with and put hashed pass to my MySQL table with the next code
makepass.php
<?php
$password = "testpass";
$hash = password_hash($password, PASSWORD_DEFAULT);
echo $hash;
?>
dologin.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('includes/functions.php');
session_start();
if(isset($_POST['login'])) {
if(isset($_POST['username'])) {
if(isset($_POST['password'])) {
$username = $_POST['username'];
$dbconn = mysqli_query($query, "SELECT * FROM cm_users WHERE Username = '$username'") or die(mysqli_error($query));
foreach ($dbconn as $user) {
if (password_verify($_POST['password'], $user['Password'])) {
$_SESSION['user'] = $user['Username'];
} else {
echo 'Invalid password!';
}
}
} else {
echo 'Invalid username!';
}
}
}
?>
So i tried to login with "testpass" and whoala: invalid password!
Any idea? Afaik its should be okay, i dont see any syntax or other problem.
You shouldn't be a foreach for this, but first to query, fetch the array (which you're not using) and then comparing that to the row's password.
Sidenote: Replace the ("xxx", "xxx", "xxx", "xxx") with your own credentials. However, using $query isn't a word you should use as a connection variable, because it is quite confusing.
(Even I was confused when writing my answer). Use $connection or $conn and I have changed them here, so please use that instead.
$conn = new mysqli("xxx", "xxx", "xxx", "xxx");
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
if(isset($_POST['login'])) {
$username = $_POST['username']; // you could use a conditional !empty() here
$password = $_POST['password']; // here also
$query = "SELECT * FROM cm_users WHERE Username = '".$conn->real_escape_string($username)."';";
$result = $conn->query($query);
// error checking on the query
if (!$result) {
echo "<p>There was an error in query: $query</p>";
echo $conn->error;
}
$row_hash = $result->fetch_array();
if (password_verify($password, $row_hash['Password'])) {
echo "Welcome!";
}
else{
echo "Invalid";
}
}
You can then add the other goodies after, once you've had success.
Sidenote: Make absolutely sure that your POST arrays do hold values and contain no whitespaces. If there are, use trim().
I.e.:
$username = trim($_POST['username']);
$password = trim($_POST['password']);
Check for errors on your query also:
http://php.net/manual/en/mysqli.error.php
And error reporting:
http://php.net/manual/en/function.error-reporting.php
$dbconn = mysqli_query($query, "SELECT * FROM cm_users WHERE Username = '$username'") or die(mysqli_error($query));
should look more like
$userQuery = mysqli_query($variableToConnectToDatabase, "SELECT * FROM cm_users WHERE Username = '$username' AND Password='$password' LIMIT 1 ")
Not sure what your main goal is. Did you want the user to be able to put in their own password, or is the password supposed to be constant?
Try Edit dologin.php to this.....
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('includes/functions.php');
if(isset($_POST['login'])) {
if(isset($_POST['username'])) {
if(isset($_POST['password'])) {
$username = $_POST['username'];
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
$dbconn = mysqli_query($query, "SELECT * FROM cm_users WHERE Username = '$username'") or die(mysqli_error($query));
foreach ($dbconn as $user) {
if ($hash == $user['Password']) {
$_SESSION['user'] = $user['Username'];
} else {
echo 'Invalid password!';
}
}
} else {
echo 'Invalid username!';
}
}
}
?>

How i connect my login.php like my register.php?

I have just connected my register.php to mysql database. and i try connect my login.php but i cant.
this is my connected register.php
$connect = mysqli_connect("mysql13.000webhost.com","a2955851_SW","********");
if(isset($_POST['submit']))
{
$username = mysqli_real_escape_string($connect, $_POST['username']);
$pass = mysqli_real_escape_string($connect, $_POST['pass']);
$pass1 = mysqli_real_escape_string($connect, $_POST['pass1']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
if($username && $pass && $pass1 && $email)
{
if($pass==$pass1)
{
mysqli_select_db($connect, "a2955851_SW");
$query = mysqli_query($connect, "INSERT INTO users VALUES('$username','$pass','$email');");
echo "You have been registered.";
}
else
{
echo "Password must match.";
}
}
else
{
echo "All fields are required.";
}
}
and this is login.php i tryed connect this but...
<?php
$connect = mysqli_connect("mysql13.000webhost.com","a2955851_SW","********");
session_start();
if(isset($_POST['login']))
{
$username = mysqli_real_escape_string($connect, $_POST['username']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
if($username && $password)
{
mysqli_select_db($connect, "a2955851_SW");
$login = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($log=mysqli_fetch_assoc($login))
{
$dbusername = $log['username'];
$dbpassword = $log['password'];
}
if($username==$dbusername && $password==$dbpassword)
{
$_SESSION['username'] = $dbusername;
$_SESSION['password'] = $dbpassword;
header("location:members.php");
}
else
{
header("location:index.php?notify=Incorrect Username or Password.");
}
}
else
{
header("location:index.php?notify=ALL field are required.");
}
}
?>
i tried connect login.php similarly I do not know
You have mixed mysql & mysqli. Use only one. Change
$login = mysql_query("SELECT * FROM users WHERE username = '$username'");
to
$login = mysqli_query($connect, "SELECT * FROM users WHERE username = '$username'");
I am not really sure but try changing the following line:
$password = mysqli_real_escape_string($connect, $_POST['password']);
to
$password = $_POST['password'];
this is because at the later part of your script, you will be checking
if($username==$dbusername && $password==$dbpassword)
and if $password is escaped, $dbpassword will not be and the same password might result in a false comparison.
Lets say the actual password is 12"3, $password will be 12\"3 and $dbpassword will be 12"3 if $password is escaped.
The best way is to make a connection file and include in all php file you want to connect to database. So you don't need to check in every page and run your query before just below connection string to make sure its working
$query = mysqli_query($connect, "INSERT INTO users VALUES('$username','$pass','$email');");
echo "You have been registered.";
}

Convert MySQL login script to PDO

I've written a functional login script using MySQL. However, I've now been told that it needs to be done using PDO, and I've a functional PDO connection:
function getConnection()
{
$userName = '*****';
$password = '*****';
$dbname = '******';
$db = new PDO("mysql:host=localhost;dbname=$dbname", $userName, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
However I've no idea how to convert the login query to PDO.
if (isset($_REQUEST['attempt']))
{
$user = $_POST['user'];
$password = $_POST['password'];
$qry = mysql_query
("SELECT *
FROM subscriber
WHERE email = '$user'
AND password = '$password'")
or die(mysql_error());
$total = mysql_num_rows($qry);
if ($total > 0)
{
session_start();
$_SESSION['user'] = 'yes';
header('location: account.php');
exit;
}
else
{
// Do nothing.
}
}
How can I do it?
To get you started:
$db = getConnection();
$stmt = $db->prepare("
SELECT * FROM subscriber WHERE email = :email AND password = :password
");
$stmt->bindParam(":email" , $user );
$stmt->bindParam(":password", $password);
$stmt->execute();
$total = $stmt->rowCount();
Non-bloated version:
$stm = $pdo->prepare("SELECT * FROM subscriber WHERE email = ? AND password = ?");
$stm-> execute($_POST['user'], $_POST['password']);
if ($id = $stm->fetchColumn()) {
session_start();
$_SESSION['user'] = $id;
header('location: account.php');
exit;
}
You can also use this example if you would not like to use bindParam. But I extracted it from #eggyal's answer. Great thanks go to eggyal.
<?php session_start();
include_once('pdo.inc.php');
$username = (isset($_POST['username']))? trim($_POST['username']): '';
$password = (isset($_POST['password']))? $_POST['password'] : '';
$pas = md5($password);
$redirect = (isset($_REQUEST['redirect']))? $_REQUEST['redirect'] :
'view.php';
$query = ("SELECT username FROM site_user WHERE username=:username
AND password =:password");
$query_login = $con->prepare($query);
$query_login->execute(array(
':username'=>$username,
':password'=>$pas));
$result = $query_login->rowCount();
if($result>0)
{
$_SESSION['username'] = $username;
$_SESSION['logged'] = 1;
echo "success";
}
else {
// Set these explicitly just to make sure
echo 'User name invalid';
}
?>

Trouble making login page?

Okay, so I want to make a simple login page. I've created a register page successfully, but i can't get the login thing down.
login.php:
<?php
session_start();
include("mainmenu.php");
$usrname = mysql_real_escape_string($_POST['usrname']);
$password = md5($_POST['password']);
$con = mysql_connect("localhost", "root", "g00dfor#boy");
if(!$con){
die(mysql_error());
}
mysql_select_db("users", $con) or die(mysql_error());
$login = "SELECT * FROM `users` WHERE (usrname = '$usrname' AND password = '$password')";
$result = mysql_query($login);
if(mysql_num_rows($result) == 1 {
$_SESSION = true;
header('Location: indexlogin.php');
}
else {
echo = "Wrong username or password." ;
}
?>
indexlogin.php just echoes "Login successful." What am I doing wrong?
Oh, and just FYI- my database is "users" and my table is "data".
<?php
session_start();
include("mainmenu.php");
$usrname = mysql_real_escape_string($_POST['usrname']);
$password = md5($_POST['password']);
$con = mysql_connect("localhost", "root", "g00dfor#boy");
if (!$con) {
die(mysql_error());
}
mysql_select_db("users", $con) or die(mysql_error());
$login = "SELECT * FROM `users` WHERE (usrname = '$usrname' AND password = '$password')";
$result = mysql_query($login);
if (mysql_num_rows($result) == 1) {
$_SESSION['logged_in'] = true;
header('Location: indexlogin.php');
exit;
} else {
echo "Wrong username or password.";
}
?>
I added mysql_real_escape_string() to prevent SQL injection.
No, I didn't because you already had it.
I cleaned up the formatting of the code a bit.
I changed $_SESSION = true; (which doesn't make sense) into $_SESSION['logged_in'] = true;. Then, in indexlogin.php you can do something like if ($_SESSION['logged_in']) { echo $secret; }
I fixed echo = "Wrong username or password."; to echo "Wrong username or password.";
I added a closing bracket near mysql_num_rows($result) == 1.
You said:
my database is "users" and my table is
"data".
If this is correct, you will need to change SELECT * FROM users to SELECT * FROM data.
I don't think you can set $_SESSION = true, because $_SESSION is an array. Try $_SESSION['logged_in'] = true.

Categories