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';
}
?>
Related
I have built a login php form for an internal website I'm building for our intranet. I am going to combine a few different websites together under one login system. I want to see how I could check if a user is logged in if they visit one of the url's directly and if they're not logged in then redirect them to the login page then after successfully logging in redirect back to the initial page.
I have logged their username and password into a cookie. I know this isn't secure, but again this is just an in house website on the companies intranet. So I don't need much security. The log in system is to just track what each user is doing.
Here's my login code, but now I need to figure out how to check if a user is logged in or not on separate web pages.
//get info from login form
if(isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = $_POST['rememberme'];
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
//query users table
$query = "SELECT * FROM users WHERE username = '{$username}' ";
$select_user_query = mysqli_query($connection, $query);
if(!$select_user_query) {
die("Query failed" . mysqli_error($connection));
}
//loop through user info and assigning to variables
while($row = mysqli_fetch_array($select_user_query)) {
$db_id = $row['user_id'];
$db_username = $row['username'];
$db_password = $row['user_password'];
$db_firstname = $row['user_firstname'];
$db_lastname = $row['user_lastname'];
$db_role = $row['user_role'];
}
//validate username and password
if($username === $db_username && $password === $db_password) {
//create cookie to remember user
if(isset($rememberme)) {
//set cookie to last one year
setcookie('username', $_POST['username'], time()+60*60*24*365, '/', 'localhost');
setcookie('password', md5($_POST['user_password']), time()+60*60*24*365, '/', 'localhost');
} else {
//cookie expires when browser closes
setcookie('username', $_POST['username'], false, '/', 'localhost');
setcookie('password', md5($_POST['user_password']), false, '/', 'localhost');
}
//if user exists send to dashboard
$_SESSION['username'] = $db_username;
$_SESSION['user_firstname'] = $db_firstname;
$_SESSION['user_lastname'] = $db_lastname;
$_SESSION['user_role'] = $db_role;
header("Location: ../dashboard.php ");
} else {
header("Location: ../index.php");
}
}
Here is how to check if a user is logged in and then redirect them to the page they first visited.
First check to see if a user is logged in:
<?php
session_start();
if(!(isset($_SESSION['username'])))
{
header("Location: index.php");
}
?>
Then include that file in all of your web pages you will be using. Also, create a session for the URL. This will go at the top of your page:
<?php include "includes/login-check.php"; ?>
<?php $_SESSION['url'] = $_SERVER['REQUEST_URI']; ?>
<?php ob_start(); ?>
Then right in the body of the HTML add this:
<input type="hidden" name="redirurl" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />
Then within your login file check for the URL session:
//check to see what page user first visited
if(isset($_SESSION['url'])) {
$url = $_SESSION['url'];
} else {
$url = "../index.php";
}
//redirect user to page they initially visited
header("Location: $url");
That should fully answer your question.
Create a file which you should include at the top in every file of your system and add the following code
session_start();
if(!(isset($_SESSION['username'])))
{
header("Location:login.php")
}
Please help me. I got this error everytime I tried to login. - "This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS"
Please help me and I'll appreciate your help very much. thanks.
This is my index.php
<?php
include('login.php'); // Includes Login Script
?>
This is my login.php
<?php
session_start();
$error = "";
if (isset($_POST['submit'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$usernameLogin = $_POST['email'];
$passwordLogin = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "apple", "Apple318992");
// To protect MySQL injection for Security purpose
$username = stripslashes($usernameLogin);
$password = stripslashes($passwordLogin);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("TS", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from Users where password='$password' AND email='$usernameLogin'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user'] = $usernameLogin; // Initializing Session
} else {
$error = "Username or Password is invalid";
}
}
}
if (isset($_SESSION["login_user"])) {
header("Location:timesheets.php");
}
?>
This is my session.php
<?php
include ('DBConnect.php');
session_start(); // Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysql_query("select email from Users where email='$user_check'", $conn);
$row = mysql_fetch_assoc($ses_sql);
$login_session = $row['email'];
if (!isset($login_session)) {
mysql_close($conn); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
instead of : header('Location: index.php');
try to do it with javascript :
echo '< script> document.location.href="index.php"< /script>';
In your session.php you have to destroy the session because it might be set still but without that the query can find a existing user?
To unset sessions do this:
unset(); for all the session variables unset($_SESSION['login_user']); for a specific session
Please put that before redirecting to index.php.
Otherwise I don't know how to help you sorry.
Also do you have php error / debug enabled? Normally session_start(); should be at very first line in your php file if I am correct, or it throws error.
When I try to display the username of a logged-in user I get 'Welcome, 1' where 1 should be the username of the person logged in.
This is my code in the members.php. The commented out line doesn't work either.
<?php
require_once('include.php');
?>
<?php
// echo "welcome, {$_SESSION['username']}";
$user = $_SESSION['username'];
echo "Welcome $user";
?>
The user is logged in, I wonder if I've made a mistake in the check-login page.
The code for the check_login page is:
<?php
require_once('include.php');
$username = trim($_POST['user']);
$password = trim($_POST['pass']);
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM user WHERE username='$username' and password='$password';";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count !== 0){
$_SESSION['logged-in'] = true;
header("location:members.php?user=$username");
exit;
}
else {
$_SESSION['logged-in'] = false;
header("location:login_again.php");
exit;
}
?>
which redirects to the members.php page upon successful login.
Anybody have any ideas why the username is '1' everytime?
Many thanks
there needs to be a session_start() somewhere at the top of your code
<?php session_start();
require_once('include.php');
?>
<?php
// echo "welcome, {$_SESSION['username']}";
$user = $_SESSION['username'];
echo "Welcome $user";
?>
you also need to set it before accessing it with session_start at the top of this file also
if($count>0){
$_SESSION['username']=$username;
$_SESSION['logged-in'] = true;
header("location:members.php?user=$username");
exit;
}
your code is open for sql injection attacks, Use prepared statements instead
In your check_login page I don't see either session_start and the code for saving username into session so that you can retrieve it on the other page.
In check_login page please add:
session_start();
at the start and then set:
$_SESSION['username'] = $username;
so that you can retrieve and display it on the other page.
Please check following points.
Make sure you set username in the Session variable.
From your code, I do not see any line like following:
$_SESSION['username'] = $username
Without setting, you can get nothing.
If you did session_start() before using $_SESSION variable.
session_start() is required function to be called if you gonna use $_SESSION variable.
So i'm writing a simple login script and I ran into some problems. I was able to create the login.php file that works with this dashboard.php file below. Let me describe the scenario: User come into the main page, which is the login page. Enters username and password. If entered correctly user will see the output "dashboard succesfull". If entered wrongly it will redirect them to loginfailed.php. Problem is that the browser does not remember that the user has already been logged in. If I re-enter this page, it will directly goes to loginfailed.php. So my obivous n00b question here is......is there a way to make the browser remember that the user has already been logged in?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$dblink = mysql_connect("localhost", "root", "");
mysql_select_db("user",$dblink);
$sql = "select * from members where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
$count = 0;
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
echo "<a href='dashboard.php'>dashboard succesfull</a>";
} else {
$_SESSION['loggedIn'] = "false";
header("Location: loginfailed.php");
}
?>
Sure. You just need to put, at the top of the page but below session_start(), something like:
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'true') {
# do something. maybe redirect and then exit?
}
Also, I'd suggest using a session name and escaping the username and password before putting them in your SQL.
I haven't been able to trace what's wrong with this code. I am trying to login the user by taking his username and password. Here is what I am trying to do.
index.php:
This file checks if the username cookie is set and displays the file accordingly. This file submits the username and password to a file called validate.php.
validate.php:
<?php
session_start();
include("connector.php");
$var=connect();
if($var==10)
{
$valid=false;
$row= mysql_query('select * from users where username="'.$_POST["username"].'"');
if($row['password']==$_POST["password"])
$valid=true;
if($valid)
{
$_SESSION["username"]=$_POST["username"];
$_SESSION["userid"]=$row['userid'];
echo "<script>document.location.href='./session_creator.php'</script>";
}
else
{
echo "invalid";
}
}
?>
connector.php==>
<?php
$connection=0;
function connect()
{
$dbc = mysql_connect('localhost:3306','root','root');
if (!$dbc)
{
die ('Not connected:'. mysql_error());
return -10;
}
else
{
$connection = mysql_select_db("citizennet",$dbc);
if(!$connection)
{
die("Not connected: ". mysql_error());
return -20;
}
}
return 10;
}
?>
session_creator.php:
<?php
session_start();
setcookie("username",$_SESSION['username'],time()+3600);
setcookie("userid",$_SESSION['userid'],time()+3600);
echo "<script>document.location.href='./index.php'</script>";
?>
the redirected index.php file reports that the cookie is not set. I am newbie, please correct me if the process I am following is wrong.
I am adding index.php that verifies if the user is logged in:
<?php
if(!isset($_COOKIE["username"]))
echo '<a id="login_button">login</a> <div id="login_box_pane"><form action=validate.php method="post">Username: <input type="text"/> Password:<input type="password"/><input type="submit"/></form></div>';
else
echo "<a>".$_COOKIE["username"]."</a>";
?>
When you set your cookie on your page it should be like this:
<?php //login page
session_start()
$username = $_POST['username'];
$password = $_POST['password'];
/*
Check authentication with database values
*/
//if login successful set whatever session vars you want and create cookie
$_SESSION['username'] = $username;
setcookie($username, $password, time()+3600);
?>
Prior to this you will have check the users credentials and log them in or deny them. Once logged in you set the session variables. Then to create the cookie you use the code above.
$user = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string($_POST['pass']);
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
That will take care of your sql injection vulnerabilities and also get you the correct account only if both the username and password are correct
Now you can use your conditions to set the cookies and sessions