I am having an issue with PHP, as I am trying to write a program that will redirect the user back to the previous page (membersOnly.php). Here is the code that isn't currently working for me.
$sess = $_SESSION['sess_username'];
if ($sess == "admin") {
return;
} else {
header("Location: membersOnly.php");
}
My attempt is to only allow the user "admin" into the admin.php page. This code is the first thing to run. The $_SESSION['sess_username'] variable is assigned in login.php with the following code:
session_start();
$_SESSION['sess_username'] = $_POST['user'];
header("Location: membersOnly.php");
Now I know I am correctly setting the session username, because in any page I choose, I can use echo $_SESSION['sess_username']; and it displays the username. But I am not sure what I am doing wrong when I try to send the user back to membersOnly.php if their username is not admin. Currently when I try to go to that page, it denies access to any user, including admin.
[EDIT: SOLVED]
I forgot to add session_start(); at the top of the page.
Danbopes is right, you are "returning" an empty page. You can simply do this. Now note that this code will not work unless the username "admin" is saved in the session.
$sess = $_SESSION['sess_username'];
if($sess !== 'admin'){
header("Location: membersOnly.php");
exit();
}
//ADMIN CONTENT
Related
So i created a navbar and add code similar to this, and here is what i have,
<ul>
some links
</ul>
<?php
if logedin == true) {
echo "you are loged in";
} else {
echo "please log in";
}
</nav>
now the other part of this code in another file called account.php,this isnt the real code i have but this is something im using to demonstrate,
$logedin = true;
but the code doesn't work and and the variable doesn't show on the fist page (the code on the top).
what can i do?
Thanks!
(EDIT) i forgot to say this, but the navbar is on more than 1 page and that the problem , and idk how to use post on more than 1 page.
A value that indicates whether someone is logged in or not would be best stored in the Session - then it will persist between requests to different scripts (by the same user), but not permanently.
e.g.
login.php
When the user has successfully logged in, set a variable
<?php
session_start(); //access the session
//...some code here to check username / password etc, and then if they are all ok, you can set them as logged in for the duration of the session....
$_SESSION["loggedin"] = true; //store a variable in the session
Then in home.php, when the user visits this page you can check the session to see if they logged in successfully or not:
<?php
session_start();
$loggedIn = $_SESSION["loggedin"];
//if not logged in, redirect back to the login page and end the script
if ($loggedIn == false) {
header("Location: login.php");
exit();
}
//otherwise, continue as normal...
There's a comprehensive explanation of how sessions work here.
This is just about the last thing I have left to do and I will have officially created my first PHP registration/login system.
What I have is a file called checksession.php. This file checks to see if a user is logged in/has a session created. If the user does, it should let them view their account page. If it isnt, it should send them to index.php.
As it stands, it is sending the user back to index.php even after successfully logging in. I am not sure what I am doing wrong in this script.
checksession.php
<?php
include('includes/db.php');
session_start();
$userSession = $_SESSION['username'];
$sql = mysqli_query($db, "SELECT emailAddress FROM users WHERE emailAddress='$username' ");
$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);
$login_user=$row['emailAddress'];
if(!isset($userSession )) {
header("Location: index.php");
}
?>
username is referencing the username field they are filling out when logging in on the login form which is login.php.
On their account page, which in this case is account.php, I have the following:
<?php
include("includes/checksession.php");
?>
Should this be redirecting to index.php or should it be setting the session based on the username they are inputting? I did make sure the start_session(); on my login.php page as well.
Make sure its session_start(); on my login.php page not start_session();
Try to echo out the $userSession and $_SESSION['username'] to see what they actually hold
Try the statement this way
.
if(isset($_SESSION['username'])) {
//do what ever
}else{
header("Location: index.php");
}
The Variable $userSession will always be set, it may me be null or empty string but it will always be set from your code.
Change the check to:
if(!isset($_SESSION['username'])) {
header("Location: index.php");
}
Ok
I dont know if this is the best way to do this as I think I may be over complicating this but here we go:
I took the check.php code and actually dropped this into my login code in order to set the SESSION.
Right below that I have the following code:
if(mysqli_num_rows($result) == 1) {
$_SESSION['username'] = $login_user; // Initializing Session
header("location: account.php"); // Redirecting To Other Page
} else {...
Logged in and voila. I am taken to my account.php like I would expect to be. If I log out and then try to view account.php, I am bounced back over to index.php.
Pages involved are:
login.php (login forms)
admin.php (dashboard)
post_ad.php (some random page)
My login pages works fine, then after login comes dashboard, which also works fine!
Problem comes when I go back to admin.php from post_ad.php, using a hyperlink, I redirect to login page!
The code actually fails to understand that I have actually logined before correctly!
Please help to out to rectify my problem!
admin.php
include 'connection.php';
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user != 'zxc' && $pass != 'zxc')
{
header('Location: login.php');
}
session_start();
?>
POST A NEW ADVERTISE
I want the code to remember, untill I logout or close the windows, that I have logined once!
First of all in any page use session_start() at the top of the page not somewhere in middle of code.
in login.php File put user id in $_SESSION if user logged in successfully
for example
$_SESSION['user_id'] = $user_id
Say $user_id stores username in your code
and at the top of login page use this code
#session_start();
if(isset($_SESSION['user_id']) && $_SESSION['user_id']!='') {
header("location: admin.php");
}
This will redirect you to admin page if user is logged in
and in other pages you could use
#session_start();
if(!isset($_SESSION['user_id']) || $_SESSION['user_id']=='') {
header("location: login.php");
}
This will redirect you to login page if user is not logged in
You are checking posted variables from login page every time.
Which are not set when navigated from page other than login.
Store the values in sessions instead (on login page action).
$user = $_SESSION['user'];
$pass = $_SESSION['pass'];
And now check these values.
Also, don't forget to include session_start() in the beginning of the page.
www.example.com/index.html on my website is a page that asks for a password, and when entered, runs through www.example.com/login.php.
<?php
if (isset($_POST['pw']) && ($_POST['pw'] == "mypassword"))
{
// Location after Logged in
header('Location: http://example.com/kareha/index.html');
}
else
{
// If not Logged in
header('Location: http://example.com/index.html');
}
?>
And then gets redirected to www.example.com/kareha/.
The problem is, anyone can just type in and directly navigate to www.example.com/kareha/.
Is there any way I can protect this index file (or anywhere else on the site) so anyone who isn't logged in is redirected to the main login page?
Also, would it help if it was protected through .htaccess? (/kareha/index.html is automatically updated according to a template, which has broken every time I mess around with it)
Edit: Maybe something along the lines of starting a session with /login.php and then having .htaccess in the /kareha/ folder check for the session?
you need to use sessions or .htpasswd. To use sessions, change your html files to php
here's the top of your login script
<?php
session_start();
// see if the form has been posted
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// check for the password
if($_POST['pw'] == "mypassword") {
// set a session
$_SESSION['loggedin'] = true;
// redirect to kareha/
header('Location: http://example.com/kareha/index.php');
}
} else {
header('Location: http://example.com/index.html');
}
// put HTML and login form here...
the very top of kareha/index.php
<?php
session_start();
if(!isset($_SESSION['loggedin'])) {
// redirect to login page
header('Location: http://example.com/index.html');
}
// put rest of page here
you can read about sessions here: http://www.php.net/manual/en/book.session.php
Edit: I misread the original question. Revised...
I created a login page in php named as index.php. Now when the user logs in it redirects to mypage.php. The login works fine. But also mypage.php gets open when I type the url of mypage.php even without login. I want the user must logged in to see mypage.php and incase if he changes the url in browser then an error message should be triggered. What to do?
1.localhost/index.php
2.localhost/mypage.php
In index.php, once the user gets logged in successfully, set an session. like $_SESSION['login'] = true; before redirect. If invalid login, use $_SESSION['login'] = false; Don't forget to start the session on the top of the page. session_start();
In mypage.php, check if that session is set or not. If not set, throw error, else show the page.
session_start();
if(isset($_SESSION['login']) && $_SESSION['login'] == true) {
echo 'You are welcome';
} else {
echo 'redirecting to login page';
header('Location: index.php');
exit;
}
How are you storing the state of being 'logged in'?
You'll need to have your mypage.php check a variable that has been set by the index.php's successful login process.
Can you paste your code here and I can take a look
In order for a login to work correctly, your "secure" page (I use that term relatively because nothing is truly secure) needs to have some sort of validation conditional. In other words you need to have some way of determining if the user is logged in.
A simple way to do this in PHP is to set a session variable when you process the user's credentials. For example:
When the user successfully logs in set a session variable like so:
$_SESSION['isLoggedIn'] = true;
Then on the mypage.php check to see if the variable is set:
if(!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] != true) {
header("Location: index.php");
exit;
}
Please also note, it is imperative if you are using sessions that you have session_start(); as the first line of all of your files. This allows $_SESSION variables that were set on a separate page to be able to be read on the current page.
Hope this helps.