PHP: this webpage has a redirect loop - php

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>

Related

Logout - have to hit button twice for it to work?

Trying to perform a logout from current page. Basically if you hit the logout, it will just show the login form again. I do not want to call a page doing this. When I execute the "Logout" button, it still shows the user logged in, but if I hit the "Logout" button a second time it works correctly. Or if I refresh the page it works also. Just seems the initial submitting of "Logout" does not refresh.
<?
session_start();
$subtitle="Login";
ob_start();
// require("header2.php");
//Get any form data.
$football->WhoOnlineDelete;
$username=$_POST['username'];
$password=$_POST['password'];
global $conn;
$conn = mysqli_connect("localhost","","", "");
function logOut()
{
unset($_SESSION['user']);
unset($_SESSION['uname']);
session_destroy();
ob_start();
exit();
}
if ($_POST)
{
//Make sure cookies are enabled.
// if ($_COOKIE["football"]=="")
// {
// $football->ErrorMessage("You must use a browser that supports cookies and<br> have them enabled in order to access this site.");
// }
// else
// {
//Check input.
if ($username=="")
{
echo "Please enter a username.";
}
elseif ($password=="")
{
echo"Please enter your password.";
}
else
{
//Verify the password and redirect to default page if correct.
$sql=mysqli_query($conn, "select * from phpfb_users where user = '".$username."'");
$row = mysqli_fetch_object($sql);
$rows = mysqli_num_rows($sql);
if($rows == 0)
{
echo "User '".$username."' not found.";
}
elseif (md5($password) != $row->password)
{
echo "Incorrect password, please reenter.";
}
else
{
$user=$row->user;
if ($row->name =="") {
$uname=$row->user;
} else {
$uname=$row->name;
}
$_SESSION['uname'] = $uname;
$_SESSION['user'] = $user;
header("Location: loginJERRY.php");
}
}
}
//}
else
{
//Set test cookie.
setcookie("football","peanutbutter",0,"/",$football->domain,0);
}
?>
<div>
<div style="display:block;margin:0px auto;" background-color="lightblue;">
<?php if(empty($_SESSION["user"])) { ?>
<form name="loginform" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<div class="error-message"><?php if(isset($message)) { echo $message; } ?></div>
<div class="field-group">
<div><label for="login">Username: </label>
<input name="username" type="text" class="input-field">
<label for="password">Password:</label>
<input name="password" type="password" class="input-field">
<input type="submit" name="login" value="Login" class="form-submit-button"></span></div>
</div>
</form>
<?php
} else {
$result = mysqli_query($conn,"SELECT * FROM phpfb_users WHERE user='".$username."' and password = '".$password."'");
$row = mysqli_fetch_array($result);
?>
<br><br>
<form action="" method="post" id="frmLogout">
<div class="member-dashboard">Welcome <?php echo $user; ?>, You have successfully logged in!
<input type="submit" name="logout" value="logout" class="logout-button"></div>
</form>
<?
if (isset($_POST['logout'])) {
if ($_POST['logout'] == 'logout') {
logOut();
} else if ($_POST['logout'] != 'logout') {
}
}
?>
</div>
</div>
<?php } ?>
</body>
<script type='text/javascript'>
document.loginform.username.focus();
document.loginform.username.select();
</script>
Am I missing something?
You need to check logout functionality before you html page renders, so add you logout key in $_POST after logout() function like,
<?
..........
$conn = ....
function logOut()
{
unset($_SESSION['user']);
unset($_SESSION['uname']);
session_destroy();
ob_start();
exit();
}
if (isset($_POST['logout']) && $_POST['logout'] == 'logout') {
logOut();
} // not required else part here
if($_POST) {
....
?>
From the technical point of view the user is logged out (because the session variable is destroyed) but the page is showing something different. You need to take the logout part on top before the page gets rendered, otherwise the page doesn't know that the user is logged out:
<?
session_start();
$subtitle="Login";
ob_start();
// require("header2.php");
//Get any form data.
$football->WhoOnlineDelete;
$username=$_POST['username'];
$password=$_POST['password'];
global $conn;
$conn = mysqli_connect("localhost","","", "");
function logOut()
{
unset($_SESSION['user']);
unset($_SESSION['uname']);
session_destroy();
ob_start();
exit();
}
if (isset($_POST['logout'])) {
if ($_POST['logout'] == 'logout') {
logOut();
} else if ($_POST['logout'] != 'logout') {
}
}
if ($_POST)
{
//Make sure cookies are enabled.
// if ($_COOKIE["football"]=="")
// {
// $football->ErrorMessage("You must use a browser that supports cookies and<br> have them enabled in order to access this site.");
// }
// else
// {
//Check input.
if ($username=="")
{
echo "Please enter a username.";
}
elseif ($password=="")
{
echo"Please enter your password.";
}
else
{
//Verify the password and redirect to default page if correct.
$sql=mysqli_query($conn, "select * from phpfb_users where user = '".$username."'");
$row = mysqli_fetch_object($sql);
$rows = mysqli_num_rows($sql);
if($rows == 0)
{
echo "User '".$username."' not found.";
}
elseif (md5($password) != $row->password)
{
echo "Incorrect password, please reenter.";
}
else
{
$user=$row->user;
if ($row->name =="") {
$uname=$row->user;
} else {
$uname=$row->name;
}
$_SESSION['uname'] = $uname;
$_SESSION['user'] = $user;
header("Location: loginJERRY.php");
}
}
}
//}
else
{
//Set test cookie.
setcookie("football","peanutbutter",0,"/",$football->domain,0);
}
?>
<div>
<div style="display:block;margin:0px auto;" background-color="lightblue;">
<?php if(empty($_SESSION["user"])) { ?>
<form name="loginform" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<div class="error-message"><?php if(isset($message)) { echo $message; } ?></div>
<div class="field-group">
<div><label for="login">Username: </label>
<input name="username" type="text" class="input-field">
<label for="password">Password:</label>
<input name="password" type="password" class="input-field">
<input type="submit" name="login" value="Login" class="form-submit-button"></span></div>
</div>
</form>
<?php
} else {
$result = mysqli_query($conn,"SELECT * FROM phpfb_users WHERE user='".$username."' and password = '".$password."'");
$row = mysqli_fetch_array($result);
?>
<br><br>
<form action="" method="post" id="frmLogout">
<div class="member-dashboard">Welcome <?php echo $user; ?>, You have successfully logged in!
<input type="submit" name="logout" value="logout" class="logout-button"></div>
</form>
</div>
</div>
<?php } ?>
</body>
<script type='text/javascript'>
document.loginform.username.focus();
document.loginform.username.select();
</script>
You could also reload the page after calling the logout function, but this isn't very nice in my opinion. You always have to keep in mind that you first have to execute all the logic before you render the page.

Login / Registration PHP form

having a bit of trouble with my login / reg forms
Basically when i register (create new user) it takes me to the login.php script and not the register script.
The login form is in the "header.php" page so its at the top of every page including the register form. But dont think that would be an issue?
Register form
<?php
include("config.php");
include("header.php");
?>
<div id="contentwrap">
<form name="myuserform" method="POST" action="register.php" onsubmit="return validateForm();">
<tr class='alt'>
<td>email address: <td><input type="text" name="email">
<tr class='alt'>
<td>Password: <td><input type="password" name="password">
<tr class='alt'>
<td>Your name: <td><input type="text" name="username">
<tr class='alt'>
<td><input type="submit" name="adduser" value="Sign me up!">
</form>
</div>
Register.php
<?php
if (isset($_POST['adduser']))
{
$error = "";
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$md5_pass = md5($password);
$email = mysqli_real_escape_string($connection, $_POST['email']);
if (!isset($username) || empty($username) ||
!isset($password) || empty($password) ||
!isset($email) || empty($email))
{
$error = "All fields must be filled out";
}
else if (user_exists($connection, $username))
{
$error = "Username already registered";
}
else if (strlen($password) < 6)
{
$error = "Password must be at least 6 characters";
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // check if email looks valid
{
$error = "Please enter a valid email";
}
if ($error == "")
{
//$query = "INSERT INTO users (email, password, username) VALUES ('{$email}','{$md5_pass}','{$username}')";
$query = "INSERT INTO users (username, password, email) VALUES ('{$username}','{$md5_pass}','{$email}')";
$result = mysqli_query($connection, $query);
if ($result)
echo " <b>Registered successfully!</b><br/>Please return to the <a href='index.php'>index</a> to login.";
else
$error = "Unable to create new user";
}
if ($error != "") // redo error string check since the last block may have set it
{
echo "Error: {$error}. Please return to the previous page.";
}
exit();
}
?>
Login.php
<?php
include("config.php");
if (isset($_POST['username']) && !empty($_POST['username']) &&
isset($_POST['password']) && !empty($_POST['password']))
{
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = md5($_POST['password']);
$query = "SELECT * FROM users WHERE username='{$username}' AND password='{$password}'";
$res = mysqli_query($connection, $query);
if (mysqli_num_rows($res) >= 1)
{
$row = mysqli_fetch_array($res);
if($row['rank'] == "banned")
{
echo "You have been banned from the site.";
exit();
}
$_SESSION['uid'] = $row['userid'];
$_SESSION['username'] = $row['username'];
if($row['rank'] == "admin")
$_SESSION['is_admin'] = true;
header("Location: index.php");
exit();
}
else
{
echo "Username/password invalid. Return to the <a href='index.php'> home </a>page";
exit();
}
}
echo "Something went wrong, try again"; <--- this is the result im getting
?>
here is the login form (apart of header.php)
<?php
if (!isset($_SESSION['uid']) || empty($_SESSION['uid']))
{
echo "<form action='login.php' method='post'>
Username: <input type='text' name='username' Placeholder='Username' style='width:100px;'/>
Password: <input type='password' name='password' Placeholder='Password' style='width:100px;' />
<input type='submit' name='submit' value='Log In' />";
echo "<div id='freeman'>
<a href='signup.php'> <img src='images/register.jpg' width='60px' height='60px' /> </a>
</div>";
} else {
echo "You are logged is as {$_SESSION['username']} • <a href='logout.php'>Logout</a>";
}
?>
The problem that when you register your not opening a session to consider the user as logged and acquire a session for him.
The other issue your not checking in your login script if the user already have a session which implies that he is already logged in

I am trying to verify the state of $_SESSION to allow access to a web page and it is not working

The page that has the following code will only redirect:
Here is the code I am trying to include at the top of other pages that I want to check S_SESSION before allowing access:
<?php
session_start();
include ('connect_SQL_DB.php');
include('header.html');
if(!isset($_SESSION['login']) || (trim($_SESSION['login'])=='')) {
header('location:login_redirect.php');
exit();
}
?>
Here js my code for the login page:
<?php
session_start();
include ('connect_SQL_DB.php');
include('header.html');
print '<h2>Login Form</h2>
<p>Users who are logged in can view and make changes to the website.</p>';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ( (!empty($_POST['email'])) && (!empty($_POST['password'])) ) {
$query=mysql_query("SELECT * FROM account WHERE email= '"
. $_POST['email'] . "'
AND password= '" . $_POST['password'] . "'
AND enabled='1'") or die (mysql_error());
$check = mysql_num_rows($query);
if ($check > 0) {
$row = mysql_fetch_array($query, MYSQL_ASSOC);
$user = array(
'userid' => $row['userid'],
'email' => $row['email'],
'accesslevel' => $row['accesslevel'],
'password' => md5 ($row['password']),
'enabled' => $row['enabled'],
);
//Session
session_start();
$_SESSION['login'][] = $user;
header('location:message.php');
ob_end_clean();
exit();
} else {
header('location:login_redirect.php');
}
} else {
print '<p>Please make sure you enter both an email address and a password!<br />Go
back and try again.</p>';
}
} else {
print '<form action="login.php" method="post">
<p>Email Address: <input type="text" name="email" size="20" /></p>
<p>Password: <input type="password" name="password" size="20" /></p>
<p><input type="submit" name="submit" value="Log In!" /></p>
</form>';
}
include('footer.html');
?>
Its not working because header already sent when you include header.html
Always put your redirect logic on above any print statement.
Try to put following code on every page.
<?php
session_start();
if(!isset($_SESSION['login']) || (trim($_SESSION['login'])=='')) {
header('location:login_redirect.php');
exit();
}
include ('connect_SQL_DB.php');
include('header.html');
?>

Login form not submitting properly in PHP

I'm new to PHP and I have a login page with a form. I want to authenticate the user and then redirect the user to another page with the season values. When I submit the page is not redirecting and if a pres F5 the page will popup the resubmission message of the form. This is my code.
<?php
session_start();
include('../includes/header.php');
$title="Login";
?>
<?php
include('../includes/authenticate.php');
include('../includes/dbschema.php');
//if the user has not logged in
if(!isLoggedIn())
{
if($_SERVER['REQUEST_METHOD']== 'POST'){
//include('../includes/authenticate.php');
$username = $_POST['username'];
$password = $_POST['password'];
//sanitize username
$username = mysql_real_escape_string($username);
if(isset($_POST['username']) && isset($_POST['password'])){
$query = "SELECT password, salt FROM user WHERE username = '$username';";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such user exists
{
header('login.php');
$errmessage = "Invalid user";
print "<p id\"errmessage\"> $errmessage </p>";
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password
{
header('login.php');
}
else
{
validateUser(); //sets the session data for this user
}
//redirect to another page or display "login success" message
header('Location: actividades.php');
}
}
else
{
$status = "logout";
print "<p id=\"usernamelink\">Bienvenido,<a id=\"usernamecolor\"> " . $_SESSION['username'] . " </a></p>";
print "<a id=\"logoutlink\" href=\"../includes/logout.php \">Log out</a>";
//page content follows
}
?>
</br>
<div id="logindiv">
<?php print "<h1 id=\"logintitle\">Login</h1>";?>
<form id="loginform" name="login" action="login.php" method="post" >
Username: <input id="inplogin" type="text" name="username" />
<br/><br/>
Password: <input id="inplogin" type="password" name="password" />
<br/>
<input id="btnlogin" type="submit" value="Login" />
</form>
</div>
<?php include('../includes/footer.php') ; ?>
You should exit; after redirecting. And pass the error to your login script, for example:
if(login_fails()){
header('Location: login.php?errorCode=1');
exit;
}
In your login.php script, check if $_GET['errorCode'] is present and display an error message:
$errors = array(
1 => 'Incorrect password',
);
if(isset($_GET['errorCode'])){
$code = $_GET['errorCode'];
print isset($errors[$code]) ? $errors[$code] : 'Unknown error';
}

How can I split my Login process into functions?

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>

Categories