I have followed this tutorial in order to build a login system for a content management site. http://www.formget.com/login-form-in-php/. I would like the site to be set in such a way that the user needs to be logged in in order to view the site, and that if the user enters the site name thru the url, they are directed immediately to the login page.
Currently when I go directly to the page I get an error stating:
Notice: Undefined index: login_user in C:\xampp\htdocs\WebDevelopment\V18\CMS\session.php on line 6
FILES USED:
login.php
<?php
session_start();
$error = ''; // variable to store error message
if (isset($_POST['login'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else {
// Define username and password
$username = $_POST['username'];
$password = $_POST['password'];
$connection = mysql_connect("localhost", "root", "");
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// select DB
$db = mysql_select_db("v18_apartments", $connection);
$query = mysql_query("Select * from login where password = '$password' AND username = '$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // initializing session
header("location: CMS-home.php");
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection);
}
}
?>
index.php
<?php
include ('login.php');
if (isset($_SESSION['login_user'])){
header("location: CMS-home.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> V18 - Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="format-detection" content="telephone=no">
<link rel="stylesheet" type="text/css" href="css/styles.css"/>
</head>
<body>
<div id="wrapper">
<div class="center">
<div id="login-form">
<form action="" method="POST">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="********">
<button type="submit" name="login">Submit</button>
<h2><?php echo $error; ?></h2>
</form>
</div>
</div>
</div>
</body>
</html>
session.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("v18_apartments", $connection);
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql=mysql_query("select username from login where username = '$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session = $row['username'];
if (!isset($login_session)) {
mysql_close($connection);
header('Location : index.php');
}
?>
logout.php
<?php
session_start();
if (session_destroy()) // destroy all sessions
{
header("Location: index.php");
}
?>
How about this?
session.php
<?php
session_start();
if(!isset($_SESSION['login_user']))
header('Location : index.php');
exit;
?>
Related
i had some problems with this code, seen some guides and arrived to this. I just started php few days ago. How exactly do you do a search of database, then compare the user input to the database username and password?
the $sqlQuery i left it empty for the sql search and maybe someone can explain what you call the "->" symbol in the loop?
I allready managed to understand and do a sign up but the tutorials never explain exactly what is going and just type.
Thanks.
<?php
include 'db.php';
include 'info.php';
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$sqlQuery = '';
$result = mysqli_query($connection,$sqlQuery);
if($result->num_rows > 0){
session_start();
echo 'welcome';
}else{
echo 'failed';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Log In</title>
</head>
<body>
<form action="login.php">
Username: <input type="text" name="username">
Username: <input type="password" name="password">
<input type = "submit" value = " Submit "/><br />
</form>
</body>
</html>
PHP PDO login with session - It's secure
index.php,general message.php, logout.php, site life.php (this page for session and put it in the other pages by required)
Database:
connection.php
<?php
$dsn = "mysql:host=localhost;dbname=mg";
$username = "root";
$password = "";
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try{
$conn = new PDO($dsn,$username,$password,$options);
} catch (PDOException $e){
echo "Error!".$e->getMessage();
}
?>
index.php:
<?php
session_start();
if(isset($_SESSION['user'])){
header("location: general message.php");
}
require "connection.php";
if(isset($_POST['login'])){
$user = $_POST['username'];
$pass = md5($_POST['password']);
$messeg = "";
if(empty($user) || empty($pass)) {
$messeg = "Username/Password con't be empty";
} else {
$sql = "SELECT username, password FROM users WHERE username=? AND
password=? ";
$query = $conn->prepare($sql);
$query->execute(array($user,$pass));
if($query->rowCount() >= 1) {
$_SESSION['user'] = $user;
$_SESSION['time_start_login'] = time();
header("location: general message.php");
} else {
$messeg = "Username/Password is wrong";
}
}
}
?>
Site life.php (and I will put it in the the other pages by require "site life.php")
//The lives of session is one hour 60*60=3600
<?php
session_start();
if(isset($_SESSION['user'])){
if((time() - $_SESSION['time_start_login']) > 3600){
header("location: logout.php");
} else {
$_SESSION['time_start_login'] = time();
}
} else {
header("location: logout.php");
}
?>
logout.php
<?php
session_start();
session_destroy();
header("location: index.php");
?>
General message.php I put this in the header (to make a refresh every hour):
// 60*60=3600 one hour
<meta http-equiv="Refresh" content="3600" >
<?php
require ('site life.php');
?>
The -> is an object operator. so you can access attribute num_rows from $result.
This is the naive example (vulnerable to SQL injection) to give you an idea, it works.
<?php
include 'db.php';
include 'info.php';
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$sqlQuery = "SELECT * FROM user WHERE username = '$username' and password = '$password'";
$result = mysqli_query($connection,$sqlQuery);
if($result->num_rows > 0){
session_start();
echo 'welcome';
}else{
echo 'failed';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Log In</title>
</head>
<body>
<form action="login.php">
Username: <input type="text" name="username">
Username: <input type="password" name="password">
<input type = "submit" value = " Submit "/><br />
</form>
</body>
</html>
login.php
I just want to prevent the user after the user logout and press the back button he will still logout... in the current state of my project after the user logout and press back button he will go back in the last page and still log in
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=MS932">
<title>Login Page</title>
<link rel ="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id ="frm">
<form action="process.php" method="post" >
<p>
<label>Username:</label>
<input type="text" id="email" name="user" required/>
</p>
<p>
<label>Password:</label>
<input type="password" id="pass" name="pass" required/>
</p>
<p>
<input type="submit" id="btn" value="Login"/>
</p>
</form>
</div>
</body>
process.php
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
mysql_connect("localhost","root","");
mysql_select_db("testproduct");
$result = mysql_query("SELECT * FROM tbluser where email = '$username' and pass='$password'")or die("Failed to query database".mysql_error());
$row = mysql_fetch_array($result);
if($row['email'] == $username && $row['pass'] == $password){
echo "<script>window.location.assign('index.php');</script>";
}else{
echo "<script>alert('Login was unsuccessful, please check your username and password')</script>";
echo "<script>window.location.assign('login.php');</script>";
return false;
}
?>
logout.php
<?php
session_start();
session_destroy();
$_SESSION = array();
header("location: login.php");
?>
Initialize session variable on user login and destroy it on logout. Everytime you go to index.php, you check if that session variable exists or there is a successful login.
http://php.net/manual/en/ref.session.php
process.php
<?php
session_start();
$username = $_POST['user'];
$password = $_POST['pass'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
mysql_connect("localhost","root","");
mysql_select_db("testproduct");
$result = mysql_query("SELECT * FROM tbluser where email = '$username' and pass='$password'")or die("Failed to query database".mysql_error());
$row = mysql_fetch_array($result);
if($row['email'] == $username && $row['pass'] == $password){
$_SESSION['un'] = $username;
echo "<script>window.location.assign('index.php');</script>";
}else{
echo "<script>alert('Login was unsuccessful, please check your username and password')</script>";
echo "<script>window.location.assign('login.php');</script>";
return false;
}
?>
index.php
<?php
session_start();
if(!isset($_SESSION['un'])){
header("location:login.php");
}
...
?>
When I hit my submit button to login nothing happens. I am just getting the same page, and not even an error. The connection to db should be fine. I have been looking at the code for 10 hours now, and I cannot figure out why. Does anybody have an idea?
dbconfic.inc.php:
<?php
$db_host = "localhost";
$db_user = "root";
$db_pass = "root";
$db_name = "testdb";
// connection:
$mysqli = new mysqli($db_host, $db_user, $db_pass , $db_name);
// tjek conenction:
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
// vi kører utf-8 på connection:
$mysqli->set_charset("utf-8");
?>
index.php:
<?php
include('login.php'); // Include Login Script
if(isset($_SESSION['username']))
{
header('Location: home.php');
}
exit();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Login Form with Session</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1>PHP Login Form with Session</h1>
<div class="loginBox">
<h3>Login Form</h3>
<br><br>
<form method="post" action="">
<label>Username:</label><br>
<input type="text" name="username" placeholder="username" /><br><br>
<label>Password:</label><br>
<input type="password" name="password" placeholder="password" /> <br><br>
<input type="submit" value="Login" />
</form>
<div class="error"><?php echo $error;?></div>
</div>
</body>
</html>
login.php:
<?php
session_start();
include("dbconfic.inc.php"); //Establishing connection with our database
$error = ""; //Variable for storing our errors.
if(isset($_POST["submit"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$error = "Both fields are required.";
}else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect from MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
//Check username and password from database
$sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
//If username and password exist in our database then create a session.
//Otherwise echo error.
if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $login_user; // Initializing Session
header("location: home.php"); // Redirecting To Other Page
}else
{
$error = "Incorrect username or password.";
}
}
}
?>
home.php:
<?php
include("check.php");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1 class="hello">Hello, <em><?php echo $login_user;?>!</em></h1>
<br><br><br>
Logout?
</body>
</html>
check.php:
<?php
include('dbconfic.inc.php');
session_start();
$user_check=$_SESSION['username'];
$sql = mysqli_query($db,"SELECT username FROM users WHERE username='$user_check' ");
$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);
$login_user=$row['username'];
if(!isset($user_check))
{
header("Location: index.php");
}
?>
logout.php
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
The index page seems more or less ok, a minor alteration to the use of isset and the inclusion of the login.php script.
The check.php does an extra db lookup - you should be able just to use the session info to judge whether or not to redirect the user - so rather than echo $login_user in the html use $_SESSION['username']
In the login.php script use prepared statements if possible to help mitigate against sql injection, and if possible avoid hashing passwords with md5!
<?php
$error='';
if( !isset( $_SESSION ) ) session_start();
if( !isset( $_SESSION['username'] ) ) include( login.php' );
else exit( header('Location: home.php') );
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<title>PHP Login Form with Session</title>
<link rel='stylesheet' href='style.css' type='text/css' />
</head>
<body>
<h1>PHP Login Form with Session</h1>
<div class='loginBox'>
<h3>Login Form</h3>
<br><br>
<form method='post' action=''>
<label>Username:</label><br>
<input type='text' name='username' placeholder='username' /><br><br>
<label>Password:</label><br>
<input type='password' name='password' placeholder='password' /><br><br>
<input type='submit' name='submit' value='Login' />
</form>
<div class='error'><?php echo $error;?></div>
</div>
</body>
</html>
<?php
/* login.php */
$error = '';
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submit'], $_POST['username'], $_POST['password'] ) ) {
if( empty( $_POST['username'] ) || empty( $_POST['password'] ) ){
$error = 'Both fields are required.';
}else {
/*
Use prepared statements - mitigates agsint sql injection.
Use placeholders in the sql which are used by the `bind_param` statement
*/
$sql='select `uid` from `users` where `u_username`=? and `password`=? limit 1';
$stmt=$db->prepare( $sql );
if( !$stmt ) exit('Failed to prepare sql statement');
/*
md5 is not recommended for password hashing as it is generally considered to be broken
bind the variables to the placeholders & execute the sql
*/
$username=$_POST['username'];
$password=md5( $_POST['password'];
$stmt->bind_param('ss', $username, $password ) );
$res=$stmt->execute();
/* bind the result of the query to a variable */
$stmt->bind_result( $login_user );
while( $stmt->fetch() ){
/* go through recordset ( 1 record ) */
$_SESSION['username'] = $login_user;
}
$stmt->close();
$db->close();
if( isset( $_SESSION['username'] ) ) exit( header( 'location: home.php' ) );
else $error='Incorrect username or password.';
}
}
?>
<?php
/* home.php */
if( !isset( $_SESSION ) ) session_start();
if( !isset( $_SESSION[ 'username' ] ) ) exit( header('Location: index.php') );
#include("check.php"); /* serves no real purpose once session is set */
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1 class="hello">Hello, <em><?php echo $_SESSION['username'];?>!</em></h1>
<br><br><br>
Logout?
</body>
</html>
Database:
<?php
$db_host = "localhost";
$db_user = "root";
$db_pass = "root";
$db_name = "testdb";
// connection:
$mysqli = new mysqli($db_host, $db_user, $db_pass , $db_name);
// tjek conenction:
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
// vi kører utf-8 på connection:
$mysqli->set_charset("utf-8");
?>
Index:
<?php
session_start();
if(isset($_SESSION['username']))
{
header('Location: home.php');
}else{
include('login.php');
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Login Form with Session</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1>PHP Login Form with Session</h1>
<div class="loginBox">
<h3>Login Form</h3>
<br><br>
<form method="post" action="index.php">
<label>Username:</label><br>
<input type="text" name="username" placeholder="username" /><br><br>
<label>Password:</label><br>
<input type="password" name="password" placeholder="password" /> <br><br>
<input type="submit" name="dologin" value="Login" />
</form>
<div class="error"><?php echo $error;?></div>
</div>
</body>
</html>
?>
Login:
<?php
include("dbconfic.inc.php"); //Establishing connection with our database
$error = ""; //Variable for storing our errors.
if(isset($_POST["dologin"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$error = "Both fields are required.";
}else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect from MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
//Check username and password from database
$sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
//If username and password exist in our database then create a session.
//Otherwise echo error.
if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $login_user; // Initializing Session
header("location: index.php"); // Redirecting To Other Page
}else
{
$error = "Incorrect username or password.";
}
}
}
?>
HOME:
<?php
include("check.php");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1 class="hello">Hello, <em><?php echo $login_user;?>!</em></h1>
<br><br><br>
Logout?
</body>
</html>
Check:
<?php
session_start();
include('dbconfic.inc.php');
$user_check=$_SESSION['username'];
$sql = mysqli_query($db,"SELECT username FROM users WHERE username='$user_check' ");
$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);
$login_user=$row['username'];
if(!isset($user_check))
{
header("Location: index.php");
}
?>
I'm trying out a login page example in php. I get the error: This webpage has a redirect loop
Details say: Error code: ERR_TOO_MANY_REDIRECTS
Here's my code:
index.php
<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
login.php
<?php
session_start();
$error='';
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
$username=$_POST['username'];
$password=$_POST['password'];
$connection = mysql_connect("localhost", "root", "");
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$db = mysql_select_db("rjtest", $connection);
$query = mysql_query("select * from login where myPassword='$password' AND myUserName='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username;
header("location: profile.php");
} else {
$error = "Username or Password is invalid";
}
}
}
?>
profile.php
<?php
include('session.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<b id="logout">Log Out</b>
</div>
</body>
</html>
session.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("rjtest", $connection);
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql=mysql_query("select myUsername from login where myUsername='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
header('Location: index.php');
}
?>
And logout.php
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
I can't seem figure out why. The site where I got this code is now inactive, so that's why Im asking this here. Hope you guys could help me out. Sorry for the long post though.
Comment to answer:
What I think is going on is that your code is erroring out and you're not seeing it, causing it to fight against what it should be showing you as an error.
You have $login_session =$row['username']; using the "username" as the row, but you're not selecting it in your query select myUsername from login where myUsername.
So, I'm thinking that if that row doesn't in fact exist, you'd need to do
$login_session =$row['myUsername'];
I have just setup Apache and Mysql on my server and trying to create a website with a session based login system. I have followed the tutorial from this link: http://www.formget.com/login-form-in-php/
Everything seems fine except when testing the login. Once I have entered a correct username and password combination it fails to login succesfully as Chrome shows an error as such
I do not have an .htaccess file on my server, and I am sure the login details are correct as the URL shown on the address bar is pointing to the dashboard page (profile.php according to the tutorial) supposed to be shown on a successful login.
The source code for the login.php page where the querying of the database is done is as follows:
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("company", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from login where password='$password' AND username='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
The login page (index.php) is as follows:
<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h1>PHP Login Session Example</h1>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>
When trying to login using Internet Explorer, IE gets stuck on trying to load the next page (just shows the waiting message with the loading icon).
I have chmod my files based on the link: http://fideloper.com/user-group-permissions-chmod-apache
(replaced /var/www with /var/www/html where all my files are at).
EDIT: Code for profile.php (and session.php)
<?php
include('session.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<b id="logout">Log Out</b>
</div>
</body>
</html>
session.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// Selecting Database
$db = mysql_select_db("company", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>