$_SESSION['user'] not working - php

SO this is the code for logging and and where I set things
<?php
session_start();
$_SESSION['user'] = "kjkj";
$_SESSION['pass'] = "";
$error = $user = $pass = "";
if (isset($_POST['user'])) {
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "") {
$error = "Not all fields were entered<br />";
} else {
$query = "SELECT store,c_pass FROM store
WHERE store='$user' AND c_pass='$pass'";
if (mysql_num_rows(queryMysql($query)) == 0) {
$error = "Username/Password invalid<br />";
} else {
$_SESSION['user'] = $user;
$_SESSION['pass'] = $pass;
$str = $_SESSION['user'] . ", You are now logged in. Please
<a href='scheduler.php'>click here</a>.";
die($str);
}
}
} ?>
It'll print the correct store name after the query and all that. But when I try to use it in another php file like this
if (!isset($_SESSION['user']) ) {
die("<p><h1>Please Login</h1></p>");
} else {
echo "<p><form id ='addemp' method=\"post\" action=\"addUser.php\">
Name<input type=\"text\" name=\"emp\" />
\"". $_SESSION['user'] . "\">
<input type=\"submit\" value=\"AddUser\" />
</form></p>";
}
It is an empty string. Not null just empty string. I tried all the solutions I can find on the internet, none of them worked. I'm out ideas as to why this isn't working.
Any help will be greatly appreciated, thank you.

It could be a number of things. First of all do sessions work any other time?
I don't think you have provided enough information for us to help you. It could be a problem with set-up of apache/php not just your code. Has happened to me before when I was developing on Windows with WAMP and temp folder didn't have correct permissions. As I said there could be many issues that cause your session to misbehave.
When you do a counter and refresh
page does it keep a number?
At the
beginning of every time that uses sessions you need to have
session_start() method called.
Important: There can't be any echo's or prints etc before
session_start().
Put var_dump($user) before $_SESSION['user'] = $user; and check the content of $user before it gets saved. It could be that your sanitizing function is not working properly. Do it also at the end of the first script to see the content of $_SESSION to make sure variables are saved properly.

You need to call session_start() before using $_SESSION. Also note that keeping the password in the session is a very BAD practice and a BIG security hole.

If you claim to have inserted session_start() in that page too, do 2 things:
1) correct your html, this line.
echo "<p><form id ='addemp' method=\"post\" action=\"addUser.php\">
Name<input type=\"text\" name=\"emp\" />
\"". $_SESSION['user'] . "\">
Has something not really clear. Where do you echo your $_SESSION to? is it maybe that your browser fails at rendering it? What did you want to accomplish? It can be that the browser is interpreting wrong that closing tag >. Try tidying html first.
If that was meant to be the input field value, write
Name <input type=\"text\" name=\"emp\" value=\"".$_SESSION['user']."\"/>
2) var_dump the $_SESSION['user'] to see if it's really an empty string.
if (!isset($_SESSION['user']) ) {
die("<p><h1>Please Login</h1></p>");
} else {
var_dump($_SESSION['user']);
}

It sounds like the OP had an issue with register_globals.
In php.ini set register_globals = Off, then try the code again.
I had the exact same problem - I had a user variable in the session, and then set $user = array(); and found that the $user variable was overwriting the $_SESSION['user'] variable. Disabling register_globals fixed it.
Or you can change your $user variable to something like $myUser, but it's better to disable register_globals anyway.

Based on #kpaulsen answer,
I got same situation on him, $variable overwrites $_SESSION['variable'] so I followed his suggestion but it isn't works fine on me then I found out another way of setting the register_globals = Off
Add this line on .htaccess
php_flag register_globals off

Maybe its a issue I had some time ago, made all the code perfectly, but forgot to insert the session_start(); at the connection script, witch receives the log-in $_POST['somevariable'] to validate with the DB.
On resume, don’t forget to start a session at your connection.

Related

php user_id in session not working

i need some help about $_session. My team have develop an Web-Application and there are a problem
that i cannot get the user_id on the $_session['user_id']?
on the mailing view:
if(isset($_SESSION['user_id'])&&$_SESSION['angemeldet']){
$objModel = new MAILING();
$id=$_SESSION['user_id'];
and on the login part:
if ($login_success) {
//die();
$_SESSION['angemeldet'] = true;
$_SESSION['user_email'] = $login_success['user_email'];
$_SESSION['user_role'] = $login_success['role'];
$_SESSION['user_id'] = $login_success['user_id'];
if ($login_success['role'] == 'admin'){
header('Location: ?page=admin');
}else{
header('Location: ?page=home');
}
}
the problem that if i try the codes on localhost, it work perfectly and on the server $_SESSION['user_id'] is somehow like empty??
could someone help me?
thx b4.
As suggested in the comments I would check if you have enabled sessions on your server environment.
See the answer by answer by Adarsh here: PHP.ini example to enable sessions?
Also, it can be useful to print out and debug you varialbes along the way to see where you lose your data/information. Try using the print_r() function for debuging. Try using print_r($login_success); print_r($_SESSION); exit(); after you have set your variables to print out all of the variables data.

trying to set session variable

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.

How to login on php

I am trying to create logins for users. I have an sql that inserts the information in a mysql database, but after that i don't know how to actually start the login. As of now, I insert the information on join_action.php which then redirects to /index.php (below). Does session_start() on /index.php actually start the login? Becuase if so, it's not working.
PHP (join_action.php):
$sql=mysql_query("INSERT INTO users VALUES ('','$name','$password','$email','$date','$time','$random','0','1','0')");
$id=mysql_insert_id();
$_SESSION['id'] = $id;
header("Location: http://localhost/index.php");
HTML (index.php top):
<?php session_start(); ?>
login.php (untested, but should give you the right idea)
<?
#session_start();
if(isset($_POST['login'])){
$name = addslashes({$_POST['login']});
$password = addslashes({$_POST['password']});
$res=mysql_query("SELECT * FROM users WHERE name = '{$name}' AND password = '{$password}'");
if(mysql_num_rows($res)>0) {
$_SESSION['loggedin'] = 1;
$_SESSION['user'] = mysql_fetch_assoc($res);
} else {
$_SESSION['loggedin'] = 0;
$_SESSION['user'] = null;
}
}
if($_SESSION['loggedin']==1) {
?>
Logged in!
<pre><? print_r($_SESSION['user]); ?></pre>
<? } else { ?>
Not logged in...<br>
<form method='post' action='login.php'>
<div>Login: <input type='text' name='login'></div>
<div>Password: <input type='password' name='password'></div>
<input type='submit' value='Log In'>
</form>
<? } ?>
Download any number of open source projects and see how they handle logins.
No, session_start() doesn't directly handle the login, it's just starting a new session which MIGHT be used by the login script.
session_start will initialize the PHP session for the page, but you don't appear to have any code to actually manipulate them like setting them or checking their validity or anything else, so it'll basically do nothing. It doesn't magically know what you want to DO with your session. All you've got is one line to set an ID.
You'll need to code a little extra in order to start using session_start(). To begin, session_start() simply begins a PHP session where the server begins tracking that particular user. In your methodology, you'll need to link that session to user data in your code.
When I was learning PHP users, this handy script really helped me understand the methodology: http://www.majordojo.com/php-users/
Although it's in PHP4, it's very similar code. :)

$_SESSION equals value from database?

when a person logs into my site i need to check a value in a database for their roleid, and dependent on that i need to allow/deny access to a page.
I have this code but it says that the $_SESION variable 'Access' is undefined, i cant see why?
$email = mysql_real_escape_string($_POST['email']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM person WHERE email = '" . $email . "' AND password2 = '" . $password . "'");
if (mysql_num_rows($checklogin) == 1) {
$row = mysql_fetch_array($checklogin);
$roleid = $row['roleid'];
$_SESSION['Email'] = $email;
$_SESSION['LoggedIn'] = 1;
$_SESSION['Access'] = $roleid;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area.</p>";
echo "<meta http-equiv='refresh' content='2;index.php' />";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
This is the if statement that is saying the session in undefined:
if (!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Email']) && $_SESSION['Access'] == '2')
EDIT
Sorry, should have mentioned, session_start() is called in my base.php file which is included in this file.
EDIT
I don't know what the problem is, i can assign the variable $email to the other session variable and display that so the user can see who they are logged in as?
Does anybody have any suggestions? Both of the other session variables work fine.
From the code you have posted, you are missing session_start()
If this is not within a framework that performs this for you, it must be called on every page that will utilize the session before any session calls are made.
I assume the error is occurring after the redirect, in your logic that is checking for it using isset() or empty(). Add session_start() to both pages before any session logic is performed.
EDIT:
Ok, you have session_start(). Can you print_r() your $_SESSION and check the output?
Also, the file you mention that runs the session start should be included in both files, as its necessary for setting and checking values from the session.
Make sure before running any empty() conditionals, you also run isset(). Empty does not check if the key is present.
EDIT AGAIN:
Is it possible your value for $y isn't coming out of the database as a single value? can you die() at that point, just printing the value of $y out to see what is output?
Just add another check to your if statement, !empty($_SESSION['Access'])
if (!empty($_SESSION['LoggedIn'])
&& !empty($_SESSION['Email'])
&& !empty($_SESSION['Access'])
&& $_SESSION['Access'] == '2')
Check the spelling of $row['roleid']. Is the field name in the database table EXACTLY like it ?
Change
SELECT * FROM person WHERE
to
SELECT roleid FROM person WHERE
see if it breaks... :-)
This might not be related to your problem but I think it's worth mentioning: Your username / password SQL statement can be dangerous. Although you escape the input variables it is usually better practice to do it this way:
$checklogin = mysql_query("SELECT * FROM person WHERE email='".$email."'");
$row = mysql_fetch_array ($checklogin, MYSQL_ASSOC);
if (mysql_num_rows ($checklogin) == 1 && $row['password'] == $password)
{
// you are logged in
}
else
{
// wrong email or password
}
Reason being is that your current statement only needs to return ANY row in your table whereas this statement needs to return one specific row in the table.

Unable to echo PHP coded cookie value?

I have the following code that builds a cookie:
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$firstName = $_COOKIE['firstName'];
$lastName = $_COOKIE['lastName'];
$active = $_COOKIE['active'];
$email = $_COOKIE['emailAddress'];
then when using:
echo "<b>Username:</b> <? " . $username . "?>";
echo "<a href=logout.php>Logout</a>";
The value is not printed as expected.
Can the community explain why and provide me with the correct method for echoing the value to the relevant output device?
I suspect that you never set $_COOKIE['ID_my_site']. You could do a print_r($_COOKIE); to see what it contains. I don't recommend using cookie like this, its against RFC. If you need to keep this information throughout the session then you should use $_SESSION. This also keeps malicious people from changing their cookie.
If you're using that syntax exactly, then you haven't echoed the variable at all. Try:
echo "Username: $username";
echo "Logout";
I see you've edited your question. If $username is not getting populated, try outputting all of $_COOKIE to see what's in there first.
var_dump($_COOKIE);

Categories