How to check if $_SESSION['myusername'] is empty and if so redirect them to index.html?
I'm currently using:
<?php
session_start();
/*** begin the session ***/
if(!isset($_SESSION['myusername']))
{
header('Location:index.html');
}
?>
But that lets non-authorized users to stay.
Make use of
<?php
session_start();
/*** begin the session ***/
if(empty($_SESSION['myusername']))
{
header('Location:index.html');;
}
?>
Change your code to this
<?php
session_start();
/*** begin the session ***/
if(!$_SESSION['myusername'])
{
header('Location:index.html');;
}
?>
Maybe you should use a stronger method to control access to your pages, like a RBA system...
Take a look at this, it helped me a lot
Try to like this:
session_start();
if(!isset($_SESSION['blah']) && empty($_SESSION['blah'])) {
header('Location:index.html');
}
exit() or die() after header()
I know this is old; but you did not share the full code.
I know this is from this tutorial here: http://www.phpeasystep.com/phptu/6.html
If you check your logs, you will see that a header cannot be set after HTML tags. If you look at the code from the tutorial, you will notice he has two HTML comments at the top.
Remove those, and PHP will be able to set the header and redirect the user. Otherwise, load the page in the else statement and serve the login form again in the if. Hope this helps.
Also, I am sure you are older and wiser after two years; but this is a poor log in process and (since the code won't work verbatim) a poor tutorial. For example, I can still get the contents of the page with curl http://example.com/protectedpage.php since it will not redirect me, and it will serve the rest of the page.
if(isset($_POST['submit'])){
echo "Success";
}else{
header("location:yoursiteurl");
}
Related
I want to ensure that an HTML page only appears if the user has logged in. I'm trying to do it by setting a session variable from the login page then checking if that variable exists when the HTML page is loaded.
This is my code at the very top of the HTML page:-
<?php
session_start();
if (!isset($_SESSION['checks'])) {
header("location: http://localhost/project/fail.php");
}
?>
It doesn't redirect! Nothing happens at all except that the HTML page gets loaded.
Can anyone help please?
Thank you all for your helpful suggestions. The snippet I posted shows the very first lines: i.e. session_start(); is the very first line.
By moving the var check snippet from the session_start() segment and making a separate php check snippet immediately after the body tag, everything works as expected.
You can use header function : https://www.php.net/manual/en/function.header.php
Referring to it :
<?php
session_start();
if (!isset($_SESSION['checks'])) {
header("Location: http://localhost/project/fail.php");
}
?>
make sure that session_start() always come at the first line
if(!isset($_SESSION['checks'])){
header('location: fail.php');
}
I believe your problem is on the login page... Although, if I were to talk about this page, consider trying the following code instead of your snippet first. If it gives the desired outcome then you will know that the problem is with your header and not the session:
<?php
session_start();
if (!isset($_SESSION['checks'])) {
echo "not logged in";
}
?>
Do make sure you're referring to the correct session variable if this code doesn't work and feel free to share how you are starting this session on your login page.
I am trying to verify that a user has logged in before showing them the page, using the method below, while the if/else method works when wrapped around plain html, it is failing when there is php involved. I am a novice by the way. What happens is the page simply loads as if the two tags below weren't there...which would be fine had I previously logged in, but I hadn't.
<?php
session_start();
if(isset($_SESSION['user'])) {
?>
HTML/PHP Page goes here.
<?php
} else {
header("Location: cms/admin/loginreadmode.php");
}
?>
Thanks in advance,
You can debug just below your session_start(); by printing your session:
echo '<pre>';
print_r($_SESSION);
die();
If $_SESSION['user'] isn't showing up in your array it isn't be set.
You can do this like this:
session_start();
$_SESSION['user'] = true;
Are you sure that you have add session support in every page?
if (!isset($_SESSION)) {
session_start();
}
This code should be working, so mistake is probably somwhere else I suggest checking if you set $_session["user] after login.
You should also replace your not-working code part with simple
echo "hello";
to chek it.
1) That is not a great method of checking whether a user is logged in, purely checking whether a user sessions exists can end up causing a lot of problems. Storing the ID in the sessions and then checking whether the ID is valid may be a better way,
2) When I copy the code above into a test document it goes straight to the redirect page in the else statement. This is down to the user session not being set, as soon as I set the user session before the code is executed it works fine. I see 'HTML/PHP Page goes here.'.
Setting the user session:
$_SESSION['user'] = 'TestUser';
You can change the code at the top of the page to be
<?php
session_start();
if(!isset($_SESSION['user'])) {
header("Location: cms/admin/loginreadmode.php");
die();
}
?>
BEFORE YOU MARK THIS AS DUPLICATE, I have read through all the answers on this topic and Non of them worked for me, this is why I am posting this.
So the problem is that the data for $_SESSION is not saving from page to page. Here is my test:
TestOne.php
<?php
session_start();
$_SESSION["user_id"] = 1;
if(isset($_SESSION["user_id"])) {
header("Location: TestTwo.php");
}
?>
TestTwo.php
<?php
if(isset($_SESSION["user_id"])) {
echo $_SESSION["user_id"];
}
?>
It goes to page two but it is a blank page. Why is the data not saving from page to page?
session_save in the php.ini is set to /tmp (I am using hostgator)
You are missing session_start(); on your TestTwo.php
FYI : You need to call session_start(); on all of your PHP files, if you are making use of Sessions.
I have read through all the answers on this topic and Non of them
worked for me, this is why I am posting this.
Really caught my attention btw.
for using session variables, u need to use session_start()
before that
session_start();
if(isset($_SESSION["user_id"])) {
echo $_SESSION["user_id"];
}
You need session_start() on every page that requires the session.
I have a simple script where a user logs in. I am trying to use sessions, so that a user remains logged in on whatever page he browses through the website.
I have these scripts:
index.php - http://pastebin.com/yqLtqPRC
login.php - http://pastebin.com/KcQWjfw1
dbConfig.php - http://pastebin.com/GKyfaJJV
upload.php - http://pastebin.com/iMrz3WB8
functions.php - http://pastebin.com/x44KrmxK
If the user logs in or is logged in, 'You are now logged in, $user' is supposed to be shown, but the default 'You are not logged in.' displays throughout the pages.
No error messages are shown whenever I change page or try to log in.
Latest version of the code can be found here: http://www.mediafire.com/?7n6qo3p4gpkaao4
Can anyone help please?
thanks.
Put the session_start() on the top of the page in each file where you need sessions just after<?php and you should be fine. You need to call this function before any actual html is echo'd on the page.
Read the php session documentation here
Further looking into your code, if you want to limit the user to see other pages only if he's logged in then make a new file called logincheck.php with contents below and include it on the top of each file by require_once("logincheck.php");. In this case don't put the session_start() code again as mentioned above.
<?php
session_start();
if(isset($_SESSION["username"])){
$welcomeMsg = "<p align='right'>Welcome, </p>" .$_SESSION["username"];
}else{
if(basename($_SERVER["PHP_SELF"])=="index.php")
$welcomeMsg = "You are not logged in";
else
header("Location:index.php");//will redirect the user to index page if he has not logged in
}
?>
Now u can use $welcomeMsg and echo it anywhere on page where u want to display the error msg.
Hope that helps answer your query.
form action="?op=login" method="POST" action="login.php"
why are using action twice in form?
action="login.php" is only required.
I didn't see exactly where your problem was, too much code to read, but by looking through 2 files (the first 2) I noticed some stuff that could become a problem:
A Session_id is supposed to identify a user. if you simply put in a boolean (true) I could easily break in your user reserved part of the site by just modifying my HTTP header.
second thing is that you put a redirect on the login.php before you echo something.... guess you wont see anything.... the redirect happens before the echo.
The third thing is that you should definetly hash the passwords you get and store. It is so sad when people get access to databases and have without any work all passwords of all people.
And a last advice: try to put the Session_Start as the first statement in every file... could be that.
I stopped at this point:
redirect('../TASK2PHP/upload.php');
what's that function and what does it do?
Maybe you meant to use http_redirect or header or HttpResponse::redirect ...
Here you go. There were a ton of errors.
http://www.2shared.com/file/A2V_Ztw8/login.html
That should at least get you started. It is also commented along the way. I did not use the functions.php file there was nothing important in there. Also when you use this change your dbConfig file accordingly.
I have edited index.php, login.php and setup working flow of sessions. Follow the code structure for setting up sessions in others file accordingly.
Download following login-form rar file;
https://www.box.com/s/1ie9ilp9jgluvokf6say
you code structure of login methods seems confusing and its always a good idea to echo everything before you redirect otherwise httpresponse complains about it. Moreover my advise is you first turn on error reporting its always a good idea to do development with error reporting enabled. You can do this inside your login.php just place at the beginning of the file.
error_reporting(E_ALL); or set E_ALL to 1
ini_set('display_errors','On');
TL,DR. But here is an article that teaches the general design pattern for this sort of thing. All web sites that use PHP client authentication follow this design.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html
You can copy and paste the code snippets from the article. If you have any questions about what the code is doing, please post a comment here and I'll try to help explain. ~Ray
Hope this may help :
you can debug if session is empty or not.
session_id() returns the string identifying the current session. If a session hasn't been initialized, it will return an empty string.
if(session_id() == '')
{
// session has NOT been started
session_start();
}
else
{
// session has been started
}
and
check session in php if empty
Make it on index.php file and include your pages if user logged in. and check inside each and every page you including. if user not set then redirect to login page.
example :
index.php
if(isset($_SESSION['UserId'])){
//make simple function to get the username from user ID
$dUserName = getUserName($_SESSION['UserId']);
echo "wellcome".$dUserName;
echo "<href='logout.php'>Logout</a>";
}
else{
echo "<href='login.php'>Logout</a>";
}
if(isset($_GET['page'])){
$includePage = "includes/".$_GET['page'].".php";
}
else{
$includePage = "includes/login.php";
}
if(isset($includePage)){
include($includePage);
}
sample page loading from index
sample.php
if(isset($_SESSION['user']) && $_SESSION['user'] != ''){
//show your page
}
else{
//redirect to login page
echo '<SCRIPT language="JavaScript">window.location="index.php?page=login";</SCRIPT>';
}
I have fixed the files...
The main problem is in login.php in the loginUser function.
Change this line:
$sql = "SELECT * FROM users WHERE Username = '$username' AND Password = '$password'";
To this:
$sql = "SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'";
The problem with the first line is that it is looking for the text '$username' (and '$password' and not the variable $username and $password
As you can see the solution is to close the string before and after the variables reference'
P.S. You would gain tremendously from using a framework such as CodeIgniter to build your site, besides for saving you a lot of time fixing errors like this, it is also much more secure.
Let me know if you need me to upload the fixed files.
This seems really simple, and I see a lot of documentation about it, but I can't get it to work. Basically, I have a page "download-software.php" that we want only to be accessed from "download-registration.php" On the second page "download-registration.php" I have this:
<?php
session_start();
$_SESSION['authenticated'] = 'yes';
?>
and on the first page "download-software.php" I have this:
<?php
session_start();
if($_SESSION['authenticated'] != 'yes') {
header("Location: http://kinetick.com/V3/download-free.php");
};
?>
I need to kick the browser to the "download-free.php" page if they dont come from the first page. Can anyone help me out pls?
**Edit**
added session_start(); still doesn't work.
You need to add another session_start() to the beginning of download-software.php to resume the session you started from download-registration.php.
You forgot session_start() on download-software.php
You must always call session_start() before any html data to be able to use $_SESSION in your script