so i have done this script below to check if logged in user is not admin and redirect non-admin to 404 page, but keep admin in the same page and show him his stuff
<?php
session_start();
$username = $_SESSION['username'];
$loggedin = $_SESSION['loggedin'];
if ($username != "administrator") {
header("location: 404.php");
exit;
} else {
include 'include/usermenu.php';
}
?>
but my admin is also redirected to 404(he shouldn't be), so could anybody tell me what have i done wrong? and by the way im having just one admin, so thats why its username
To test, change your code as follows:
<?php
session_start();
$username = $_SESSION['username'];
$loggedin = $_SESSION['loggedin'];
if ($username != "administrator") {
##header("location: 404.php"); exit;
print "normally I would redirect you because username is $username ";
} else {
include 'include/usermenu.php';
}
?>
See if username is coming up as a blank or some alternate spelling?
Related
Here's my sample code for preventing user from entering the page using direct URL
<?php
ob_start();
include("../include/userlogin.php");
include('../include/database.php');
if(!isset($_SESSION))
{
session_start();
}
if($_SESSION['usertype'] != "admin"){
$_SESSION['message'] = "You cannot access only admin is allowed!";
header("location: login.php?success=1");
}
ob_end_flush()
?>
How to achieve this after the user successfully logged in, how can I prevent that user from going back to login page by clicking the back button in google chrome?
You can have another session variable to be TRUE when login is successful and false if not successful. Then you can check if the variable is true on the login page and redirect the user to the required page.
The $_SESSION container can store when a user was logged in and will be unset when not.
<?php
session_start();
if(isset($_POST["login"])){
$user = "";
$passwd = "";
if(isset($_POST["user"]))
$user = $_POST["user"];
if(isset($_POST["passwd"]))
$passwd = $_POST["passwd"];
if(stripslashes($user) == "user" &&
stripslashes($passwd) == "passwd")
{
$_SESSION["user"] = "user";
}
}
if(isset($_GET["logout"]))
session_destroy();
if(isset($_SESSION["user"]) && $_SESSION["user"] != "user")
include "internalPage.php";
else
include "loginPage.php";
Good morning/evening,
I'm stuck and I need some help in PHP.
I am trying to code up an admin dashboard. And I want to check if user is logged in, if not , redirect to the login page.
My index.php is this:
<?php
$pagename ="Index";
#require_once('inc/head.php');
?>
<body>
CONGRATS! Welcome to the Admin dashboard.
</body>
</html>
My login page:
<?php
$pagename = "login";
$adminUser = "admin";
$adminPass = "admin";
#require_once('inc/head.php');
// If POST is submitted and IDs match the ones set
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if($_POST["username"] == $adminUser && $_POST["password"] == $adminPass)
{
session_start();
$_SESSION["username"] = $adminUser;
$_SESSION["login"] = true;
echo '<script>alert("Congrats, you logged in");
window.location = "index.php"; </script>';
/* I skip the line underneath because for unknown reasons my code
Doesn't fully run through. So I redirected with the JS above instead.
header("Location: index.php");
exit(); */
}else{
echo '<script>alert("Incorrect username or password!'");</script>';
}
}
?>
<html>
<!-- login page here -->
</html>
And here goes my head.php:
<?php
// If we AREN'T on the login page , check if session exist. If not send to login
if($pagename != "login")
{ if(!$_SESSION['login'])
{
header('location: login.php');
exit();
}
}
?>
There is alot of things wrong with this and I know but as of now I'm trying to fix my login in issue. Whenever I log in I get the JS pop up that says I successfully logged in, but I don't get redirected to the index. I think I do get sent to my index.php ( there's no reason for my JS redirect to NOT function ) but my index sends me right back to login and I don't understand why.
Start Session in head.php page.
head.php
<?php
if($pagename != "login") {
session_start();
if(!$_SESSION['login']) {
header('location: login.php');
exit();
}
}
?>
I've started to learn PHP Sessions recently.That really helped me to do the login properly.
I should give the link to you first: mk-appform.net16.net/login.php(feel free to use as you want,This is a testing.Im able to change the pass as soon as it gets fixed)
Username:admin
Password:1234
Please test it
The problem is,When you're not logged in and type mk-appform.net16.net/advsearch.php directly in the adress bar,The content of the page that I require login beforehand is visible for a second.Then it redirects to login page.But you know,I would not want this to be shown in any way.It should require login eventually.
Here are the PHP codes of login.php
<?php
if (isset($_POST['submit']))
{
if(isset($_POST['user']) && isset($_POST['password']))
{
$user = $_POST['user'];
$password = $_POST['password'];
if(empty($user) || empty($password))
{
echo 'Please fill the form';
}
else
{
if($user == 'admin' && $password == '1234')
{ // check the infos
session_start();
$_SESSION['user'] = 'admin';
$_SESSION['password'] = '1234';
echo 'Login Succeeded.Now redirecting to panel...';
header("refresh:2; url=advsearch.php");
}
else
{
echo 'Invalid Username or Password';
}
}
}
else
{
echo 'Please use the form';
}
}
?>
And ,the code of the content I show after successfully logging in(advsearch.php)
<?php
session_start();
if(isset($_SESSION['user']) && isset($_SESSION['password']))
{
if($_SESSION['user'] == 'admin' && $_SESSION['password'] == '1234')
{
header("url=advsearch.php");
}
else
{
session_destroy();
echo 'Redirecting..';
}
}
else
{
header("refresh:0; url=login.php");
}
?>
header redirects aren't instantaneous. It takes a few moments for the browser to start shutting down the connection and initiate the new one. That means any content you output on the page after you output the location header can still be viewed. You have to abort your script after outputting the header. e.g.
<?php
if (need to redirect) {
header('Location: login.php');
echo 'redirecting to login page, please wait ...';
exit(); // you need this
}
... regular page contents ...
In short, if you don't want something visible to the user, then DON'T output it in the first place. Don't depend on everything working properly (or even fast). They rarely do.
I'm using $_SESSION to keep my users logged in after they have logged in.
When they return to the homepage, they at first appear to be logged in, but after refreshing the page once, they are no longer logged in.
NOTE: I'm still learning PHP programming so please don't mind that most of my code is rather, noobish.
Index.php Code:
<?php
session_start();
$UserOnline = "Guest";
if (isset($_SESSION['username'])) {
$UserOnline = $_SESSION['username'];
}
echo $UserOnline;
?>
Login.php Code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username)) {
$InvalidLogin = "Please submit a username";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
} elseif (empty($username)) {
$InvalidLogin = "Please submit a password";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
require 'required/connect.php';
$result = mysqli_query($con, "SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
if ($password == $row['password']) {
$_SESSION['username'] = $username;
echo "Successful Login!";
echo "<br>";
echo "<a href='index.php'>Return to HomePage?</a>";
} else {
$InvalidLogin = "Your info didn't match ours!";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
?>
I have tested on the login.php page if the user is in a session there, and I always get the correct return value. The issue is that after I refresh once on the Index.php page, the user is no longer in a session.
Is there something I'm forgetting, or am I not using the $_SESSION correctly? Is there another error that I simply do not know about?
Put exit; after header('location:.....') and your problem will be solved.
Issue is resolved. Error was found in Index.php. Set Variable $UserOnline before the if(isset($_SESSION['username'])). Thanks for the help guys
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.