PHP webpage has a direct loop error? - php

I have been trying to create a login page in PHP to no avail though, i have been getting a "This webpage has a redirect loop" error when i try to run it, so i was wondering if anyone could possibly spot my mistakes? Here is my code:
<?php
require_once("nocache.php");
$id = $_POST["id"];
$pword = $_POST["pword"];
if (!empty($_POST){
if (!empty($id) || !empty($pword)){
require_once("dbconn.php");
$sql = "select username, school_type from school_info where username = '$id' and password = '$pword'";
$rs = mysql_query($sql, $dbConn);
if (mysql_num_rows($rs)> 0 ) {
session_start();
$_SESSION["who"] = $id;
$_SESSION["school_type"] = mysql_result($rs,0,"school_type");
header("location: EOI_home.php");
}
}
else {
header("location: login.php");}
} else {
header("location: login.php");}
?>
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="login">
ID: <input type="text" name="id" /><br/>
pword: <input type="password" name="pword" /><br/>
<input type="submit" value="log in" />
<input type="reset" />
</form>

All of the answers given are technically correct, the way you've set your logic is incorrect... take the following example and port it across into your own code.
<?php
$id = $_POST["id"];
$pword = $_POST["pword"];
if(!empty($_POST)) {
// The form was submitted, perform validation here.
if(!empty($id) || !empty($pword)) {
// Form validation passed, insert into database
} else {
// Form validation failed, display an error or redirect back
}
} else {
// Form was not submitted, so display the form.
}
?>
Edit
I was hoping not to have to do the work for you (since it's best you learn) but perhaps seeing the above code, and the below code you can learn from it that way?
<?php
require_once("nocache.php");
$id = $_POST["id"];
$pword = $_POST["pword"];
if(!empty($_POST)) {
if(!empty($id) || !empty($pword)) {
require_once("dbconn.php");
$sql = "select username, school_type from school_info where username = '$id' and password = '$pword'";
$rs = mysql_query($sql, $dbConn);
if(mysql_num_rows($rs) > 0) {
session_start();
$_SESSION["who"] = $id;
$_SESSION["school_type"] = mysql_result($rs, 0, "school_type");
header("location: EOI_home.php");
}
} else {
header("location: login.php");
}
}
?>
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="login">
ID: <input type="text" name="id" /><br/>
pword: <input type="password" name="pword" /><br/>
<input type="submit" value="log in" />
<input type="reset" />
</form>

The loop is here:
$id = $_POST["id"];
$pword = $_POST["pword"];
if (empty($id) || empty($pword)){
header("location: login.php"); }
If the $_POST values are not set, the redirect happens. Since you are not setting the values before the redirect, it happens again. And again. And again...
To correct this problem, display your form if the $_POST values are not set.

Related

HTML form not passing values to PHP (mysqli_real_escape_string)

HTML
<form type="POST" action="includes/login.php">
<input type="email" name="email" placeholder="email" />
<input type="password" name="password" placeholder="parola" />
<input type="submit" value="Login">
</form>
PHP
<?php
require_once 'config.php';
if(isset($_POST['email']))
{
$email = mysqli_real_escape_string($_POST['email']);
}
else
{
echo "Nu ati completat adresa de e-mail. <br />";
}
if(isset($_POST['password']))
{
$email = mysqli_real_escape_string($_POST['password']);
}
else
{
echo "Nu ati completat parola. <br />";
}
if(isset($_POST['email']) && ($_POST['password']))
{
$query = ("SELECT * FROM `users` WHERE password = '$password' AND email = '$email'");
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$count_rows = mysqli_num_rows($result);
if ($count_rows == 1)
{
$_SESSION["login"] = "OK";
header("Location: ../index.php");
}
else
{
header("Location: ../login.php");
}
}
?>
I tried switching from MySQL to MySQLi and I'm sure it's related to this. My form is not passing values to the PHP script even if the inputs have a name. Did some research here on StackOverflow and found many questions about forms not passing data but there was usually a typo or a missing name, which is not my case (I think).
(I know that the password is not secured yet, I'll add a SHA256 or something there soon so don't stress about it)
Tried echoing the query and it's just blank where the password and email address should be.
SELECT * FROM `users` WHERE password = '' AND email = ''
I also get this warning:
Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\breloc\includes\login.php on line 4
Line 4 in my script is:
$email = mysqli_real_escape_string($_POST['password']);
make change to Your form tag
<form type="POST">
to
<form method="POST">
Change form type="post" to method="post"
Add database connection string to your mysqli_real_escape_string function.
According to the Documentation http://php.net/manual/de/mysqli.real-escape-string.php
you must provide the mysqli ressource as first parameter of the function.
You should use method instead of type in your <form> tag, like this:
<form method="POST" action="includes/login.php">
<form method="POST" action="includes/login.php">
<input type="email" name="email" placeholder="email" />
<input type="password" name="password" placeholder="parola" />
<input type="submit" value="Login" name="submit">
</form>
<?php
require_once 'config.php';
if(isset($_POST['submit'])) {
if(!empty($_POST[email]))
{
$email = mysqli_real_escape_string($link,$_POST['email']);
}
else
{
echo "Nu ati completat adresa de e-mail. <br />";
}
if(!empty($_POST['password']))
{
$password = mysqli_real_escape_string($link,$_POST['password']);
}
else
{
echo "Nu ati completat parola. <br />";
}
if(!empty($_POST['email']) && !empty($_POST['password']))
{
$query = ("SELECT * FROM `users` WHERE password = '".$password."' AND email = '".$email."'");
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$count_rows = mysqli_num_rows($result);
if ($count_rows == 1)
{
$_SESSION['login'] = "OK";
header("Location: ../index.php");
}
else
{
header("Location: ../login.php");
}
}}
?>
set 'method' not type
<form method="POST" action="includes/login.php">
<input type="email" name="email" placeholder="email" />
<input type="password" name="password" placeholder="parola" />
<input type="submit" value="Login">
</form>
don't forget to connect to your db and pass the that connection to your mysqli_query and mysqli_real_escape_string functions
<?php
require_once 'config.php';
$con=mysqli_connect("localhost","my_user","my_password","my_db");
if(isset($_POST['email']))
{
$email = mysqli_real_escape_string($con, $_POST['email']);
}
else
{
echo "Nu ati completat adresa de e-mail. <br />";
}
if(isset($_POST['password']))
{
$email = mysqli_real_escape_string($con,$_POST['password']);
}
else
{
echo "Nu ati completat parola. <br />";
}
if(isset($_POST['email']) && ($_POST['password']))
{
$query = ("SELECT * FROM `users` WHERE password = '$password' AND email = '$email'");
$result = mysqli_query($con, $query);
$row = mysqli_fetch_array($result);
$count_rows = mysqli_num_rows($result);
if ($count_rows == 1)
{
$_SESSION["login"] = "OK";
header("Location: ../index.php");
}
else
{
header("Location: ../login.php");
}
}
?>
string mysqli_real_escape_string ( mysqli $link , string $escapestr )
As from Docs, the first parameter must be mysqli resource and its missing within your code, and also change
<form type="POST">
into
<form method="post">
So your code looks like
mysqli_real_escape_string($link,$_POST['email']);// and been repeated at all those occurences

Login PHP with DB

I am trying to do a login with MySQL, but it's not working. Basically I'm trying to check the login and password posted against my DB, but it's not working for some reason. Could someone give me a hint?
login.php
include "conexao.php";
$result = mysql_query("SELECT * FROM usuario WHERE login = '".$_POST['login']."' AND senha = '".$_POST['senha']."'") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
session_start();
if ($_POST['login'] && $_POST['senha']) {
if ($row['login'] == $_POST['login'] && $row['senha'] == $_POST['senha']) {
$_SESSION['login'] = $row['login'];
$_SESSION['senha'] = $row['senha'];
header("Location: index.php");
} else {
unset ($_SESSION['login']);
unset ($_SESSION['senha']);
header("Location: login2.php?i=n");
}
}
}
HTML form
<form method="post" action="login.php" class="cbp-mc-form" autocomplete="off">
<label for="login">Login</label>
<input type="text" name="login" id="login" /><br />
<label for="senha">Senha</label>
<input type="password" name="senha" id="senha" /><br />
<center><input class="cbp-mc-submit" type="submit" value="Login""/></center>
</form>
Dear Brother try the following code, (I edited your code)
I hope it will work in your case, but if you're using the same code for production, than please take care of the Sanitization.
the code I edited for you is as follows (if it still doesn't work, than there might be some error in your database connection).
The PHP Script:
<?php
session_start(); // better to start the session in the begining,
//in some cases it doesn't work in the mid of the document'
include 'conexao.php';
if (isset($_POST['login']) && isset($_POST['senha'])) // check if both the form fields are set or not
{
// Values coming from the user through FORM
$login_form = $_POST['login'];
$senha_form = $_POST['senha'];
// query the database only when user submit the form with all the fields filled
$result = mysql_query("SELECT * FROM usuario WHERE login='$login_form' AND senha='$senha_form'") or die (mysql_error());
while ($row = mysql_fetch_assoc($result))
{
// values coming from Database
$login_db = $row['login'];
$senha_db = $row['senha'];
}
// compare the values from db to the values from form
if ($login_form == $login_db && $senha_form == $senha_db)
{
// Set the session only if user entered the correct username and password
// it doesn't make sense to set session even if the user entered wrong values
$_SESSION['login'] = $login_db;
$_SESSION['senha'] = $senha_db;
header("Location: index.php");
}
else
{
header("Location: login2.php?i=n");
}
}
?>
The HTML: (exactly your html copied)
<form method="post" action="login.php" class="cbp-mc-form" autocomplete="off">
<label for="login">Login</label>
<input type="text" name="login" id="login" /><br />
<label for="senha">Senha</label>
<input type="password" name="senha" id="senha" /><br />
<center><input class="cbp-mc-submit" type="submit" value="Login""/></center>
</form>
from PHP Header not redirecting
I added ob_start(); on the very first line and it worked.

Issue with php mysql login $_POST['username'] = $result['username']

I'm kinda' beginner and I've coded my own PHP login from Zero, but I still got some errors, here's the code:
<?php
include 'connection.php';
$query = " SELECT * FROM admin";
$result = mysql_query($query) or die(mysql_error());
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
if ($username = $result['username']) {
if ($password = $result['password']){
header('Location: admin.php');
} else {
echo "PASSWORD IS INCORRECT";
}
} else {
echo "USERNAME IS INCORRECT";
}
?>
So if you can fix this or got an easier way from PHP login from please tell me. :)
A few things...
Don't use mysql functions
You need to use == to compare strings, not =
You need to actually fetch the results of your query
include 'connection.php';
$query = " SELECT * FROM admin";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result); /* add this */
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
if(isset($_POST['usernameInput']) && isset($_POST['passwordInput'])){
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
}
else{
echo 'some error ...';
}
if($username == $row ['username'] && $password == $row ['password']){
header('Location: admin.php');
}
else{
echo ' username or password is wrong';
}
?>
I have to point out that you are sending the same form over and over without first checking the post. And when you send the form, you will not be able to send the header to redirect, because html is started and headers are sent already.
Mysql functions are deprecated, please use mysqli interface.
Among other several bugs like assignment = instead of is equal ==
Try it this way:
If no post exists send the form else check and if ok redirect or not ok. resend the form
<?php
if($_POST){
include 'connection.php';
$query = " SELECT * FROM admin";
$r = mysql_query($query) or die(mysql_error());
// get an associated array from query result resource.
$result = mysql_fetch_assoc($r);
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
if ( ($username == $result['username'])
&& ($password == $result['password'])){
header('Location: admin.php');
exit(0);
} else {
echo "PASSWORD IS INCORRECT";
}
}
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
?>

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>

cant make login page work

I have this php page that posts to itself and then it checks weather if to login someone or not. The problem I am having is that if it logins... then it still shows the username and password textboxes.. but if i refresh they go away and now the welcome thing comes up thanks to the session.
What i want is to once the submit is clicked and it logs the person in to immediately not show the textboxes (username, password) and show the welcome message. Right now i have to refresh.
Please note i am new to PHP and any wise advise will be much appreciated.
<?php
echo "<form method=\"post\" action=\"index.php?form_type=$page_vals\">";
echo "<body>";
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
extract($_POST);
$username = "";
$password = "";
$userrole = "";
$userid ="";
$login_query = "SELECT user_id, user_role, user_username FROM users WHERE user_username = '$_POST[logInUsername]' AND user_password = '$_POST[logInPassword]'";
if(!($database = mysql_connect("localhost","root","")))
die("<p>Could not connect to database</p></div></div>
</body>
</html>");
if(!mysql_select_db("mydatabase", $database))
die("<p>Could not open my databases database</p></div>
</div>
</body>
</html>");
if(!($result = mysql_query($login_query, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
if (mysql_num_rows($result) == 0) {
print("Please verify your login information<br/>");
}
while ($row = mysql_fetch_assoc($result)) {
$username = $row["user_username"];
$userrole = $row["user_role"];
$userid = $row["user_id"];
}
echo "Hello - '$username'";
mysql_close($database);
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $userid;
$_SESSION['SESS_NAME'] = $username;
//Write session to disc
session_write_close();
echo '<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" class="button" />
</div>';
}
else
{
$sessionName = $_SESSION['SESS_NAME'];
echo '<div id="login" class="login">
<label for="welcome">Welcome '. $sessionName.'!</label>
</div>';
}
?>
Problem here is just your code is not in sequence. I have corrected Try it now.
<?php
session_start();
echo "<body>";
//Start session
//print_r($_SESSION);exit;
//Check whether the session variable SESS_MEMBER_ID is present or not
extract($_POST);
$username = "";
$password = "";
$userrole = "";
$userid ="";
if(isset($_POST))
{
$login_query = "SELECT reg_id, role_id, f_name FROM registration WHERE f_name = '$_POST[logInUsername]' AND password = '$_POST[logInPassword]'";
if(!($database = mysql_connect("sunlinux","pukhraj","pukhraj123")))
die("<p>Could not connect to database</p></div></div>
</body>
</html>");
if(!mysql_select_db("testbaj", $database))
die("<p>Could not open my databases database</p></div>
</div>
</body>
</html>");
if(!($result = mysql_query($login_query, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
if (mysql_num_rows($result) == 0) {
print("Please verify your login information<br/>");
}
while ($row = mysql_fetch_assoc($result)) {
$username = $row["f_name"];
$userrole = $row["role"];
$userid = $row["reg_id"];
}
$_SESSION['SESS_MEMBER_ID'] = $userid;
$_SESSION['SESS_NAME'] = $username;
}
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
echo "Hello - '$username'";
mysql_close($database);
session_regenerate_id();
//Write session to disc
session_write_close();
echo "<form method=\"post\" ><div id=\"login\" class=\"login\">
<label for=\"login\">User Name</label>
<input type=\"text\" name=\"logInUsername\" />
<label for=\"Password\">Password</label>
<input type=\"password\" name=\"logInPassword\" />
<input type=\"submit\" value=\"Submit\" class=\"button\" />
</div>";
}
else
{
$sessionName = $_SESSION['SESS_NAME'];
echo "<div id=\"login\" class=\"login\">
<label for=\"welcome\">Welcome '$sessionName' !</label>
</div>";
}
?>
Small changes :
Just plase form tag at appropriate place.
Never mix code after post and before post.
here all database stuff should be execute after submit so I enclosed them in condition if(isset($_POST))
due to nonlinearity of code it was creating session after one more refresh after post data. Now corrected.
for message :
do below changes :
give name to submit button <input type=\"submit\" name=\"submit\" value=\"Submit\" class=\"button\" />
replace first if condition with if(isset($_POST['submit']))
So, not dealing with any of the security or style issues that are here...
Right now you are seeing if the session is set. If it is not, then you process the login. After processing the login, you display the form fields.
You should actually check for 3 states...
Is someone already logged in?
Do you need to process a login?
If neither of those, show normal form...
You can do this by using your existing isset for the session field.
Then if it is not set, check if the post fields are set... if they are set, process a login.
Otherwise, show the basic login form.
EDIT:
Full code sample (sorry for the terrible formatting, mostly cut and paste...:
<?php
echo "<form method=\"post\" action=\"index.php?form_type=$page_vals\">";
echo "<body>";
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) != '')) {
$sessionName = $_SESSION['SESS_NAME'];
echo '<div id="login" class="login">
<label for="welcome">Welcome '. $sessionName.'!</label>
</div>';
}
else if ($_POST[logInPassword] != null && $_POST[logInUsername] != null)
{
extract($_POST);
$username = "";
$password = "";
$userrole = "";
$userid ="";
$login_query = "SELECT user_id, user_role, user_username FROM users WHERE user_username = '$_POST[logInUsername]' AND user_password = '$_POST[logInPassword]'";
if(!($database = mysql_connect("localhost","root","")))
die("<p>Could not connect to database</p></div></div>
</body>
</html>");
if(!mysql_select_db("mydatabase", $database))
die("<p>Could not open my databases database</p></div>
</div>
</body>
</html>");
if(!($result = mysql_query($login_query, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
if (mysql_num_rows($result) == 0) {
print("Please verify your login information<br/>");
}
while ($row = mysql_fetch_assoc($result)) {
$username = $row["user_username"];
$userrole = $row["user_role"];
$userid = $row["user_id"];
}
echo "Hello - '$username'";
mysql_close($database);
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $userid;
$_SESSION['SESS_NAME'] = $username;
//Write session to disc
session_write_close();
$sessionName = $_SESSION['SESS_NAME'];
echo '<div id="login" class="login">
<label for="welcome">Welcome '. $sessionName.'!</label>
</div>';
}
else
{
echo '<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" class="button" />
</div>';
}
?>
Good luck!
Your logic just needs to be rethought. How about something like this? (pseduocode)
if( user is NOT logged in) // Check via session
{
$errors = array();
if( user submitted the form and is trying to log in) // Can be checked with a POST'd variable
{
// Set the session correctly here, query DB, etc.
// If there are any errors, add them to the $error array
}
if( !empty( $errors) || form was not submitted)
{
// Print the form and any errors (like invalid username / password combo)
}
exit; // Stop here
}
// Print welcome message here (since we know if we get here, the user is logged in)

Categories