PHP Login not registering data in database - php

<?php
$userid = $_POST["userid"];
$pword = $_POST["pword"];
# session
session_start();
# check that session is valid and set
if(!isset($_SESSION['login']))
{
header('Location: login.php');
}
# check that the required values have been entered
$testin1 = ($userid);
$testin2 = ($pword);
if($testin1 == "")
{
print "<hr><h1> No Username Entered, Please return to the Login page</h1></hr>";
}
elseif ($testin2 == "")
{
print "<hr><h1> No Password Entered, Please return to the Login page</h1></hr>";
}
# Connect to database
$connect = mysql_connect ("localhost","root") or die("Error Connecting to SQLServer");
$db = mysql_select_db ("test");
# query
$query = mysql_query ("select username from login where username = '$userid' and pword = '$pword';");
if($query === FALSE)
{
die(mysql_error());
}
$result = mysql_fetch_array($query);
$record = $result['username'] ;
if ($record != null)
# check if session is operational, if so redirect the user to the correct page
{
$_SESSION['login'] = true;
header( 'Location: index.php' ) ;
}
else if ($record == null)
{
header( 'Location: login.php' );
}
?>
Does anyone know where this is not functioning? It seems to be 'error free' however keeps redirecting me back to the login.php page as opposed to the index.php page. any help would be great as i am a relative novice in PHP.
Thanks

You are using mysql_fetch_array(). In order to access a result by the key you need to use mysql_fetch_assoc().
$result = mysql_fetch_assoc($query);
$record = $result['username'] ;
Keep in mind that it is always best to escape any user input with mysql_real_escape_string().

It looks like you might possible be outputting data to the user before the header() is output. You have <HR>s and output (I know that it is only if there is an error) but if you are using those, you could well have <HTML> and the like above the code.
If that is the case, then no other header will function.
(Posting as answer as too long for comment - and might be the issue.
Try this code:
<?php
session_start();
$userid = $_POST["userid"];
$pword = $_POST["pword"];
// check that the required values have been entered
$testin1 = ($userid);
$testin2 = ($pword);
if($testin1 == "")
{
print "<hr><h1> No Username Entered, Please return to the Login page</h1></hr>";
}
if ($testin2 == "")
{
print "<hr><h1> No Password Entered, Please return to the Login page</h1></hr>";
}
// Connect to database
$connect = mysql_connect ("localhost","root") or die("Error Connecting to SQLServer");
$db = mysql_select_db ("test");
// query
$query = mysql_query ("select username from login where username = '$userid' and pword = '$pword';");
if($query === FALSE)
{
die(mysql_error());
}
$result = mysql_fetch_array($query);
$record = $result['username'] ;
if ($record != null)
// check if session is operational, if so redirect the user to the correct page
{
$_SESSION['login'] = true;
header( 'Location: index.php' ) ;
}
else if ($record == null)
{
header( 'Location: login.php' );
}
?>
I looked through and moved a few things around as well as modifying the logic ever so slightly.

The problem seems to be in your session, check $_SESSION['login'] whether it is set or not, because you are checking if !isset() then you are redirecting to login.php page.
Just verify the session variable by debugging your code

Related

Multi level user login and session

I have a problem with multi-level user login in PHP MySQL. I already have a code but the user still can access the admin site, what's the problem with my code? still, I do have a problem with the session of admin and user acct. thank you! here's my code.
require('db.php');
session_start();
if (isset($_POST['username'])){
$account = stripslashes($_REQUEST['account']);
$account = mysqli_real_escape_string($con,$account);
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($con,$username); //escapes special
characters in a string
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM users_detail WHERE account = '$account',username=
'$username' and password= '$password' ";
$result = mysqli_query($con,$query);
$rows = mysqli_num_rows($result);
if($account == "admin" && $rows['username'] = $username &&
$rows['password']=$password){
$_SESSION['username'] = $username;
header("Location: index.php"); // Redirect user to index.php
}
if($account == "user" && $rows['username'] = $username &&
$rows['password']=$password){
$_SESSION['username'] = $username;
header("Location: add user.php"); // Redirect user to index.php
}else{
echo " <div class='alert'>
Username/password is incorrect. Click <a href = 'login.php'>here</a> to log-in.
</div> ";
}
}else{
?>`
here is the full solution,
1 , in your user table you need to create a column call user_role
every user in the table either admin or normal_user
2 in your log.php , first fetch data base get the user_role value , when you verify user password and db password , save as session .
<?php
if( isset($_POST['login_btn'])){ // someone click login btn
$username = clean($_POST['username']);
//clean is the custom function to remove all harmful code
$password = clean($_POST['password']);
// run query to get db username & password i am using prepare stmt for more secure , you can use mysqli_fetch_array , but need to implement mysql_real_escape_string for sql injection
$stmt = mysqli_prepare($connection,"SELECT username,password,email,user_role FROM your table WHERE username = ? ");
//$connection is your db connection
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $bind_username,$bind_password,$bind_email,$bind_user_role);
confirm($stmt); // confirm is also custom function to check query is successful execute
while (mysqli_stmt_fetch($stmt)) {
$db_username = $bind_username;;
$db_password = $bind_password ;
$db_email = $bind_email ;
$user_role = $bind_user_role ;
}
// do form validation
if($username =="" or $password =="" ){
echo 'All Fileds Are Required';
}elseif( $username !== $db_username ){
echo 'username not existed';
}else{
if( password_verify($password, $db_password)){
// assuming your using password_hash function to verify , or you can just use simply compare $password == db_password
// if password_verify return true meaning correct password then save all necessary sessions
$_SESSION['username'] = $db_username ;
$_SESSION['user_email'] = $db_email ;
$_SESSION['user_role'] = $user_role ;
// first method -> header('Location: portal.php');
// you can now direct to portal page{1st method } where all admin or normal user can view
// or you can now do separate redirection (2nd method below )
// remember $user_role will == 'admin' or 'normal_user'
if( $user_role == 'admin' ){
header('Location: page_admin_will_view.php');
}elseif( $user_role == 'normal_user' ){
header('Location: page_normal_user_will_view.php');
}
}else{
echo 'incorrect password';
}
}
} // end of post request
?>
3 how about normal user accidentally visit the admin page ?
we have consider this and do some extra work
put below code in the page_admin_will_view.php header
<?php
if( isset($_SESSION['user_role'] )){
// meaning user is logged in
if( $_SESSION['user_role'] !== 'admin'){
// meaning user_role is not amind , redirect to the page normal user belongs to
header("Location: ../normal_users.php");
}
} else{
//redirect to somewhere meaning user is not logged in
header("Location: ../somewhere.php");
}
?>
I hope this would help you , and I am using it, it may not be a perfect solution. but it works for me. hah
mysqli_num_rows($result) returns the number of rows.
So after $result = mysqli_query($con,$query); you need to write fetch data using mysqli_fetch_array($query)
What you are talking about is RBAC(Role Base Access Control).
if($account == "admin" && $rows['username'] = $username && $rows['password']=$password){
$_SESSION['username'] = $username;
$_SESSION['access'] = $account;
}
And on your pages where you want admin access, probably you should either redirect the user to home or send an UnAuthorised access message.
if(isset($_SESSION['access']) && $_SESSION['access'] != 'admin') {
header("Location: index.php");
}
Also if you are looking for more controlling based on the role I will suggest you to use a library like
http://phprbac.net/
first of all , create admin role like you did with $account
when user login save their admin_role in session ,
$admin_user = $_SESSION['admin_user'] ;
$normal_user = $_SESSION['normal_user'] ;
in admin site , like admin.php , the page you do not want normal user view
write this {perfectly write it in header.php}
if(isset($_SESSION['username'])){
//meaning user is logged in
if(isset($_SESSION['admin_user']) or isset($_SESSION['normal_user'])){
if( $_SESSION['admin_user'] !== 'admin_user' ){
header('Location: somewhere.php');
}
}
}else{
//meaning user is not logged or session had terminated
header('Location: index.php');
}
Seems like you're trying to implement role-based access control on your website.
Here is a possible implementation using prepared statements:
<?php
// db.php should create a mysqli insance:
// $con = new mysqli("host", "username", "password", "databaseName");
require('db.php');
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
//Checking is user existing in the database or not
$query = "SELECT * FROM users_detail WHERE username = ? and password = ?";
//use prepared statement
$stmt = $con->prepare($query);
$stmt->bind_param('ss', $_POST['username'], $_POST['password']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows !== 0) {
//fetch user from database.
$user = $result->fetch_assoc();
//check if user is an admin.
if($user['account'] === "admin") {
$_SESSION['username'] = $username;
header("Location: admin.php"); //admin's page
}
//check if user is a normal user.
if($user['account'] === "user") {
$_SESSION['username'] = $username;
header("Location: user.php"); //user's page
}
} else {
echo '<div class="alert">Username/password is incorrect. Click here to log-in.</div>';
}
//free memory used by the prepared statement.
$stmt->close();
} else {
//username and password not provided.
}
?>

.php file security using MAMP

I have generated a php file that has information stored in a database. To access this a person must use a login in page.
However, when you are using MAMP how can you prevent someone from accessing the file through writing the IP address and php file name e.g. 123.456.78.00:80/fileone.php. I want this fileone.php to be hidden and for them to only access it through a login page.
Thanks in advance.
<?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
mysql_connect("localhost", "root","root") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("SELECT * from users WHERE username='$username'"); //Query the users table if there are matching rows equal to $username
$exists = mysql_num_rows($query); //Checks if username exists
$table_users = "";
$table_password = "";
if($exists > 0) //IF there are no returning rows or no existing username
{
while($row = mysql_fetch_assoc($query)) //display all rows from query
{
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
$table_password = $row['password']; // the first password row is passed on to $table_users, and so on until the query is finished
$table_id = $row['id'];
$page_id = $row['page'];
}
if(($username == $table_users) && ($password == $table_password)) // checks if there are any matching fields
{
if($password == $table_password)
{
$_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
//echo $table_id;
//echo $page_id;
redirect ($page_id); //take the user to the page specified in the users table
}
else
{
echo "Login Failed";
}
}
else
{
Print '<script>alert("1. Incorrect Password!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
}
else
{
Print '<script>alert("Incorrect Username!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
function redirect($page_id)
{
/* Redirect browser */
header('Location: ' . $page_id);
/* Make sure that code below does not get executed when we redirect. */
exit;
}
?>
Login check
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true) {
"Your script"
}
If you have a profile for your users, like a normal user = 0 and an admin = 1 you can do it like this
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true && $_SESSION['profile'] == 1) {
"Your script"
}
Set sessions
To set set the sessions to true you need this
if(isset($_POST['submit'])) {
$_SESSION['loggedIn'] = true;
// for set a profile
$_SESSION['profile'] = 1;
}
Maybe I didn't understand you good, but to be sure I will explain something:
You said attached checklogin.php, but you can't use that to deny access for non members. If they know that the file exists, they can type it in the URL and still read fileone.php. The first coding block need to be in your fileone.php.
Session time
Search in your php.ini for 'session.gc_maxlifetime'. There will be a number and that is the time in seconds.

Can't fetch data from mysql_fetch_array() in PHP

Here is my PHP: (that code does it's job well)
if(isset($_COOKIE["user"])) {
$username = $_COOKIE["user"];
$pass = $_COOKIE["password"];
$check = mysql_query("SELECT * FROM members WHERE email = '$username'")or die(mysql_error());
while ($info = mysql_fetch_array( $check ))
{
//if the cookie is present but has the wrong password, they are taken to the login page
if ($pass != $info['password'])
{
header("Location: login.php");
exit();
}
else //if the cookie is present and doesn'T have the wrong password they are shown the admin area
{
include 'header.php';
}
}
}
else //if the cookie is present and doesn'T have the wrong password they are shown the admin area
{
header("Location: login.php");
exit();
}
but later on the same page, I try to access data from the $info variable and nothing comes out. I know i'm doing something wrong, but can't figure out what...
<?php print $info['name']?>
If I make my variable global, how do I use it the while ?
$check = mysql_query("SELECT * FROM members WHERE email = '$username'")or die(mysql_error());
$info = mysql_fetch_array( $check );
while ($info.....???)
{
}
When you do:
while ($info = mysql_fetch_array( $check ))
{
//
// do things with info:
//...
//
}
The last $info is false (no more record), when it reaches beyond the last record. So $info is false, the while loop terminates, there is no more database "info" in it.
As a workaround, we save the first $info in $info0,
$info0 = false;
while ($info = mysql_fetch_array( $check ))
{
if(! $info0)
{
$info0 = $info;
}
//
// do things with info:
//...
//
}
you use $info0 instead of $info after the while loop.
<?php echo $info0['name']; ?>
The $info variable is localized to the if statement.
Make the $info variable global.
After the while loop, use the mysql_data_seek function:
$info = mysql_data_seek($check, 0) ? mysql_fetch_array($check) : null;
Of course, you MUST avoid to use all PHP functions that begin with mysql_.
if you want use $info in if(isset($_COOKIE["user"])) { is okay but if you want to use $info outside if(isset($_COOKIE["user"])) { there will be a problem becaause $info not initialization before if(isset($_COOKIE["user"])) { so your code will be like this
$username = $_COOKIE["user"];
$pass = $_COOKIE["password"];
if(isset($_COOKIE["user"])) {
$check = mysql_query("SELECT * FROM members WHERE email = '$username'")or die(mysql_error());
while ($info = mysql_fetch_array( $check ))
{
//if the cookie is present but has the wrong password, they are taken to the login page
if ($pass != $info['password'])
{
header("Location: login.php");
exit();
}
else //if the cookie is present and doesn'T have the wrong password they are shown the admin area
{
include 'header.php';
}
}
}
else //if the cookie is present and doesn'T have the wrong password they are shown the admin area
{
header("Location: login.php");
exit();
}
$check = mysql_query("SELECT * FROM members WHERE email = '$username'")or die(mysql_error());
$info = mysql_fetch_array( $check );

Problem with blank submitted values and returned mysql query

<?php
$link = mysql_connect('127.0.0.1', 'ilhan', 'password123');
if(!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("metu", $link);
mysql_set_charset('utf8',$link);
if(isset($_POST["email"])) // AND strlen($_POST["email"])>1 solves the problem
// but I didn't get why the page is redirected...
{
$email = mysql_real_escape_string($_POST["email"]);
$password = mysql_real_escape_string($_POST["password"]);
$result = mysql_query("SELECT password, id FROM users WHERE email = '$email'");
if (!$result)
{
die('Invalid query: ' . mysql_error());
}
$row = mysql_fetch_assoc($result);
if($row['password'] == $password)
{
$_SESSION['valid_user'] = $row['id'];
mysql_close($link);
header("Location: http://www.example.com");
}
else $login = false;
mysql_close($link);
}
else $login = false;
?>
Do you think that the page will be redirected if the user submits a blank email and blank password? It shouldn't but the page is redirected. Why is that? Bug?
I've overlooked the issue at first.
here it is:
if($row['password'] == $password)
empty $row['password'] is equal to empty $password. evaluated to true
here is what I'd do it
<?php
include 'db.php';
if(isset($_POST["email"]))
{
$sql = "SELECT id FROM users WHERE email='%s' AND password='%s'";
$id = dbGetOne($sql,$_POST["email"],MD5($_POST["email"].$_POST["password"]));
if($id)
{
$_SESSION['valid_user'] = $row['id'];
header("Location: http://www.example.com");
exit;
}
}
Use mysql_num_rows function to find then umber of rows returned. mysql_query will return FALSE on error but in your case, your SQL is still a valid SQL if email is blank. It will just return an empty result set.
if(isset($_POST["email"]))
// AND strlen($_POST["email"])>1 solves the problem
// but I didn't get why the page is redirected...
if $_POST["email"] is empty string -> isset will return true
EDIT: add if ( isset($_POST["email"]) && isset ($_POST["password"]) ) to avoid empty passwords and make sure that $row is not empty when `if($row['password'] == $password)'

PHP MYSQL question

I am trying to do a simple login with PHP and mysql, and using Sessions as well. I have the code, which should work in theory, however it keeps redirecting me to the login page (refreshing it) instead of taking me to the profile.
$username = $_POST['username'];
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1){
$result2 = mysql_query($query);
$row = mysql_fetch_row($result2);
$_SESSION['conf_code'] = $row[0];
$uid = $row[0];
session_register($uid);
header('location:profile.php?conf='.$row[0]);
}
else{
echo 'Wrong username';
}
no it shouldn't work in theory
try this
<?php
$username = mysql_real_escape_string($_POST['username']);
$query = "SELECT `confirmcode` FROM `fb_network`
WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if ($row = mysql_fetch_row($result)){
session_start();
$_SESSION['conf_code'] = $row[0];
header('Location: profile.php');
exit;
} else {
echo 'Wrong username';
}
but there can be other issues, from code you didn't post here r other reasons.
as a matter of fact, only debugging can tell you what's the problem for sure
I would use a user defined function and make it to check the login credentials and return true or false from the function.
you can use something like this.
function check_login ($username, $password) {
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if( mysql_num_rows($result) == 0) {
return false;
}
if( mysql_num_rows($result) == 1) {
$_SESSION['loggedin'] = "true";
header('location:profile.php?conf='.$row[0]);
return true;
}
}
and then call the function easily and display the appropriate message.
check the following code..
<?php
session_start();
/** If the User is already Logged in then redirect to login.php **/
if(isset($_SESSION['loggedin'])){
header("Location: login.php");
}
else {
if( check_login($_POST['username'], $_POST['password'])) {
header('location:profile.php?conf='.$row[0]);
}
}
althoough the code is not exact but this might be enough to get you going.
I see that your code has only two options - display "wrong code" or redirect to the other page. no place where you are redirecting to the login page?
You need to initiate the session by sessions_start() before the rest of the code.
If you have any sort of 'test' script on the profile page that re-directs you if you're not logged in, it may be that the above code logs you in, but does not carry the session variable correctly to the profile page...and subsequently sends the user back to log in again.
Make sure the session is properly initiated on each page using the variable and make sure they match on both ends.
You have two main problems:
You are not using session_start to tell PHP to start tracking sessions
You are using session_register. session_register requires register_globals to be on, which it hopefully is not in your environment. It also expects its argument to be a string which is the name of the variable you wish to store. You should instead use $_SESSION['uid'] = $row[0];
You should also read about SQL injection, a very serious and common security flaw that your code exhibits.
Here is a corrected version of your code:
<?php
session_start(); //it's fine to just do this by habit at the top of every page
$username = $_POST['username'];
//I added mysql_real_escape_string - please read about "sql injection", as it is a very serious and common problem!
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '".mysql_real_escape_string($username)."' AND `status`='Confirmed' ";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
$result2 = mysql_query($query);
$row = mysql_fetch_row($result2);
$_SESSION['conf_code'] = $row[0];
//not sure if this is what you weree going for or not
$_SESSION['uid'] = $row[0];
header('location:profile.php?conf='.$row[0]);
}
else {
echo 'Wrong username';
}
Then in profile.php, to check if someone is logged in:
<?php
session_start();
if( ! isset($_SESSION['uid']))
//Not logged in!
if( $_SESSION['uid'] != $_GET['conf'])
//trying to access someone else's page!

Categories