PHP loading issue "redirected too many times" - php

localhost redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS
My code was working perfectly fine, but today this error occurred not quite sure why. I have cleared browsing data, deleted cookies but nothing works. The rest of my site is functioning well, just this user login page. I am using PHPstorm.
<?php
include_once("db.php");
if (isset($_POST['Login'])) {
$email = $_POST['email'];
$password = $_POST['pwd'];
$path = "home.php";
$select = "SELECT * FROM finalflight.tbl_book
WHERE email='" . $email . "'
AND ContactNo='" . $password . "'";
$query = mysqli_query($conn, $select);
}
if ($row = mysqli_fetch_assoc($query)) {
session_start();
$_SESSION['email'] = $row['email'];
$_SESSION['name'] = $row['BookedBy'];
$_SESSION['ContactNo'] = $row['ContactNo'];
$_SESSION['bookid'] = $row['SrNo'];
$_SESSION['uid'] = session_id();
$path = "home.php";
} else {
$path = "login.php?msg='unable to login'";
}
header("location:$path");
I have attached the error message screenshot. I am intrigued to know why the error has occurred wondering if someone could explain what is actually going on. PHPstorm came up with a redirect link for my page which I copied to clipboard and pasted it into my browser but that didn't seem to work. Is this a programming issue or a web browser issue? I have checked through my code and there doesn't seem to be any errors. I have tried reloading the web browser many times, deleted history nothing seems to work.
Error Message

you are calling header function while page leading that's why too many redirections. call header after post submitted
try this,
<?php
include_once("db.php");
if (isset($_POST['Login'])) {
$email = $_POST['email'];
$password = $_POST['pwd'];
$path = "home.php";
$select = "SELECT * FROM finalflight.tbl_book
WHERE email='" . $email . "'
AND ContactNo='" . $password . "'";
$query = mysqli_query($conn, $select);
if ($row = mysqli_fetch_assoc($query)) {
session_start();
$_SESSION['email'] = $row['email'];
$_SESSION['name'] = $row['BookedBy'];
$_SESSION['ContactNo'] = $row['ContactNo'];
$_SESSION['bookid'] = $row['SrNo'];
$_SESSION['uid'] = session_id();
$path = "home.php";
} else {
$path = "login.php?msg='unable to login'";
}
header("location:$path");
}

Your browser will tell you what is going wrong if you dig a bit deeper. Likely your PHP error logging is trying to tell you about some of the problems too.
At a guess, The code you've shown us is probably working OK, but the page you are redirecting to is sending you back to this page - but you should NEVER REDIRECT TO THIS CODE! Actually, the code you've shown us should be re-written to handle the case where it is retrieved without the required POST vars without going completely pear-shaped.
Use the network monitor in your browser to see where you are getting 302 responses and where they are directing you to. Make sure your error logging is working properly and recording errors.

Related

all the links redirects to index.php

I have a php script. Many of my customers are using it. But for few they say, they are able to login but when they click on any links from the menu, it just redirects to index.php
I have checked my code, menu links, folders... I have even checked users browser settings, antivirus, firewall... But no problem.
I am not getting why it is happening. here is my session file, while submitting login details i include this file
admin_auth.php
session_start();
if(isset($_SESSION['ADMIN']))
{
$_SESSION['name'] = $_SESSION['ADMIN'];
try {
$bdd = new PDO('mysql:host=localhost;dbname=nerp', 'root', '');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
$m1 = "select * from users where username='".$_SESSION['ADMIN']."'";
$resultat = $bdd->query($m1) or die(print_r($bdd->errorInfo()));
//$m2 = mysql_query($m1) or die (mysql_error());
//$m3 = mysql_fetch_array($resultat);
$m3 = $resultat->fetch(PDO::FETCH_ASSOC);
$_SESSION['uid'] = $m3['id'];
$_SESSION['name'] = $m3['firstname'] ." ". $m3['lastname'];
$_SESSION['pos']= $m3['position'];
$_SESSION['department'] =$m3['department'];
$_SESSION['location'] =$m3['location'];
$_SESSION['password'] =$m3['password'];
$_SESSION['auth'] = md5( date('Ymd') . $_SESSION['password'] );
$_SESSION['email'] = $m3['email'];
}
else
if(!isset($_SESSION['ADMIN']) )
{
header("location:index.php");
}
login_submit.php
<?php
ob_start();
error_reporting(0);
session_start();
include("connect.php");
$user=$_POST['login_name'];
$pass=$_POST['login_password'];
$sql="SELECT * FROM users WHERE username='".$user."' AND password='".$pass."' ";
$query=mysqli_query($con, $sql) or die(mysqli_error());
$row=mysqli_fetch_array($query);
$username=$row['username'];
$count=mysqli_num_rows($query);
if($count==1)
{
$_SESSION['ADMIN']=$row['username'];
$_SESSION['name'] = $row['firstname'];
header("location:dashboard.php?user=".$_SESSION['ADMIN']."");
}
else
{
header("location:index.php");
echo "could not connect";
}
?>
is there any problem with this? . if not, why they are not able to open any links.
Based your code, and the symptom you described of those few users, it looks like those few users have disallowed cookies. So when a user with cookies disallowed goes to make a subsequent request after authenticating, they don't send the PHPSESSID cookie (here you can see an example)
So, what happens in your code is, the server sees isset($_SESSION['ADMIN']) is not set, and it drops them to the bottom of your code, which sends them back to index.php.
You can test this by disallowing cookies in your browser. A way to fix it (other than telling your users to enable cookies) is to attach some kind of ID to the URL and maintain an ID as your users move though the site. PHP can do this for you if you set:
<?php
ini_set("session.use_cookies",1);
ini_set("session.use_only_cookies",0);
ini_set("session.use_trans_sid",1);
session_start();
?>
Although I should mention this works with regular html links. It works by the PHP preprocessor adding its code to your links. Since you mentioned a menu, if your menu links are generated by javascript the PHP preprocessor won't know to add its code to the links there.

Header is not redirecting to specific page after providing user name and password

I am using header statement to redirect my user to specific page after successful or un Successful login, but the header statement is not redirecting me to that specific page. and if i see the URL i can find (#) sign instead of the specific page
Though the same code is working on other server. I have read most of the questions and tried almost all the answer on Stackoverflow.com but all in vain.
Here is my code:
if($_POST)
{
ob_start();
$office = $_POST["search_category"];
$sub_category = $_POST["sub_category"];
$password = md5($_POST["password"]);
$query = "select * from contacts where officeid = $office and Posting = '$sub_category' and password = '$password'";
$result = mysql_query($query) or die('Mistake in query');
$count = mysql_num_rows($result);
if ($count>=1)
{
$data = mysql_fetch_array($result);
$_SESSION['user'] = $data['Posting'];
$_SESSION['semenu'] = $data['semenu'];
$_SESSION['seid'] = $data['seid'];
if ($_SESSION['semenu'] == 1 or $_SESSION['semenu'] == 2)
header("location:contenrollment.php");
else
header("location:relogin.php");
exit;
ob_end_flush();
}?>
Instead of redirecting to any of the above two pages, I am redirected to a blank page and the blank page has the exact URL but only has (#) instead of file name. I have also checked the query, There is no mistake in it.
If your scripts located in root directory of site, try to use:
header("Location: /contenrollment.php");
or
header("Location: /relogin.php");

Wrong session value when reading

I have got this strange problem. I wanted to make a page which uses a Username to identify which content should be displayed. It seems to work fine, except for one thing. The wrong value is read from the session on one specific page. I have checked the session value in my browser, but there the value seems to be correct. I'll show you the code:
this is my login function, using php:
<?php
//CONNECT TO DATABASE
$db = mysqli_connect("localhost","root","MyPassword","MyDBName");
if($db->connect_errno){
die('connection error: ' . $db->connect_errno);
}
//CHECK IF LOGIN DATA IS SUBMITTED AND IS CORRECT
if(isset($_POST['action'])){
switch($_POST['action']){
case "login":
$pw = $_POST['pw'];
$loginUn = $db->real_escape_string($_POST['loginUn']);
$result = mysqli_query($db,"SELECT `Password` FROM `accounts` WHERE `Username`='" .$loginUn. "'");
if(mysqli_num_rows($result) != 0){
$dbpw = $result->fetch_object();
$VI = explode("-",$dbpw->Password);
$dbpw = openssl_decrypt($VI[1],"blowfish","",0,$VI[0]);
if($pw == $dbpw){
$login = true;
$_SESSION['login'] = true;
$_SESSION['Username'] = $_POST['loginUn'];
$un = $_POST['loginUn'];
}
}
break;
case "logout":
$_SESSION['login'] = false;
$_SESSION['Username'] = "";
break;
}
}else{
if(isset($_SESSION['login'])){
$login = $_SESSION['login'];
$un = $_SESSION['Username'];
}
}
?>
it seems to work fine, since it works in the page it is used.
I have made some dummy accounts in the database, with these usernames: Admin and User.
Here is the code of the page it went wrong:
PHP:
//THIS IS NOT THE SAME PAGE AS THE PREVIOUS PHP CODE
$login = false; //CHECK IF USER HAS LOGGED IN
$un = "";
if(isset($_SESSION['login'])){
$login = $_SESSION['login']; //IF LOGGED IN SET TO SESSION VALUE
$un = $_SESSION['Username']; //SET $UN TO USERNAME IN SESSION
}
Then I used javascript and php to alert the values which the variables contain:
<script type="text/javascript">
alert("$un = <?php echo $un;?>");
</script>
With the login variable seemed to be no problem, since it had the good value, but the variable $un was wrong. When I wasn't logged in, it had no value, which is correct, but when I was logged in, it contained the value Admin, even when I wasn't logged in with Admin. In the browser options the cookie value seemed correct. I've checked the cookie on every page, and it worked just fine, just not on this page. What am I doing wrong that makes the browser(which is firefox by the way) think that it is always Admin that is logged in?
As mentioned earlier in the comments, there are many security risks in your script.
You should take a look at PHP's sessions to build your login. Using sessions, there will be only one cookie storing an ID and all the data will be stored on your server and can't be modified by the user.
Your problem with 'Admin' staying as cookie value could be a caching problem.
I just found out what I did wrong. A piece of code which I found irrelevant, missed a = so the variable wasn't compared, but set to this wrong value.

php login script works locally but not on host

<?php
session_start();
include 'db.php';
include 'header.html';
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['email'])) {
header("location:profile.php");
} elseif(!empty($_POST['email']) && !empty($_POST['pass'])) {
$email = mysql_real_escape_string($_POST['email']);
$pass = md5(mysql_real_escape_string($_POST['pass']));
$sql = mysql_query("SELECT id, name, email, pass FROM users WHERE email='$email' AND pass='$pass'");
$row = mysql_fetch_array($sql);
$id = $row['id'];
$email1 = $row['email'];
$name = $row['name'];
$num = mysql_num_rows($sql);
if($num == 1) {
$_SESSION['id'] = $id;
$_SESSION['email'] = $email1;
$_SESSION['name'] = $name;
$_SESSION['LoggedIn'] = 1;
$update = mysql_query("UPDATE users SET lastlogin=NOW() WHERE email='$email1'");
header("location:profile.php");
} else {
echo "<h1>Error</h1>";
echo "<p>Sorry! Either your account could not be found or you have entered the wrong email or password. Please try again.</p>";
}
}
?>
This script works perfectly in my localhost environment but when uploaded to host, it does not go to the profile.php after logging in. Also, it doesn't redirect to profile.php if the session is set or not empty. Any ideas?
And second question, is my code correct for updating the 'lastlogin' to the current time? What does the database structure have to be for this? It is not updating in my database.
Thank you for your help.
your code is very ok for updating the lastlogin, but what is the error you get? please give what type of error you get on this. logically your code seems to be right, it may be some syntax error. add error_reporting(E_ALL) on top of your page and see what error is occurred actually.
header("location: profile.php");
^ //space should present because in some host environment it creates problem
If you are redirecting to the login script from a form using most likely POST, shouldn't you use $_POST[''] instead of $_SESSION?
Just a thought.
Always use exit(); after header redirection
Ok figured it out with an extensive search. The headers were already being sent with the
include header.html
line so it could not perform the
header(location: profile.php)
line. I had never heard of this issue before until now. So to resolve this issue, I just moved
<?php
...
include header.html
?>
to the bottom of the php code right before the HTML starts. Now the include header line can do it's thing and then the header will still be loaded for the page.
Thanks for all your help with this.

Recurring redirect error

I have posted a question for this a long time ago, but i still can't find a answer. Basically, when a user has logged into the account and has been inactive for a while and when they return they would click something and then the system would log them out and they would have to re-login. It works 90% of the time, but sometimes it gives an error like: This page is redirecting in a way it will never complete.
But when a user clears the cookies it works fine and sometimes closing the tab and opening up a new one works too.
Here's the code:
<?php
$SUBDOMAIN = mysql_real_escape_string($_GET['p_name']);
$pname = mysql_real_escape_string($_GET['p_name']);
echo "$p_name";
include("db.php");
?>
<?php
session_start();
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
$ugData = $_REQUEST['p_name'];
if($_POST)
{
$_SESSION['user_name']=$_POST["user_name"];
$_SESSION['password']=$_POST["password"];
}
$secret = $info['password'];
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site']))
//if there is, it logs you in and directes you to the members page
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT user_name, password FROM accounts WHERE user_name = '$username' and p_name='$ugData'")or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{
if (# $info['password'] != $pass)
{
}
else
{
header("Location: home.php");
}
}
}
//if the login form is submitted
if (isset($_POST['submit']))
{
// if form has been submitted
// makes sure they filled it in
if(!$_POST['user_name'] | !$_POST['password'])
{
die('You did not fill in a required field.');
}
//checks it against the database
if (!get_magic_quotes_gpc())
{
$_POST['user_name'] = addslashes($_POST['user_name']);
}
$check = mysql_query("SELECT user_name,password FROM accounts WHERE user_name = '".$_POST['user_name']."' and p_name='".$ugData."'")or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0)
{
die('That user does not exist in our database. <a href=add.php>Click Here to Register</a>');
}
while($info = mysql_fetch_array( $check ))
{
$_POST['password'] = md5($_POST['password']);
$_POST['password'] = $_POST['password'];
//gives error if the password is wrong
if (# $_POST['password'] != $info['password'])
{
die('Incorrect password, please try again');
}
else
{
// if login is ok then we add a cookie
$_POST['user_name'] = stripslashes($_POST['user_name']);
$hour = time() + 3600;
setcookie(ID_my_site, $_POST['user_name'], $hour);
setcookie(Key_my_site, $_POST['password'], $hour);
//then redirect them to the members area
header("Location: home.php");
}
}
}
else
{
// if they are not logged in
?>
</table>
</form>
<?php
}
?>
Hey, your code formatting is really bad no fun to read you might want to fix that. :)
I just had a quick look at it, erros occurring only 90% or sometimes hard to catch.
I saw you are using header("Location: home.php"); without any exit; at the end, which is generally a bad idea unless you intent to do so.
The function call header("Location: home.php"); will not stop the script from processing. The user might get the header and redirects and stops code from processing (depending on some php settings) but maybe some cookies get set before the user gets redirected. So try adding a exit; after your redirect header calls.
format you code
I would wager a guess that this has to due with the differing expire times of your session cookie, and the expire times you set for your ID_my_site and Key_my_site cookies. If not overridden, the default session timeout is 30 minutes (expressed as seconds in the settings - so 1,800). Your cookies are set to expire after an hour. So you could find yourself in a situation where the session has expired, but the other cookies are still present. Depending on the order / way you are checking things and then redirecting, you will encounter this situation if the user was idle for more than 30 minutes but less than 1 hour.
Since the only redirect you are performing in this code sample is the one to home.php, there is some sort of check occurring in that file, that is sending them on the never ending redirect spiral.
As an aside, that code sample really is very messy. You are assigning and reassigning the $username variable so often for example (and to seemingly different types of things - though I wouldn't know without seeing actual input), that it is no wonder you are having mystery issues. These few lines for example are redundant:
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
You're assigning $username from the session and immediately assigning it back.
From the beginning of the file:
$SUBDOMAIN = mysql_real_escape_string($_GET['p_name']);
$pname = mysql_real_escape_string($_GET['p_name']);
These two variables are assigned the same $_GET value, but it doesn't appear that $SUBDOMAIN is ever used.
And from the end of the file you are assigning the same value twice:
$_POST['password'] = md5($_POST['password']);
$_POST['password'] = $_POST['password'];
I really would encourage you to step back from your code, look at your inputs and figure out what you need to accomplish and refactor or rewrite this code entirely. With stuff like this floating around it is no wonder you have mystery bugs in your system.
Additionally, a HTTP Location header requires the URL to be absolute. You should use something like this:
$currentServerHost = $_SERVER['HTTP_HOST'];
$currentBaseURI = $currentServerHost . rtrim(dirname($_SERVER['PHP_SELF']), '/\');
header( 'Location: ' . 'http://' . $finalURI . '/home.php' );
exit;

Categories