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.
Related
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
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.
I am hosting a website from a local computer (using MAMP Pro on a Mac), and need to switch the hosting to another local Mac. I have copied across all of the files for my website, and the MySQL tables, and checked that the server and MySQL are running OK. Everything seems to be fine, except that the login system is returning "Invalid User" when I try to log in, even though I am entering the correct user info (I have tried a few users just to be sure).
The log.php that handles the login looks like this:
<?
session_name("MyLogin");
session_start();
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","root","password"); // your MySQL connection data
$db = mysql_select_db("nick"); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM USERS WHERE login='$name'");
if(mysql_num_rows($q_user) == 1) {
$query = mysql_query("SELECT * FROM USERS WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) {
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/may.php"); // success page. put the URL you want
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}
// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}
?>
I have temporarily removed the password in the above code.
I wonder what steps I can take to troubleshoot this issue, and would be grateful for any help.
Thanks,
Nick
A few common techniques when I encounter this issue.
Output the generated SQL and test it by hand - echo $query;
See if mysql_error() outputs anything after you run your queries.
Use var_dump() and print_r() on your data objects to ensure they are as expected.
Comment out your redirects and exit() lines so you can determine where the script is breaking.
Fix or comment back with anything determined by the above.
Your code does a query to find a user with the given username, and then checks if the number of rows with that username is exactly 1.
The only way you could see the 'Invalid User' error is if there are 0 users with that username or more than 1 user with that username.
Have a look at the contents of the table and check which of these is the case (I recommend http://sequelpro.com for viewing database contents on a Mac). You can also use sequel pro to test your queries.
i have been trying to learn session management with PHP... i have been looking at the documentation at www.php.net and looking at these EXAMPLES. BUt they are going over my head....
what my goal is that when a user Logs In... then user can access some reserved pages and and without logging in those pages are not available... obviously this will be done through sessions but all the material on the internet is too difficult to learn...
can anybody provide some code sample to achieve my goal from which i can LEARN or some reference to some tutorial...
p.s. EXCUSE if i have been making no sense in the above because i don;t know this stuff i am a beginner
First check out wheather session module is enabled
<?php
phpinfo();
?>
Using sessions each of your visitors will got a unique id. This id will identify various visitors and with the help of this id are the user data stored on the server.
First of all you need to start the session with the session_start() function. Note that this function should be called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data.
session_start();
$_SESSION['username'] = 'alex';
Now if you create a new file where you want to display the username you need to start the session again. In this case PHP checks whether session data are sored with the actual id or not. If it can find it then initialise the $_SESSION array with that values else the array will be empty.
session_start();
echo "User : ".$_SESSION['username'];
To check whether a session variable exists or not you can use the isset() function.
session_start();
if (isset($_SESSION['username'])){
echo "User : ".$_SESSION['username'];
} else {
echo "Set the username";
$_SESSION['username'] = 'alex';
}
Every pages should start immediately with session_start()
Display a login form on your public pages with minimum login credentials (username/password, email/password)
On submit check submitted data against your database (Is this username exists? » Is this password valid?)
If so, assign a variable to your $_SESSION array e.g. $_SESSION['user_id'] = $result['user_id']
Check for this variable on every reserved page like:
<?php
if(!isset($_SESSION['user_id'])){
//display login form here
}else{
//everything fine, display secret content here
}
?>
Before starting to write anything on any web page, you must start the session, by using the following code at the very first line:-
<?php
ob_start(); // This is required when the "`header()`" function will be used. Also it's use will not affect the performance of your web application.
session_start();
// Rest of the web page logic, along with the HTML and / or PHP
?>
In the login page, where you are writing the login process logic, use the following code:-
<?php
if (isset($_POST['btn_submit'])) {
$sql = mysql_query("SELECT userid, email, password FROM table_users
WHERE username = '".mysql_real_escape_string($_POST['username'])."'
AND is_active = 1");
if (mysql_num_rows($sql) == 1) {
$rowVal = mysql_fetch_assoc($sql);
// Considering that the Password Encryption used in this web application is MD5, for the Password Comparison with the User Input
if (md5($_POST['password']) == $rowVal['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $rowVal['email'];
$_SESSION['userid'] = $rowVal['userid'];
}
}
}
?>
Now in all the reserved pages, you need to do two things:-
First, initialize / start the session, as mentioned at the top.
Initialize all the important configuration variables, as required by your web application.
Call an user-defined function "checkUserStatus()", to check the availability of the User's status as logged in or not. If the return is true, then the web page will be shown automatically, as no further checking is required, otherwise the function itself will redirect the (guest) viewer to the login page. Remember to include the definition of this function before calling this function, otherwise you will get a fatal error.
The definition of the user-defined function "checkUserStatus()" will be somewhat like:-
function checkUserStatus() {
if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
return true;
}
else {
header("Location: http://your_website_domain_name/login.php");
exit();
}
}
Hope it helps.
It's not simple. You cannot safely only save in the session "user is logged in". The user can possibly write anything in his/her session.
Simplest solution would be to use some framework like Kohana which has built-in support for such function.
To make it yourself you should use some mechanisme like this:
session_start();
if (isset($_SESSION['auth_key'])) {
// TODO: Check in DB that auth_key is valid
if ($auth_key_in_db_and_valid) {
// Okay: Display page!
} else {
header('Location: /login/'); // Or some page showing session expired
}
} else {
header('Location: /login/'); // You're login page URL
exit;
}
In the login page form:
session_start();
if (isset($_POST['submit'])) {
// TODO: Check username and password posted; consider MD5()
if ($_POST['username'] == $username && $_POST['password'] == $password) {
// Generate unique ID.
$_SESSION['auth_key'] = rand();
// TODO: Save $_SESSION['auth_key'] in the DB.
// Return to some page
header('Location: ....');
} else {
// Display: invalid user/password
}
}
Missing part: You should invalidate any other auth_key not used after a certain time.
using mysql as database. I got this code from the previous answers to the same question:
session_start()):
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
Could you please explain what is: $_SESSION['loggedin'] .
Where could I define it? the loggedin, please help
http://www.php.net/manual/book.session.php
I hope it will help you ;)
$_SESSION is a super-global array (available anywhere) that store all sessions variables.
session_start(); // begins session
$_SESSION['user_id'] = 99;
So, the loggedin variable is set to true when a user logged in, and then it is stored in the session. Sessions are basically information that are saved on the server.
$_SESSION is simply a persistent container where you can store anything and retrieve it in other requests during the same session. As such, you would have to set $_SESSION['loggedin'] and $_SESSION['username'] at the point where the user has successfully logged in.
You use sessions to store userdata to pass it between all pages that get loaded. You can define it as said by others by using the $_SESSION['sessionname'] var.
I will post a simple script below how to let people login on the website since you wanted to know how to use it:
session_start(); #session start alwas needs to come first
//Lets make sure scriptkiddies stay out
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
//Read the user from the database with there credentials
$query = mysql_query("select id from user where username = $username and password = $password");
//Lets check if there is any match
if(mysql_num_rows($query) > 0)
{
//if there is a match lets make the sessions to let the user login
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
}
This is a simple script how to use a Session for a login system. There are many other ways you can use sessions
After login:
$_SESSION['loggedin'] = true;
That's it.