This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
I am making a simple login page however my $_SESSION variables are not transferring between pages. I've read numerous other posts about session_start() at the beginning of each page, folder writing priveleges, session_write_close(), etc., but none have worked. The session_write_close() doesn't make a difference withor without so I just left it in. All of the code below works fine as I have left out code below and above such as where $login_fail comes from.
Currently I set the the $_SESSION variables as shown in the code below:
if($login_fail == "")
{
$query = "SELECT first_name, last_name, email_address,password FROM user_info WHERE email_address = '$email_address' AND password = '$password'";
$result = mysql_query($query);
if(!$result) die ("Database access : " .mysql_error());
elseif (mysql_num_rows($result))
{
$row = mysql_fetch_row($result);
$token = "$email_address";
$token1 = "$password";
echo "token: $token, token1: $token1, row[1]: $row[1], row2: $row[2] </ br>";
if($token == $row[2] && $token1 == $row[3])
{
session_start();
$_SESSION['first_name'] = $row[0];
$_SESSION['last_name'] = $row[1];
$_SESSION['email_address'] = $row[2];
$_SESSION['password'] = $row[3];
$_SESSION['check'] = md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']);
//print_r($_SESSION);
session_write_close();
header("Location: http://127.0.0.1/websiteproject/test.php");
}
else die("Invalid username/password combination");
}
}
else
{
echo "Login failed. Please try again.";
}
I have done print_r($_SESSION) and it prints all the correct information.
The session variables are then called again in my test.php just to see what happens in really simply code.
session_start();
print_r($_SESSION);
The result is an empty array.
When I go to the easyphp temp file where my sessions are written I always find two files: the original one with all the correct information and a new one with no information. It seems as if when I call the second session_start() it is literally starting a new session and not recalling the current session.
I try to do my research to give as much info as possible and not waist people's time. Any ideas are greatly appreciated. Odd is that this was working a few days ago and then I started making changes to files deeper into the program and this happened. So I made the test.php just to find out more about the transfer problems.
You cannot call session_start() once any data or whitespace has been output to the browser.
In the code you posted, you are calling echo "token: $token, token1: $token1, row[1]: $row[1], row2: $row[2] "; prior to calling session_start() which will not start the session.
Add error_reporting(E_ALL); ini_set('display_errors', 1); to the beginning of your script and you should see a warning about not being able to start the session because output has already been sent.
Try moving the session_start(); call to the very beginning of the file.
Related
This question already has answers here:
Session variables not working php
(12 answers)
Closed 4 years ago.
Im trying to save my username to the SESSION variable using a login system however it doesn't save.
I tried printing the session variable straight away in the same page and that works however when i go to another page, it won't save.
I'm very new this stuff so im sorry if it's something obvious :)
Any help will be much appreciated :)
PHP CODE 1:
$app->post('/api/customer/login/{Username}/{PassW}', function(Request $request, Response $response){
$Username = $request->getParam('Username');
$PassW = $request->getParam('PassW');
$PassW = md5($PassW);//FIND NEW WAY OF HASHING AS MD5 IS DEPRECIATED
$sql = "SELECT * FROM login WHERE Username= '$Username' AND PassW='$PassW' LIMIT 1";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($result) == 1){
session_start();
$_SESSION['Username'] = $Username;
echo "<script type='text/javascript'>alert('Correct!');
window.location='http://localhost/testing/dashboard.php';
</script>";
exit();
PHP CODE 2 (The next page):
This page is simply a HTML page with other stuff but has the below PHP code in its body to test if its saved the variable.
<?php
session_start();
print_r($_SESSION);
?>
This code is missing the session_start(): PHP CODE 2 (The next page)
It should have been:
<?php
session_start();
print_r($_SESSION);
?>
whenever you use session on the page so you must start the session on that page so your code on code 2 page should be like this
<?php
session_start();
print_r($_SESSION);
?>
also, add the same line on a login page
session_start();
if everything seems fine to you then try to remove the cache from your browser as you are using javascript to redirect the page and there might be a chance that browser is loading the page from cache.
I have created a user authentication system with necessary DB tables and php.
THe first time before I login (Before any SESSION is created) the redirect on every page works perfect (ie Redirects to the login page if not logged in).
But once I login with a user and then logout the same doesnt work. I think it might be a problem with not ending the SESSION (Sorry if am wrong)
Here are some pieces of the code in each Page
Login PHP
<?php
session_start();
$message="";
if(count($_POST)>0)
{
include('config.php');
echo $_POST['username'];
$result = mysql_query("SELECT * FROM members WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row))
{
$_SESSION["id"] = $row[ID];
$_SESSION["username"] = $row[username];
$_SESSION["password"] = $row[password];
$_SESSION["mname"] = $row[mname];
$_SESSION["fname"] = $row[fname];
date_default_timezone_set("Asia/Calcutta");
$lastlog=date("d/m/Y");
$logtime=date("h:i a");
$query = "UPDATE `members` SET `lastlogin`='$lastlog',`logintime`='$logtime' WHERE `ID`='$row[ID]'";
mysql_query($query);
$_SESSION['logged'] = TRUE;
}
else
{
echo "<SCRIPT>
alert('Wrong Username/Password or Awaiting Approval');
</SCRIPT>";
header("Location:login_failed.html");
}
}
if(isset($_SESSION["id"])) {
header("Location:member/myprofile.php");
}
?>
PHP code on every page
<?php
session_start();
include('config.php');
if(!$_SESSION['logged'])
{
header("Location: ../login.html");
exit;
} ?>
And Finally Logout
<?php
session_start();
unset($_SESSION["id"]);
unset($_SESSION["username"]);
unset($_SESSION["password"]);
unset($_SESSION["mname"]);
unset($_SESSION["fname"]);
header("Location:../login.html");
?>
Is there any problem with my Code. Am i missing something? I couldn't get it right. Pls Help
Thanks guys got it solved..
Now can you tell me How I can redirect login.php to user home page(myprofile.php) in case the User is logged in (Session exists) - Like facebook,gmail etc
Instead of calling unset() on each session var, you can simply use session_destroy(), which will destroy all of the current session data.
session_start();
session_destroy();
header("Location:../login.html");
For complete destructive power, you might also want to kill the session cookie:
setcookie(session_name(), '', 1);
See this question for a more complete example of session logout.
You need to unset $_SESSION['logged']
Also you should reference keys in the $row variable with strings. Eg $row['username'];.
Turning on E_NOTICE level warnings with error_reporting will help you with this.
If you haven't already, reset the session login
unset($_SESSION['logged']);
Or just change it to false
$_SESSION['logged'] = false;
When you are directly hitting a page in address bar for the first time then its a new request which goes to the server and server checks for existing session as written in your code. But its not same when you are pressing back button after logout. In this case there is no request is going to the server instead the request is fetched from browser cache. If you want to disable this situation then you have to tell browser explicitly to not to store your page in cache memory. For more detail please go through this link
Something weird is happening with the following code. Instead of completely redirecting. It loads the page of the redirect into the login page and mixes things up.
Q1: How do i make a complete redirect.
- session start is the first line
- There's nothing being output before header.
- As for spaces, I'm not sure what will count as a space in the below script.
Q2: How do i preg_replace a string to only allow both lower cases and uppercases and 0 - 9 numbers and again how do i preg replace emaail to allow the '#' charecter and alphanumerics.
Q3: What's the best way to check if the user trying to login matches exactly the registered user?
Q4: What danger can a hacker do with my session variables?
PHP CODE
<?php
session_start();
require_once 'db_conx.php';
$email = preg_replace ('#[^A-Z, 0-9 ]#i', '', $_POST['email']);
$pwd = preg_replace ('#[^A-Z, 0-9 ]#i', '', $_POST['pwd']);
if ($uname == '' || $pwd == ''){
echo '<span style="color:#F00">Please fill in all login details.</span>';
} else {
$Result = mysql_query("SELECT * FROM users WHERE uemail = '$uname' && pwd = '$pwd'")
or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$_SESSION['Sname'] = $row['firstname'];
$_SESSION['Slname'] = $row['lastname'];
$_SESSION['SUid'] = $row['uid'];
$_SESSION['Semail'] = $row['uemail'];
$_SESSION['Suid'] = $row['uid'];
$_SESSION['Szip'] = $row['zip'];
}
if (mysql_num_rows($Result) > 0){
header ('Location: ../user.php');
} else {
echo '<span style="color:#F00">Your account details do not match, please check your details and try again or try to recover your account if you forgot your password</span>';
}
}
?>
Thanks.
Q1
instead of using header( 'Location...)
you can use
echo '<meta http-equiv="refresh" content="0; URL= http://something.com">';
EDIT
i believe you can also use the following. the die should allow for the redirect, but in my experience it doesn't always get along with jquery.
header('Location: http://something.com');
die();
This is especially useful if you are using event.preventDefault(); in jquery on the same page, which will almost always cause header location redirects to be ignored. this method is also appropriate when you are using get requests to include a php page in your index file, causing a url like http://somesite.com/index.php?page=home
EDIT the above information was wrong it wasn't working for me because php had already sent the headers. i'm an idiot.
instead of this meta refresh, you could do this which should produce the desired result.
echo '<script type="text/javascript">window.location = "yoururlhere"</script>';die;
Q2
$step1 = preg_replace('#[^A-Z, 0-9 ]#i', $_POST["variable"]);
$step2 = strtolower($step1);
echo $step2;
Q3
This is a tough question to answer, but basically you want to hash there password, then check if it matches the password in the db. heres a brief pseudocode.
$username = $db->real_escape_string(strip_tags($_POST["username"]));
$password = hash('sha512', $salt.$_POST["Password"});
$db->query("SELECT * FROM `usertable` WHERE `Username`='$username' AND `Password`='$password' AND Username IS NOT NULL AND Username != '' LIMIT 1");
$result = $db->get();
if(!$result){
//the query returned a null result, so the username or password was incorrect.
}else{
//set user session and log them in.
}
Q4
I'm no expert, but it all depends on the architecture of your application and how you are setting sessions and cookies.in my opinion look into using formkeys and preventing xss, rfi, sql injection and lfi, then worry about session variables. the experience gained tackling the aforementioned problems will give you confidence and a broader understanding when attempting to secure your user sessions.
further information can be obtained from php.net/manual/en/session.security.php and stackoverflow.com/questions/328/php-session-security
thanks to the suggestions of DanFromGermany who improved on this answer.
So i'm basically messing around with my own cms type system at the moment and running into some problems with php sessions. Below is a rough explanation on what i have,
All the SQL is working fine as if i remove the sessions i get no login errors (unless i put in incorrect credentials),
$query = "SELECT * FROM `test` WHERE username='$user' AND password='$pass_md'";
$result = mysql_query($query) or die("Error: " . mysql_error());
$rows = mysql_num_rows($result);
$data = mysql_fetch_assoc($result);
if($rows == 1){
$_SESSION['expire'] = time() + (10 * 60);
$_SESSION['id'] = $data['id'];
header("Location: admin.php");
}
else {
header("Location: ulogin.php?login=failed");
}
So in admin.php i have this,
<?php
session_start();
if(!(isset($_SESSION['id']))){
header("Location: ulogin.php");
}
?>
My issue is it is logging me in and then passing me straight back to ulogin.php so i'm assuming i have an empty session however i am inserting the user id into the session.
Any help would be greatly appreciated, i'm probably missing something pretty obvious, i'm not the most advanced php developer so yeh, need some more eyes on it.
Thanks
Found the issue, because i was using 2 seperate login pages (One for the frontend and one for the backend) i was missing;
<?php
session_start();
?>
from one of my login pages, sorted now, thanks all for the comments that actually made me triple check that!
if(isset($_SESSION['admin'])) {
echo "<li><b>Admin</b></li>";
}
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
$conn = blah blah
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
$result2 = $conn->query($query2);
if($result2->num_rows==1) {
$_SESSION['admin'] = $result2;
}
?>
Hi, I'm trying to set this session variable but it doesn't seem to be setting, and i'm wondering if anyone can help. If session['admin'] isset it should echo the admin button.
But i'm not quite sure why? (I do have session start and everything on everypage, it's not a problem with that or any of the "You don't have php tags" I have checked the mysql query, and it does return something from my table. Any ideas please?
Your session_start(); should be at the top of the page before anything to do with the session variables.
From the docs:
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
Edit from comments:
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
// Moved to start after answer was accepted for better readability
// You had the <?php after this if statement? Was that by mistake?
if(isset($_SESSION['admin']))
{
echo "<li><b>Admin</b></li>";
}
// If you have already started the session in a file above, why do it again here?
$conn = blah blah;
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
// Could you echo out the above statement for me, just to
// make sure there aren't any problems with your sessions at this point?
$result2 = $conn->query($query2);
if($result2->num_rows==1)
{
$_SESSION['admin'] = $result2;
// It seems you are trying to assign the database connection object to it here.
// perhaps try simply doing this:
$_SESSION['admin'] = true;
}
?>
Edit 2 from further comments:
You have to actually fetch the fetch the data like this - snipped from this tutorial which might help you out some more:
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
But having said that, while we are talking about it, you would be better off moving away from the old mysql_* functions and move to PDO which is much better.
Move session_start(); to the top of the page. You are trying to retrieve sessions, where it's not loaded.
EDIT: Try echoing $_SESSION['admin'], if it even contains something. Also try debugging your if($result2->num_rows==1) code by adding echo('its working'); or die('its working'); inside it, to check if $result2 contains exactly 1 row, since currently it seems $result2 contains either more than 1 row or no rows at all.