PHP: Localhost redirected you too many times - php

I want to check in login page if one user already login in the system its go to index page. But the code i used had an error like this
localhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
and this is my code to check the user is login or not. Thanks
<?php
session_start();
include '../pages/koneksi.php';
if(isset($_SESSION['username'])){
$username = $_SESSION['username'];
$res = mysqli_query($link, "select * from tb_user where username = '$username';");
$user = mysqli_fetch_array($res);
$_SESSION['ID']=$user['ID'];
header("location: index.php");
die();
} else {
header("location: login.php");
}
?>
And this is the index file
<?php
session_start();
include '../pages/koneksi.php';
//check session udah login apa belum
if(isset($_SESSION['username'])){
$username = $_SESSION['username'];
$res = mysqli_query($link, "select * from tb_user where username = '$username';");
$user = mysqli_fetch_array($res);
$_SESSION['ID']=$user['ID'];
} else {
header("location: login.php");
}
?>

Do this... On
index.php
<?php
session_start();
include '../pages/koneksi.php';
if(!isset($_SESSION['username'])){header("location: login.php");}
?>
And on
login.php
<?php
session_start();
include '../pages/koneksi.php';
if(isset($_SESSION['username'])){header("location: index.php");}
?>
Don't add these code on same page... both code are opposite of each other.
If you add them in same page then if or else condition runs every page load....

Related

How to set session for login and logout in php?

I have created session and destroying session in logout.php but if i entered in url(http://localhost/demo/home.php)it showing loggedin.It should be redirect on index.php or display page not found.
What i am achieving- I have login section and there is no issue in that.I am able to login with my credentials and page is redirecting on home.php successfully.From home.php i have logout link and i clicked on that page is redirecting on index.php but if i entered home.php showing loggedin..
Please help me in this.
index.php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$sel_user = "SELECT * FROM admin WHERE Username='$username' and Password='$password'";
$run_user = mysqli_query($conn, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0){
echo "<script>window.open('home.php','_self')</script>";
$_SESSION['user_email']=$username;
}
else {
$msg="Username and Password is incorrect.";
}
Home.php
<h2>Home page</h2>
logout
logout.php
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
Your home.php should check if user is logged in or not. Just add if statement at the top.
Something like:
if (isset($_SESSION['user_email']) == FALSE){
header("Location: index.php");
}
also your logout.php just creates session and then checks if it's destroyed. For that you could just:
unset($_SESSION['user_email']);
and your home.php would just redirect, since this var is not declared anymore.
In your home page
if (!isset($_SESSION['user_email'])){
header("Location: index.php");
}
In your logout page
<?php
unset($_SESSION['user_email']);
header("Location: index.php");
?>
Also use mysqli_real_escape_string($conn, $variable) in your mysql request to avoid injection sql
$sel_user = "SELECT * FROM admin WHERE Username='".mysqli_real_escape_string($conn, $username)."' and Password='".mysqli_real_escape_string($conn, $password)."'";
And check the data received by your POST method before adding to the database.

PHP session resets when i refresh page

Hi i'm a noob when it comes to PHP but im making a page where after you login you go to the homepage, but when im at the homepage logged in and refreshes the page i get logged out.
Here the code for my login.
`
session_start();
require('connect.php');
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
header("Location: index.php");
}else{
echo "Invalid Login Credentials.";
and the code for my index.php
<?php
require'connect.php';
session_start();
if (!isset($_SESSION['username'])){
echo" not logged in";
}else {
echo "logged in";
}
?>
your login page has:
session_start();
require('connect.php');
whereas your home page has:
require'connect.php';
session_start();
Try to be consistent. From the manual:
"To use cookie-based sessions, session_start() must be called before outputting anything to the browser."
Make sure you're calling session_start() first, in both pages. Make sure you don't have any white space or anything else being outputted first. For example:
correct:
<?php
session_start();
incorrect:
// white space above PHP tag
<?php
session_start();
That should solve your problem.
Looks like a small issues as not much of php code is involved here.
Try running this code without
require('connect.php');
If it still doesn't get resolved, I would recommend you to check with the code in connect.php file.

Issue on Destroying - Ending Session on Logout

I have a session set up like this:
<?php
session_start();
include 'conconfig.php';
$con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$email = $_POST['email'];
$pass = $_POST['pass'];
$query = "SELECT * FROM tempusers WHERE user='$email' AND pass='$pass'";
$result = mysqli_query($con,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_assoc($result);
if( $num_row >=1 ) {
echo 'true';
$_SESSION['uName'] = $row['uName'];
}
else{
echo 'false';
}
?>
and in my logout.php I have
<?php
session_start();
session_unset();
unset($_SESSION['uName']);
session_destroy();
header("Location:index.php");
?>
but none of the session_unset(); , unset() and session_destroy(); seems to be not working because after getting to the page I am still able to use browser Back button and back to the restricted page! besides the header() is not changing the page into index.php can you please let me know what I am doing wrong and how I can fix it?
Basically, I have a Log out Link in Restricted page which is like this
<a href="logout.php" >Logout</a>
Thanks
Update:
Here is the Session code which I have at the top of restricted page
<?php
session_start();
if(empty($_SESSION['uName'])){
header('Location: login.php');
}
?>
Try regenerating the session id and destroying all the data.
<?php
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(), '', 0, '/');
session_regenerate_id(true);
header("Location:index.php");
exit();
?>

Php Session Redirect Page

Okay, What I have here is a simple php login session. Sometimes session destroy even I don't destroy the session. In my Index.php, there's a link for editing record. My problem is, if session destroy and I click edit, the page open's in modal or fancybox and shows login.php and after I login it's goes to index.html. What I need to do is instead of going into index.html, I need to redirect to edit.php with GET value to continue the edit process. Any help?
Index.php
<a class="fancybox" href="edit.php?pn='.$row["id"].'"><img src="images/edit.png"></a>
Edit.php
<?php
session_start();
include('connect.php');
$tbl_name="login_admin";
if(! isset($_SESSION['id'])){
header('location:login.php');
exit;
}
$id = $_SESSION['id'];
$sql = $mysqli->query("SELECT * FROM $tbl_name WHERE username='$id'");
$accounts = $sql->fetch_assoc();
$term= $mysqli->real_escape_string($_GET["pn"]);
?>
Login.php
<?php
require_once('connect2.php');
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$submit = $_POST['submit'];
if($username && $password){
$sql = sprintf("SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'");
$result = #mysql_query($sql);
$accounts = #mysql_fetch_array($result);
}
if($accounts){
$_SESSION['id'] = $accounts['username'];
header("location:index.html");
exit;
}elseif($submit){
$msg = 'Invalid Username or Password';
}
?>
Unfortunately you can't continue the edit process, but you can redirect user to edit page after login.
There are more ways how to to it, I will show one of them.
before redirecting user to login script, save his original URL to session (another way would be to pass it to login.php as GET parameter - don't forget validation in that way):
Edit.php:
<?php
session_start();
include('connect.php');
$tbl_name="login_admin";
if(! isset($_SESSION['id'])){
$_SESSION['original_url']=$_SERVER['REQUEST_URI']
header('location:login.php');
exit;
}
// rest of the code.....
Then redirect user to that page instead of default index.html page
Login.php:
<?php
require_once('connect2.php');
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$submit = $_POST['submit'];
// Security note: see I've sanitized $username and $password with mysql_real_escape_string() to avoid SQL injection
if($username && $password){
$sql = sprintf("SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'");
$result = mysql_query($sql);
$accounts = mysql_fetch_array($result);
}
// when account was found store identity to session
if($accounts){
$_SESSION['id'] = $accounts['username'];
if (isset($_SESSION['original_url']) {
// if user came from internal url, redirect to it and remove it from session
$originalUrl = $_SESSION['original_url'];
unset($_SESSION['original_url']);
header("location:".$originalUrl);
exit;
} else {
// redirect user to default page after login
header("location:index.html");
exit;
}
} elseif($submit){
// login form was sent, but user with given password not found
$msg = 'Invalid Username or Password';
}
?>

if is not session , redirect to login page

I am trying to code a simple script,
I created a " ADMIN Panel " , so if the user is admin (admin=1) then he can pass and see the link/file
If he is not (admin=0) then he should be redirected to login page , and if is not Session['username'] he should go back to login page ,
but it seems that i have a problem with this code, in user panel it works , but in admin panel it doesn't
<?php
include './includes/db.php';
session_start();
// ADMIN CHECk
$username = mysql_real_escape_string($_SESSION['username']);
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND admin=1");
$count = mysql_num_rows($result);
if($count != 1) // make sure user is a admin
{
session_start();
session_destroy();
header("location: login.php");
die;
}
if(isset($_GET['act']))
{
if($_GET['act'] == "logout")
{
session_start();
session_destroy();
header("location: login.php");
}
}
?>
Ok, first thing i see is that you don't declare the session first. Secondly, the mysql function is deprecated, mysqli will do what you need done. This fix should work for you. Also it would be easier to have a logout.php.
db.php
<?php
$db = new mysqli(host, user, pass, database);
?>
Then, in your page, you can run the queries like so:
<?php
session_start();
include './includes/db.php';
//check that the session exists
if(!isset($_SESSION['username'])
{
//the session does not exist, redirect
header("location: login.php");
}
// ADMIN CHECk
$username = $db->real_escape_string($_SESSION['username']);
$result = $db->query("SELECT * FROM users WHERE username='$username' AND admin='1'");
$count = $result->num_rows;
if($count != 1) // make sure user is a admin
{
header("location: login.php");
}
?>
Then in logout.php, you should remember to actually unset the session variables
<?php
session_start();
//unset session variables
unset($_SESSION['username']);
session_destroy();
header("location: login.php");
?>

Categories