I'm stuck in login page. From home,user will login (form send to check_login) and from check_login user will be directed to page based on their role. However, I cannot pass through the login page. I mean I keep getting the error message from header('location: 1.php?error=1');
fyi, i've successfully connected to db. The data is there. But if I echo oci_num_rows, the result is 0..
Here is my code login.php
<form action="check_login.php" method="post" name="login">
<div class="error"><?php include('error-handler.php'); ?></div>
<p> Matric / Staff ID :</p>
<p><input type="text" name="id" size="20" maxlength="10" onkeypress="return isNumberKey(event)" required value=""/></p>
<p>Password :</p>
<p><input type="password" name="password" id="password" size="20" maxlength="8" min="6" required value="" />
<script type="text/javascript">
//add a show password checkbox
new ShowPasswordCheckbox(document.getElementById("password"));
//test the submitted value
document.getElementById('login').onsubmit = function()
{
alert('pword = "' + this.pword.value + '"');
return false;
};
</script>
</p>
<p><input type="submit" name="submit" value="Login"/></p> </form>
and here is my check_login.php
<?php
ob_start();
// Inialize session
session_start();
require_once('connection.php');
//if the login form is submitted
if(isset($_POST['submit']) && !empty($_POST['submit']))
{
$id = $_POST['id'];
$pass = $_POST['password'];
$stmt2= oci_parse($conn, "SELECT * FROM user1 WHERE id = '$id'")or die(oci_error());
$check2 = oci_execute($stmt2);
//Gives error if user dosen't exist
$check3 = oci_num_rows($stmt2);
if ($check3 == 0)
{
header('location: 1.php?error=1'); //the msg will be: you are not eligible user.
exit();
}
else
{
while($info2=oci_fetch_array($stmt2,OCI_ASSOC+OCI_RETURN_NULLS))
{
//gives error if the password is wrong
if ($pass != $info2['password'])
{
header('location: 1.php?error=2'); //password mismatch with id
exit();
}
else
{
// if login is ok then we add a cookie
$_SESSION['id'] = $_POST['id'];
$_SESSION['password'] = $_POST['password'];
$hour = time() + 86400;
setcookie(ID_site, $_SESSION['id'], $hour);
setcookie(Pass_site, $_SESSION['password'], $hour);
//then redirect them to the members area
if ($info2['role']=='admin')
{
header('Location: homeAdmin.php');
}
elseif ($info2['role']=='staff')
{
header('Location: homeStaff.php');
}
elseif ($info2['role']=='student')
{
header('Location: homeStudent.php');
}
else
{
header('Location: 1.php');
}
} //end else
} //end while
}//end else
}// end if submit
else
{
header('Location: 1.php');
}
?>
Please share your opinion or pls correct if i'm wrong. Thank you. :)
From PHP manual 'oci_num_rows' : http://php.net/manual/en/function.oci-num-rows.php
This function does not return number of rows selected! For SELECT
statements this function will return the number of rows, that were
fetched to the buffer with oci_fetch*() functions.
Related
my code is here
<?php
// This section processes submissions from the login form.
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//connect to database
require ('mysqli_connect.php');
// Validate the email address:
if (!empty($_POST['email'])) {
$e = mysqli_real_escape_string($dbcon, $_POST['email']);
} else {
$e = FALSE;
echo '<p class="error">You forgot to enter your email address.</p>';
}
// Validate the password:
if (!empty($_POST['psword'])) {
$p = mysqli_real_escape_string($dbcon, $_POST['psword']);
} else {
$p = FALSE;
echo '<p class="error">You forgot to enter your password.</p>';
}
if ($e && $p){//if no problems
// Retrieve the user_id, first_name and user_level for that email/password combination:
$q = "SELECT user_id, fname, user_level FROM users WHERE (email='$e' AND psword=SHA1('$p'))";
$result = mysqli_query ($dbcon, $q);
// Check the result:
if (#mysqli_num_rows($result) == 1) {//The user input matched the database rcoord
// Start the session, fetch the record and insert the three values in an array
session_start();
//echo '<pre>';
//print_r($_SESSION);
//echo '</pre>';
$_SESSION = mysqli_fetch_array ($result, MYSQLI_ASSOC);
//echo '<br>33333333333333333333333333333333333<br>';
//echo '<pre>';
//print_r($_SESSION);
//echo '</pre>';
$_SESSION['user_level'] = (int) $_SESSION['user_level']; // Changes the 1 or 2 user level to an integer.
$url = ($_SESSION['user_level'] === 1) ? 'admin-page.php' : 'members- page.php'; // Ternary operation to set the URL
header('Location: ' . $url); // Makes the actual page jump. Keep in mind that $url is a relative path.
exit(); // Cancels the rest of the script.
mysqli_free_result($result);
mysqli_close($dbcon);
//ob_end_clean(); // Delete the buffer.
} else { // No match was made.
echo '<p class="error">The email address and password entered do not match our records.<br>Perhaps you need to register, click the Register button on the header menu</p>';
}
} else { // If there was a problem.
echo '<p class="error">Please try again.</p>';
}
mysqli_close($dbcon);
} // End of SUBMIT conditional.
?>
and my form is:
<h2>Login</h2>
<form action="login.php" method="post">
<p><label class="label" for="email">Email Address:</label>
<input id="email" type="text" name="email" size="30" maxlength="60" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" > </p>
<br>
<p><label class="label" for="psword">Password:</label>
<input id="psword" type="password" name="psword" size="12" maxlength="12" value="<?php if (isset($_POST['psword'])) echo $_POST['psword']; ?>" ><span> Between 8 and 12 characters.</span></p>
<p> </p><p><input id="submit" type="submit" name="submit" value="Login"></p>
</form><br>
why this code does not log to the admin-page.php or members-page.php
althogh i enter email and pass correctly.
result of this code pointed to the login page!
I know this error is very common and plenty of solution are mentioned but for some reason I cant get it working.
This is my index.php file which is the log in page for users
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: index.php");
}
?>
...
...
<form name='log' action='loginproc.php' method='POST'>
<input type="text" placeholder="Username" name="username">
<input type="password" placeholder="Password" name="password">
<input type='submit' value='Login' onclick="return check()">
</form>
This is the loginproc.php file
<?php
require 'config.php';
require 'core.inc.php';
if(isset($_POST['username'])&&isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(!empty($username) && !empty($password)) {
// $md5pwd = md5($password);
$query = "SELECT username FROM `login` WHERE `username` = '$username' and `password` = '$password';";
//echo $query;
//$query_run = mysqli_query($query);
//echo $query_run;
if($query_run = mysqli_query($conn,$query)) {
//echo $query_run;
$query_num_rows = mysqli_num_rows($query_run);
if($query_num_rows==0) {
phpAlert( "Invalid USERNAME or PASSWORD combination" );
echo '<script type="text/javascript">window.location = "index.php"</script>';
exit();
//echo '<p> Invalid USERNAME or PASSWORD combination <br /><br /> Click here to Login ';
}
else if($query_num_rows==1) {
//echo 'Hello';
$_SESSION['username']=$username;
header('Location: main.php');
}
}
}
else {
echo 'You Must supply a username and password';
}
}
function phpAlert($msg) {
echo '<script type="text/javascript">alert("' . $msg . '")</script>';
}
?>
The core.inc.php file
<?php
ob_start();
session_start();
function loggedin() {
if(isset($_SESSION['username'])&& !empty($_SESSION['username'])) {
return true;
}
else {
return false;
}
}
?>
you need to add an extra parameter when redirecting to index.php.
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
if($_REQUEST['ftime']!=1)
{
header ("Location: index.php?ftime=1");
}
}
?>
You need to have the redirect go elsewhere for logged in users and bypass when not logged in:
<?php
session_start();
// if session username is set and valid, go to somewhere else
if(isset($_SESSION['username']) && !empty($_SESSION['username'])) {
// elswhere could be a profile page, or similar
header("Location: elsewhere.php");
// It is more accepted to exit after a header
exit;
}
?>
<!-- All other instances beside valid login will allow this to form to show-->
<form name='log' action='loginproc.php' method='POST'>
<input type="text" placeholder="Username" name="username">
<input type="password" placeholder="Password" name="password">
<input type='submit' value='Login' onclick="return check()">
</form>
I'm currently using a modified version of a login script I found online.
Can anybody suggest some ways of modularizing the code into functions?
Here is the code for the login page:
<?php
include("db.php");
include("login_fns.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from Form
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$password=md5($password);
$sql="SELECT * FROM client_login WHERE Username='$username' and Password='$password'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row = mysql_fetch_array($result);
$client_ref = $row['Client_ref'];
$user_level = $row['user_level'];
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
$_SESSION['user_level'] = $user_level;
$_SESSION['client_ref'] = $client_ref;
$_SESSION['user'] = $username;
if ($user_level == '1') {
header('Location: admin.php');
} else {
header('Location: myaccount.php');
}
}
else
{
echo "Error logging in!";
}
}
?>
<form action="login.php" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Login "/><br />
</form>
Ideally, I'd like a function for the user account search and the session setting. I previously tried to copy snippets of this code into a separate php functions file, but it didn't seem to work.
What do you think about this? :)
The function
<?php
function checkLogin($username, $password) {
global $bd;
$returnArray=array();
$username=mysqli_real_escape_string($bd, $username);
$password=md5($password);
$getUser=mysqli_query($bd, "SELECT `Client_ref`,`user_level` FROM client_login WHERE Username='$username' and Password='$password'");
$arrayUser=mysqli_fetch_array($getUser);
if(mysqli_num_rows($getUser) == 0)
{
$returnArray['error']='true';
$returnArray['errormsg']='User not found in the database.';
return $returnArray;
}
$returnArray['Client_ref']=$row['Client_ref'];
$returnArray['user_level']=$row['user_level'];
return $returnArray;
}
?>
Rest of the code
<?php
include("db.php");
include("login_fns.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$username=$_POST['username'];
$password=$_POST['password'];
$loginArray=checkLogin($username, $password);
if(!isset($loginArray['error']))
{
$_SESSION['user_level'] = $loginArray['Client_ref'];
$_SESSION['client_ref'] = $loginArray['user_level'];
$_SESSION['user'] = $username;
if($loginArray['user_level'] == '1')
{
header('Location: admin.php');
}
else
{
header('Location: myaccount.php');
}
}
else
{
echo "Error logging in!";
echo "The detailed error message is: ".$returnArray['errormsg'];
}
}
?>
<form action="login.php" method="post">
<label>UserName :</label>
<input type="text" name="username"/><br />
<label>Password :</label>
<input type="password" name="password"/><br/>
<input type="submit" value=" Login "/><br />
</form>
I have a buyer form, called "Buyer.php":
<form method="post" action="check_buyer.php" id="LoggingInBuyer">
<div style="width:265px;margin:0; padding:0; float:left;">
<label>Username: <span>Forgot Username?</span></label> <br />
<input id="UserReg" style="width:250px;" type="text" name="userName" tabindex="1" class="required" /></div>
<div style="width:265px;margin:0; padding:0; float:right;">
<label>Password: <span>Forgot Password?</span></label> <br />
<input id="UserReg" style="width:250px;" type="password" name="userPass" tabindex="2" class="required" /></div>
<div class="clearB"> </div>
<input type="submit" style="width:100px; margin:10px 200px;" id="UserRegSubmit" name="submit" value="Login" tabindex="3" />
</form>
A file called check_buyer.php (in the same dir):
<?php
session_start(); #recall session from index.php where user logged include()
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
header( 'Location: buyer/' ); # return true if sessions are made and login creds are valid
echo "Invalid Username and/or Password";
return false;
}
require_once('../inc/db/dbc.php');
$connect = mysql_connect($h, $u, $p) or die ("Can't Connect to Database.");
mysql_select_db($db);
$LoginUserName = $_POST['userName'];
$LoginPassword = mysql_real_escape_string($_POST['userPass']);
//connect to the database here
$LoginUserName = mysql_real_escape_string($LoginUserName);
$query = "SELECT uID, uUPass, dynamSalt, uUserType FROM User WHERE uUName = '$LoginUserName';";
function validateUser($ifUserExists['uID'], $ifUserExists['uUserType']) {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = $uID;
$_SESSION['uUserType'] = $uUserType; // 1 for buyer - 2 for merchant
}
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such USER exists
{
echo "Invalid Username and/or Password";
}
$ifUserExists = mysql_fetch_array($result, MYSQL_ASSOC);
$dynamSalt = $ifUserExists['dynamSalt']; #get value of dynamSalt in query above
$SaltyPass = hash('sha512',$dynamSalt.$LoginPassword); #recreate originally created dynamic, unique pass
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}else {
validateUser();
}
// If User *has not* logged in yet, keep on /login
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
// This is now throwing error of: Parse error: syntax error, unexpected '[', expecting ')' in on line 23 which is function validateUser($ifUserExists['uID'], $ifUserExists['uUserType']) {
and the file "index.php" in the buyer/ directory:
<?php
session_start();
if($_SESSION['uUserType']!=1)
{
die("You may not view this page. Access denied.");
}
function isLoggedIn()
{
return (isset($_SESSION['valid']) && $_SESSION['valid']);
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1){
#echo "<a href='../logout.php'>Logout</a>";
require_once('buyer_profile.php');
}else{
echo "<a href='../index.php'>Login</a>";
}
?>
The point of this is that when a username and password is entered, the user is logged in and directed to /buyer/index.php, to the buyer portion of that website. It seems everytime I login with the dummy credentials I made to test, it just blurts out : You may not view this page. Access denied. But, then if I go back by pressing back arrow in browser it has me logged in and showing a link to logout.
I did some trouble shooting:
1) Shown here, to test my sql query is fine and indeed it is. http://i.stack.imgur.com/n2b5z.png
2)Tried choing out echo 'the userid: ' . $userid; before it whines about You may not view.. and it doesn't print anything.
How do I go about getting this userID? I double checked the field names in the database and all is fine..
From a quick check, it looks like you're setting $_SESSION['uUserType'] = $userType in validateUser(), but don't seem to be passing in $userType itself to that function. So $_SESSION['uUserType'] won't be 1, but $_SESSION['valid'] will be, because you're setting it to that in validateUser().
I suspect you should be passing valid data in to validateUser in order to set it into the session.
e.g.
validateUser($ifUserExists['uID'], $ifUserExists['uUserType']);
function validateUser($uID, $uUserType) {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = $uID;
$_SESSION['uUserType'] = $uUserType; // 1 for buyer - 2 for merchant
}
I am using the code below for a user login. The first I try to login after cache / cookies, etc. have been cleared, the browser refreshes and the user name is not logged in. After that, logging in works fine.
Any idea how I can make it work the first time?
Thanks in advance,
John
index.php:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){header('Location: http://www...com/.../index.php?username='.$username.'&password='.$password.'');}
require_once "header.php";
include "login.php";
require_once "footer.php";
?>
login.php:
<?php
if (!isLoggedIn())
{
if (isset($_POST['cmdlogin']))
{
if (checkLogin($_POST['username'], $_POST['password']))
{
show_userbox();
} else
{
echo "Incorrect Login information !";
show_loginform();
}
} else
{
show_loginform();
}
} else
{
show_userbox();
}
?>
show_loginform function:
function show_loginform($disabled = false)
{
echo '<form name="login-form" id="login-form" method="post" action="./index.php?'.$_SERVER['QUERY_STRING'].'">
<div class="usernameformtext"><label title="Username">Username: </label></div>
<div class="usernameformfield"><input tabindex="1" accesskey="u" name="username" type="text" maxlength="30" id="username" /></div>
<div class="passwordformtext"><label title="Password">Password: </label></div>
<div class="passwordformfield"><input tabindex="2" accesskey="p" name="password" type="password" maxlength="15" id="password" /></div>
<div class="registertext">Register</div>
<div class="lostpasswordtext">Lost password?</div>
<p class="loginbutton"><input tabindex="3" accesskey="l" type="submit" name="cmdlogin" value="Login" ';
if ($disabled == true)
{
echo 'disabled="disabled"';
}
echo ' /></p></form>';
}
EDIT: header.php includes this:
session_start();
So does that mean I'm using Sessions?
EDIT: per webbiedave's request, here are the login credential check functions I'm using:
<?php
#### Login Functions #####
function isLoggedIn()
{
if (session_is_registered('loginid') && session_is_registered('username'))
{
return true; // the user is loged in
} else
{
return false; // not logged in
}
return false;
}
function checkLogin($u, $p)
{
global $seed; // global because $seed is declared in the header.php file
if (!valid_username($u) || !valid_password($p) || !user_exists($u))
{
return false; // the name was not valid, or the password, or the username did not exist
}
//Now let us look for the user in the database.
$query = sprintf("
SELECT loginid
FROM login
WHERE
username = '%s' AND password = '%s'
AND disabled = 0 AND activated = 1
LIMIT 1;", mysql_real_escape_string($u), mysql_real_escape_string(sha1($p . $seed)));
$result = mysql_query($query);
// If the database returns a 0 as result we know the login information is incorrect.
// If the database returns a 1 as result we know the login was correct and we proceed.
// If the database returns a result > 1 there are multple users
// with the same username and password, so the login will fail.
if (mysql_num_rows($result) != 1)
{
return false;
} else
{
// Login was successfull
$row = mysql_fetch_array($result);
// Save the user ID for use later
$_SESSION['loginid'] = $row['loginid'];
// Save the username for use later
$_SESSION['username'] = $u;
// Now we show the userbox
return true;
}
return false;
}
?>
The line that is causing your page to refresh is
if($_SERVER['REQUEST_METHOD'] == "POST"){header('Location: http://www...com/.../index.php?username='.$username.'&password='.$password.'');}
What that is doing, is when you post to the page, it redirects you back to the index page with the username and password in the url.
So does that mean I'm using Sessions?
Yes, you are using sessions. That is how you are saving your login state from page to page.
However, to answer the question, remove the line I mentioned at the beginning of the article. I cannot see where it does you any good. It simply moves the values from the $_POST array to the $_GET array, and then you still look in the $_POST array.
Edit:
Change index.php to the following:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
if (checkLogin($_POST['username'], $_POST['password'])) {
header('Location: http://www...com/.../index.php');
}
}
require_once "header.php";
include "login.php";
require_once "footer.php";
?>