I have been learning PHP for a little bit now, and it has been going really easy for the most part. The only thing I'm hung up on is getting sessions to work. Google has been unforgiving in this endeavor.
It could be one of two reasons; syntax or my software. I'm currently building a local website using EasyPHP 5.3.5.0 on a machine that isn't connected to the internet. Connecting it to the internet is not an option.
What I currently know of sessions is that a lot of syntax related to it has be deprecated, replaced by the superglobal $_SESSION array, which is a lot easier to use. start_session(); must be before any syntax relating to sessions. However, my login script isn't establishing a session, as a quick !isset ($_SESSION['username']) always returns true.
My script is set up like this:
PHP include to login.php, which is a form. check_login.php is what validates it, and if a query returns one row, it'll redirect to login_success.php which establishes the session, gives a welcome message then redirects (Using JavaScript) to the homepage.
Any ideas?
EDIT to include more information:
Here is a synopsis of my code:
index.php:
include 'main_login.php';
main_login.php:
if(!isset ($_SESSION['username'])){
...
Login form, action="cehcklogin.php" method="post"
...
}else{
var_dump ($_SESSION): // Just to see if it works
}
checklogin.php:
Connect to SQL
$username = $_POST['username'];
$password = $_POST['password'];
$username / $password stripslashes / mysql_real_escape_string
Query to find the username & password
$count = mysql_num_rows($result);
if($count = 1){
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
header("location:login_success.php");
}else{
echo "Wrong Username or Password."
}
login_success.php:
The login process goes to all of the way here, redirects home and that's where the problem is.
session_start();
var_dump($_SESSION); //This works
if(!isset ($_SESSION['username'])){
header("location:index.php");
}
Javascript redirect, and a welcome message appears.
It all works until you get to the homepage, which $_SESSION['username'] should be set, and it should not display the form, but it does.
It looks like you're not using session_start() in your main_login.php like etranger alluded to. You need to call that function at the start of each new request to begin using sessions.
Otherwise, if you are calling session_start() and you just neglected to show it in the code sample, then maybe the session ID is being lost during the redirect. Are you using cookie-based sessions or passing session ID as a URL parameter? Try printing session_id() or SID at the top of each page. This will let you know when the session is lost (the session ID will change or be "").
If you're using cookie-based sessions, then maybe the cookie is getting lost for some reason. If you're using URL parameter to pass session ID, then maybe transparent session ID support isn't working right.
You have to call session_start() as early as possible, and definitely before using $_SESSION, which would otherwise be empty.
Related
I am relatively new to PHP, so I realize this is very likely a beginners mistake; but I have done my due diligence and I have attempted to trouble-shoot the issue on my own, but with no luck.
First, I pass the values myusername and mypassword from the form to checklogin.php. From there it queries the database, and if a single row is returned where the username and password match, this code is run:
$_SESSION['myusername']=$myusername;
$_SESSION['mypassword']=$mypassword;
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>
Now, I understand writing your own login mechanism is frowned upon --especially since mine doesn't even work. I understand this; but at this point, getting it to work is more of a learning experience for myself than a practical application.
From here I am directed to this page (login_success.php), which should only load if $_SESSION['myusername'] is set or rather, I am "logged in".
<?php
session_start();
var_dump($_SESSION);
if(!isset($_SESSION['myusername'])){
header("location:login.php");
}
var_dump($_SESSION['myusername']);
var_dump($_SESSION['mypassword']);
?>
<html>
<body>
Login Successful
</body>
</html>
Now, immediately after logging in, both var_dumps output NULL. If I pull the whole $_SESSION array I get array(0) { }.
Now, I also have a logout.php function:
<?php
session_start();
unset($_SESSION['myusername']);
$_SESSION = array();
session_destroy();
header("location:dashboard.php");
?>
a var_dump of $_SESSION['myusername'] still shows NULL, and a var_dump of $_SESSION is array(0) { }. Which is expected; HOWEVER when I got tologin_success.php, which should only load if$_SESSION['myusername']is set, it will still load; but thevar_dumpsof the$_SESSIONarray still showNULL`.
So, two issues. After setting my session tokens they are always null; and after unsetting/session_destory()ing my $_SESSION, I can still access a page that checks to see if $_SESSION['myusername'] is set.
Does anyone know what could cause this behavior?
Make sure to have session_start(); in every PHP file where you are working with $_SESSION variables. Make sure to include it on the top of the PHP file.
Also, are you submitting the form with method POST? The variables you are posting are stored in a $_POST array, so:
$_SESSION['myusername']=$myusername;
$_SESSION['mypassword']=$mypassword;
should be:
$_SESSION['myusername']=$_POST['myusername'];
$_SESSION['mypassword']=$_POST['mypassword'];
Whenever submitting a password through a form, make sure to set the form attribute method to post, like so: <form method="post">
For a website, I need to route users to their own page. I have a login form, which sends data to a PHP file to check if the user's information is correct, and if so, forwarding the user to their page. The only problem is that I need to validate the user on arrival, to check if they logged in or just typed out the URL. I plan to use this with a POST, but how can I auto-send the constant (i.e. "logged-in")? Is there a way to do that through an HTML form (outputted from an echo) and sending it when the page loads? Thanks in advance!
EDIT 1: I understand that I must use Sessions, but whenever the page redirects it clears the session. The whole reason I was asking this was because I needed a way to keep the session active. How do I redirect in a way that doesn't clear the session?
In the PHP file that validates their credentials, start a "session". You can then apply session variables that can be called at any time while the session is valid. You can do this with POST, which is sounds like you're using, or by querying a database upon validation.
For example, upon validation:
session_start();
$_SESSION['username'] = $_POST['username'];
$security_check = mysql_query("SELECT * FROM userList WHERE username = '$username'");
$row = mysql_fetch_assoc($security_check);
$_SESSION['userId'] = $row['userId'];
$_SESSION['userFullName'] = $row['userFullName'];
On subsequent pages, you can put the following code at the top to check if the user logged in. If not, it will kick them back to the index page; otherwise the $_SESSION variables will be maintained.
<?php
session_start();
if (!isset($_SESSION['userId'])) {
echo "<script> window.location.replace('index.php?login=no') </script>";
}
?>
As suggested in the comments, I would recommend doing some further research on sessions to get a full understanding of how they work.
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.
I am working on a login system for a client and I have run into an issue that I am unsure how to fix. I have it set so that when the user tries to access the index.php of a certain directory they are require to login. The code that I have doing this is:
<?php
session_start();
if(!$_SESSION['myusername']){
header("location:Login_admin.php");
}
?>
On the Login_admin.php page, there is a form with the action="checklogin.php". here is where it connects to the database and starts a session where it stores the username:
if($count==1){
session_start();
// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION['myusername'];
$_SESSION['mypassword'];
header("location:index.php");
}
Originally the above code did not have the session_start() so I added that in in attempt to solve my problem.
The actual problem is the session is not registering. If I go to one of the other pages in the director (all of them have that first segment of code at teh top) and log in it sends me to index.php like I want, but when I try to go back to that page it makes me log in again. At one point I had that first segment of code on my index page and even with the correct log in it would loop back to the login page.
I was shown this script by a friend and have not really changed much. Originally the script had:
session_register("myusername");
But after some debugging, I changed it to:
$_SESSION['myusername'];
A final note, I am not an expert the issue is probably considered a silly mistake but for the life of me I can't figure it out.
Thanks in advance!
the
$_SESSION['myusername'];
line does absolutely nothing
to assign a value to session variable you have to assign a value to session variable
the usual way values being assigned to variables in PHP
You have to give a value to each session variable
$_SESSION['myusername'] = 'thename';
$_SESSION['password'] = '*******';
I want to get user input in one page, store that in a php variable and use it in another php page. I have tried using 'sessions' but it doesn't seem to be working. Is there another safe alternative? This information is likely to be usernames and passwords.
Try changing your session code as this is the best way to do this.
For example:
index.php
<?php
session_start();
if (isset($_POST['username'], $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
echo 'Click to continue.';
} else {
// form
}
?>
nextpage.php
<?php
session_start();
if (isset($_SESSION['username'])) {
echo $_SESSION['username'];
} else {
header('Location: index.php');
}
?>
However I'd probably store something safer like a userid in a session rather than the user's login credentials.
I Agree with carson, sessions should work for this. Make sure you are calling session_start() before anything else on any page you want to use the session variables.
Also, I would not store password info directly, rather use some kind of authentication token mechanism. IMHO, it is not intrinsically unsafe to store password data in a session, but if there is no need to do so, you should probably try to avoid it.
There are several ways:
use sessions (but don't forget to call session_start() on every page you'll use the session data store ($_SESSION))
append your data to the query string of the "next" page ($_GET)
post your data to the "next" page ($_POST)
The session-way is the only way on which the data does not "leave" the server as it's stored on the server itself. For all other ways mentioned above you have to take care of sanitizing and validating the data on the receiving page.
The most simple way would be
//page1.php
session_start();
$_SESSION['user']='user';
$_SESSION['password']='password';
//page2.php
session_start();
echo $_SESSION['user'] . ' ' . $_SESSION['password'];
You can try using POST and GET methods for transferring user inputs within PHP scripts.
PHP GET
PHP POST
I agree too, sessions are the best solution. See this chapter from Web Database Applications with PHP & MySQL for some examples.