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.
Related
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();
}
}
?>
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?
I have one problem with my logout.php . Problem is second time logout. For example, a user has two accounts on my website. User loged in with the first account and then he click loged out it is ok. But when he logged in with the second account then he click loged out logout.php does not work. Can you help me here please..
Here is my session.php
<?php
$session_uid=$_SESSION['uid'];
// Session Private
if(!empty($session_uid))
{
$uid=$session_uid;
$login='1';
}
else if($_GET['username'] || $_GET['msgID'])
{
$uid=$Wall->User_ID($username);
$login='0';
}
else
{
$url=$base_url.'index.php';
header("location:$url");
}
?>
And here is Login.php code:
<?php
ob_start("");
error_reporting(0);
include_once 'includes/db.php';
include_once 'includes/User.php';
session_start();
$session_uid=$_SESSION['uid'];
if(!empty($session_uid))
{
header("location:main.php");
}
$User = new User();
//Login
$login_error='';
if($_POST['user'] && $_POST['passcode'] )
{
$username=$_POST['user'];
$password=$_POST['passcode'];
if (strlen($username)>0 && strlen($password)>0)
{
$login=$User->User_Login($username,$password);
if($login)
{
$_SESSION['uid']=$login;
header("Location:main.php");
}
else
{
$login_error="<span class='error'>Wrong password or username!</span>";
}
}
}
//Registration
$reg_error='';
if($_POST['email'] && $_POST['username'] && $_POST['password'] )
{
$email=$_POST['email'];
$username=$_POST['username'];
$password=$_POST['password'];
if (strlen($username)>0 && strlen($password)>0 && strlen($email) )
{
$reg=$User->User_Registration($username,$password,$email);
if($reg)
{
$_SESSION['uid']=$reg;
header("Location:main.php");
}
else
{
$reg_error="<span class='registererror'>Username or Email is already exists.</span>";
}
}
}
?>
And logout.php code:
<?php
error_reporting(0);
session_start();
$_SESSION['uid']='';
if(session_destroy())
{
$url=$base_url.'index.php';
//header("Location: $url");
echo "<script>window.location='$url'</script>";
}
?>
Because you decided to do echo "<script>window.location='$url'</script>"; instead of header("Location: $url"); your logout.php is being cached in the browser. So on the second click, its not even hitting the server.
You should do the redirect on the server-side, not in Javascript. If (1) you don't print anything, (2) you only return the location header, (3) you do the redirect regardless of whether session_destroy() returns true or false, then the browser should not cache this page, and you should not have this problem.
Of course the page being redirected to could also have been cached, so set no-cache headers on pages that should be protected by the login so that a cached version will not be displayed by the browser when the user is logged out.
I have tested my login by using the following script on my index.php file,
<?php
include 'core/init.php';
?>
<html>
<?php
if (isset($_SESSION['user_id'])) {
echo 'logged in';
} else {
echo 'Not Logged In';
}
?>
So at first the page displays, 'not logged in' but when email and password is entered correctly the page is supposed to redirect to the index.php page. But instead I am getting a blank page when running the login.php file. I have to manually change the page back to index.php, where then it says 'logged in'.
Heres my Login.php script:
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$email = $_POST['email'];
$password = $_POST['password'];
if (empty($email) === true || empty($password) === true) {
$errors[] = 'You need to enter a email and password';
} else if (user_exists($email) === false) {
$errors[] = 'We can\'t find that email. Have you registered?';
} else if (user_active($email) === false) {
$errors[] = 'You haven\'t activated your account!';
} else {
if (strlen($password) > 32) {
$errors[] = 'Password too long';
}
$login = login($email, $password);
if ($login === false) {
$errors[] = 'That email/password combination is incorrect';
} else {
$_SESSION['user_id'] = $login;
header('Location: Index.php');
exit();
}
}
print_r($errors);
}
?>
My Login.php file includes another file called init.php which I start the session;
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
?>
An update, I have created a logout.php file to log the user out which redirects to the index.php file. Logout.php
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
PS - I am new to PHP ad there may be a small error I am overlooking, any feedback or comments are welcome. Thanks (Y)
A couple of things about your code:
It doesn't seem you are starting the session anywhere.
I would recommend against using file names like Index.php, use index.php instead (just an advice, not necessarily a problem)
Does the url change in the browser? I mean is the redirect taking effect, but redirect to a non existing/blank page, or the url remains the same? If remains the same means your code never hit's the redirection, if it changes means the Index.php doesn't exists.
UPDATE!
In case of successfully login you are redirecting, but in case of errors you are not showing the errors.
At the end of login.php do a print_r($errors), to see them.
The redirect probably doesn't happen, because the authentication failed.
hi I have a login system for my admin section that i have a problem with, the problem is that the first time the user attempts to login, the $_SESSION isn't passed to the target page,
on the second attempt it works fine, this is what is called on the login page
$membership = new Membership();
if($_POST && !empty($_POST['username']) && !empty($_POST['pwd'])) {
$response = $membership->validate_User($_POST['username'], $_POST['pwd']);
}
in the class memebership
function validate_user($un, $pwd) {
$ensure_credentials = $this->verify_Username_and_Pass($un, $pwd);
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION['id'] = $ensure_credentials;
header("location: ambassadorUpdate.php");
die;
} else return "Please enter a correct username and password";
}
i've checked the code when i don't then send to ambassadorUpdate and the SESSION is set however if i use the header to redirect to page then the first time the SESSION is not
there is a session_start on both pages,
the code runs fine when all the pages where in the same folder, however i am getting this problem when i have organised them in a separate admin folder however all of the files are included correctly,
any ideas greatly appreciated many thanks
Try to modify:
$membership = new Membership();
if($_POST && !empty($_POST['username']) && !empty($_POST['pwd'])) {
$response = $membership->validate_User($_POST['username'], $_POST['pwd']);
}
if ($response == true){
header("location: ambassadorUpdate.php");
} else echo "Please enter a correct username and password";
in the class memebership
function validate_user($un, $pwd) {
$ensure_credentials = $this->verify_Username_and_Pass($un, $pwd);
if($ensure_credentials) {
echo 'workied';
$_SESSION['status'] = 'authorized';
$_SESSION['id'] = $ensure_credentials;
echo $_SESSION['status'] . $_SESSION['id'];
return = true;
} else return false;
}
I can't create an comment, so i write an answer.
Have you check session_start() in ambassadorUpdate.php. Does your browser accept cookies?
If not, it is usefull to use "location: ambassadorUpdate.php".?SID or you can use session_name()=session_id() instead of SID
Hope this helps.