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.
Related
I managed to develop a login page (index.php) which correctly redirects to another php page (welcome.php).
My goal is to prevent users to access welcome.php page if not logged in.
I already followed suggestions of other users, here's part of code:
Index.php
<?php
include("settings/dbConfig.php");
if (!isset($_SESSION))
session_start();
if($_SESSION['login_user'])
header("location: php/welcome.php");
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myemail = mysqli_real_escape_string($db,$_POST['email']);
$mypassword = mysqli_real_escape_string($db,$_POST['pass']);
$sql = "SELECT id FROM users WHERE email = '$myemail' and password = md5('$mypassword');";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1
if($count == 1) {
$_SESSION['login_user'] = $myusername;
header("location: php/welcome.php");
}
else {
$error = "Login Failed... Please retry";
}
}
?>
Welcome.php
<?php
session_start();
if(!isset($_SESSION['login_user'])){
header("location: logout.php");
die();
}
?>
Login works good, if I try to access welcome.php page without having logged in I get immediately redirected to index.php page and that's good too.
Problem is: I get redirected to index.php even if I correctly log in with valid credentials.
I expect to be redirected back to index.php only if I'm not logged in and to be redirected to welcome.php if I'm logged in.
How should I modify provided code in order to achieve that?
try
<?php
session_start();
if(isset($_SESSION['login_user']))
header("location: php/welcome.php");
else
header("location: php/index.php");
?>
This might be a solution, but you better learn about prepared statements and PHP built-in functions for security reasons as suggested in comments.
Managed to solve problem, was easier than expected.
Issue was on line : $_SESSION['login_user'] = $myusername;
Since $myusername doesn't exists, of course session variable won't exist too.
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.
I've been following some tutorials and managed to get my login and logout scripts working. What I"m now trying to do it get it to only allow access to pages when the user is logged in. Right now it's just redirecting users to the login page every time, which tells me that the session isn't being set or or my code is just wrong (and I've tried everything I can think of)
This is the login.php script that my form runs in order to set the session:
<?php
// establishing the MySQLi connection
require 'init.php';
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established: " . mysqli_connect_error();
}
// checking the user
if(isset($_POST['login'])) {
$username = mysqli_real_escape_string($conn,$_POST['username']);
$pass = mysqli_real_escape_string($conn,$_POST['password']);
$sel_user = "select * from login where username='$username' AND password='$pass'";
$run_user = mysqli_query($conn, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0) {
$_SESSION['username']=$username;
echo "<script>window.open('index.php','_self')</script>";
} else {
echo "<script>alert('Sorry. Your username or password is not correct, try again!')</script>";
}
}
?>
And this is what I'm including at the top of every page:
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: account-login.php");
}
require 'init.php';
?>
I switched the login.php file from directing to a page to a popup telling me that I logged in and I get the popup, so the user and password are registering fine, it's just not storing the session somehow. Any ideas? Thanks!
OK, so I got it to work finally!
Apart from all the comments (which helped a TON), I also decided to change the name I was setting in $_SESSION. I think it may be because the session name matched the name or POST data and that eas causing a conflict somewhere.
Changed this:
$_SESSION['username']=$username;
Which I think conflicted to this:
$_SESSION['session_id']=$username;
Worked!
THANK YOU!!!!!!!
Hey guys I'm creating a simple login script. When I enter a valid username and password, the function calls login_success.php but nothing happens. I've used the following links for resources:
http://www.phpeasystep.com/phptu/6.html
http://forum.codecall.net/topic/44787-creating-loginregistration-forms-with-php/#axzz2DwhIYfzj
http://frozenade.wordpress.com/2007/11/24/how-to-create-login-page-in-php-and-mysql-with-session/
I've also searched a number of posts on this site as well. Your help is always appreciated. Here's the code:
login.php
<?php
ob_start();
include 'connect.php';
$usernamefield = $_POST['usernamefield'];
$passwordfield = $_POST['passwordfield'];
$sql = "SELECT * FROM login WHERE username = '$usernamefield' and password = '$passwordfield'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1) {
session_register("usernamefield");
session_register("passwordfield");
header("Location: login_success.php");
} else {
echo "Invalid username or password";
}
exit();
?>
login_success.php
<?php
session_start();
if(!session_is_registered(myusername)){
header("Location: login.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>
Put session_start(); at the top of your login.php file.
Set session variables using $_SESSION['variable']='value';.
Check access using if(isset($_SESSION['variable'])){ and that should get it done.
The session_register('variable'); is deprecated and should not be used, along with session_is_registered('variable'): http://php.net/manual/en/function.session-register.php
If you are trying to get this to work in a new PHP installation, you could possibly be using 5.4.x, and those functions have been removed, so they do not work.
I'm trying to make a website in which the admin can upload books through an admin portal. I've made a successful login but when the user gets logged in and presses the back button (on the browser) the form page appears again, and the same happens when they log out and press back button, the page that should appear only appears after they login again. I searched a lot on the internet but all in vain. Please make a suggestion about it.
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password) {
$connect = mysqli_connect("localhost", "root", "") or die ("Could'nt connect to database!"); //database connection
mysqli_select_db($connect, "mahmood_faridi") or die ("Could'nt find database");
$query = ("SELECT * FROM user WHERE username= '$username'");
$result = mysqli_query($connect, $query);
$numrows = mysqli_num_rows($result);
if ($numrows !== 0) {
while ($row = mysqli_fetch_assoc($result)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password == $dbpassword) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header('location: help.php'); //another file to send request to the next page if values are correct.
exit();
} else {
echo "Password Incorrect";
}
exit();
} else {
die("That user doesn't exists!");
}
} else {
die("Please enter a username and password");
}
?>
On the login screen, in PHP, before rendering the view, you need to check if the user is already logged in, and redirect to the default page the user should see after logged in.
Similarly, on the screens requiring login, you need to check if the user is not logged in and if not, redirect them to the login screen.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
}
You can conditionally add Javascript code to go forward to the intended page.
<script>
history.forward(1);
</script>
This might be annoying or fail when Javascript is not present and/or disabled.
index.php page you should need to add the code in the top of a php file....
<?php
include 'database.php';
session_start();
if (isset($_SESSION['user_name'])) {
header('location:home');
}
if (isset($_POST['submit'])) {
$user = $_POST['user_name'];
$password = $_POST['password'];
$query = "select count(*) as count from users where user_name= '$user' and password = '$password';";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($result)) {
$count = $row['count'];
if ($count == 1) {
$_SESSION['user_name'] = $user;
header('location:home');
}
}
}
?>
This is another page. home.php page you should need also to add the code in the top of a php file to check it first.
<?php
include 'database.php';
if (!(isset($_SESSION['user_name']))) {
header('location:index');
}
?>
I am just modifying #sbecker's answer, use exit() after redirecting.
I have faced the same issue, but now exit(); works for me.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
exit();
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
exit();
}
you can use this it's easy to use
<?php
if(empty($_SESSION['user_id'])){
header("Location: login.php");
}
else{
header("Location: dashboard.php");
}
?>
My suggestion: the login should happen when the users clicks some link/button
Once the login server side takes place, use the the php function header('url') to redirect the user to the url it should be. (be careful not to echo anything otherwise the redirect will not happen)
[Edit] You say you have the first login file an html one, that is fine to me, but you say it redirects to whatever, then you are using a redirect from client side. In my opinion you should not use that client side redirect for the login. Probably that is causing the confusion.