separate sessions - php

When someone logs in on my website, it will output information just for that user and so on. But there is a problem as it seems it doesn't recognise different users. If I log in two users on the website, first one will become second one... here is my code at the start of each page
?php
session_start();
require_once 'loginDetails.php';
$db_server = mysql_connect("$db_hostname", "$db_username",
"$db_password");
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
if (isset($_SESSION['username']))
{
$user = $_SESSION['username'];
$query = mysql_query("SELECT * FROM cssh_students_table WHERE StudentUserName = '$user'");
$query1 = mysql_fetch_row($query);
$course = $query1[10];
$year = $query1[6];
$email = $query1[4];
$loggedin = TRUE;
}
else
{
$loggedin = FALSE;
}
if ($loggedin == FALSE)
{
session_unset();
session_destroy();
header('Location: ../index.html');
}
?>

session_destroy() is not guaranteed to kill your session cookie. Your problem is probably because your original session cookie still exists.
See this related question.
Additional (Not Related)
Doing a SELECT * and then accessing the results using integer indexes is a bad practice that will eventually cause you problems some day when the database structure is changed. Either SELECT the items you need, or use mysql_fetch_assoc and access the values by name.

There can be many solutions for that.
For us, we need to do that kind of thing in development. For each user we want to open, we use an anonymous browser window. Another solution could be to use a different domain name for each user you want to login (with a dns wildcard).

Related

Echo out user information in the same table to their page base on their store information without echoing out the same information to another user

First of all I stored users in the same table and I created a page called welcome.php, where I want it to be echoing out user info from MySQL based on their entry.
Now when I created first user and echo it out to this welcome.php, it comes out from the table, and if I create another user info in the same table for it to echo out at the same welcome.php based on the user login info such as, if I create a user called John Fred etc and a user called Michael Kenneth etc.
So user John Fred comes out to the welcome.php with its information from the same table, and then user Michael Kenneth doesn't come to welcome.php when i sign with user Michael Kenneth instead it shows only user John Fred. I don't know where this error comes from; maybe from the login.php, or from welcome.php.
Here is my code echoing in welcome.php
<?php
$tnumber2 = "{$_SESSION['tnumber2']}";
// Connect to the database
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$Tname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<? echo $rows['tnumber2']; ?>
Another script for other user info which I store for another table:
<?php
// Connect to the database
$tnumber2 = "{$_SESSION['tnumber2']}";
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$UPname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
?>
<?php
while($rows=mysql_fetch_array($result)){ // Start looping table row
?>
<? echo $rows['pdate']; ?>
<?php
// Exit looping and close connection
}
mysql_close();
?>
And here is my login.php in this case am using one input form:
<?php
session_start();
ob_start();
?>
<?php
if ($_POST['submit']) {
$tnumber2 = $_POST['user'];
if ($tnumber2) {
require("connect.php");
$query = mysql_query("SELECT * FROM users WHERE tnumber2='$tnumber2'");
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_assoc($query);
$id = $row['id'];
$tnumber2 = $row['tnumber2'];
if ($tnumber2 == $tnumber2) {
$_SESSION['id'] = $id;
$_SESSION['tnumber2'] = $tnumber2;
header("Location: welcome.php");
}
}
else
include "error.php";
}
}
?>
I have tried all I can on this, maybe I might be a fool to think that such thing is possible but I am not a PHP professional, just a learner, please any help will be gladly appreciated.
Assuming the session has indeed stored the data of the logged-in user, you need to change "welcome.php" so it reads the correct user with a WHERE clause:
<?php
// Retrieve the ID of the user (and untaint it too)
$id = (int) $_SESSION['id'];
// Connect to the database (I've removed the unnecessary quotes)
$db = mysql_connect($Sname, $Uname, $Pname) or die("Could not connect to the Database.");
$select = mysql_select_db($Dname) or die("Could not select the Database.");
// Here is the query from the users table, we're selecting one user here
$sql="SELECT * FROM `users` WHERE `id` = $id;";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
?>
<!-- Let's see what is in rows now, should be just one record -->
<?php print_r($rows) ?>
I would advise that you try to understand each part of the code above, and indeed the same for the code you have - don't just copy-and-paste without knowing what each bit does. If you get stuck on something, don't be afraid to look it up in the manual!
I've used print_r to just dump the row result - you can use the contents of that to determine what columns and other data you wish to extract out of it. After you have done that, the print_r can be removed.
Bear in mind that your login is not testing for password correctness - it only checks that someone has entered a particular username in login.php. If you want users to log on with a username and password, that needs to be designed and implemented as well. There are many questions on this site with best-practice techniques on how to do that, if that's of interest to you.
It has, incidentally, been rather difficult to understand what you are doing. I don't think this is a problem with your English, which seems fine to me. Rather, it's worth remembering to write in short sentences (no more than 20 words, say) and short paragraphs (no more than 4 or 5 sentences). And keep your descriptions as short as you can - it makes the difference between people helping you and their deciding they don't understand what you are trying to do. I expect this advice would be just as relevant in your native language as well!
Also, remember to add as much useful information to a question as you can, and if people ask for clarification, make sure you answer all their questions. Remember that people here are volunteers, and you need to make their job as easy as possible.

Session Confliction Error

Am creating a website where people can leave their opinions on releases by rating them and this gets stored into a MySQL database which is driven by PHP.
I have a feedback form for one particular release, which (lets say in this example) has the ID of 35. When I send a user another one which has the ID of 36 and the user has both windows open, the PHP processing code stores the responses from ID 35 but with ID 36. The page redirects to the previous page when the database already has a 'reaction_reacted' value of '1'.
Is there a way to solve this?
Here is an example of my code. The $promo_id, reaction_id and username are passed to it from the previous page when submission occurs.
session_start();
include 'connect.php';
mysql_connect($host,$db_user,$db_password);
mysql_select_db($database);
$promo_id = $_SESSION['promo_id'];
$reaction_id = $_SESSION[reaction_id];
$username = $_SESSION['username'];
if(isset($_SESSION['username']))
{
// Check to see if Receipt and DJID values are entered
$queryb = "select reaction_ID from reactiondata where reaction_ID='$reaction_id' AND reaction_username='$username' AND reaction_promoID='$promo_id' and reaction_reacted='1'";
$result2 = mysql_query($queryb) or die(mysql_error());
while($row = mysql_fetch_array($result2)){
header('Location: ' . $_SERVER['HTTP_REFERER']);
// session_destroy();
// exit;
}
if ($reaction_id && $promo_id != null)
{
$p4support = $_POST['DJsupport'];
$p4favouritemix = $_POST['FavMix'];
$p4score = $_POST['score'];
$p4comment = $_POST['DJcomment'];
$query = "UPDATE reactiondata SET reaction_username='$username', reaction_promoID='$promo_id', reaction_support='$p4support', reaction_favouritemix='$p4favouritemix', reaction_score='$p4score', reaction_comment='".mysql_real_escape_string($p4comment)."', reaction_reacted='1' WHERE reaction_ID='$reaction_id'";
mysql_query($query) or die('Error in MySQL query. Here is the error message: '.mysql_error());
$query7 = "UPDATE reactiondata SET reaction_time=NOW() WHERE reaction_ID='$reaction_id'";
mysql_query($query7) or die('Error in MySQL query. Here is the error message: '.mysql_error());
}
Thanks
CP
P.S I know I am using depreciated mysql_query methods, I just want the page to function properly before I start preventing SQL Injection attacks.
The easiest solution (one of the...) is to add the reaction_id as a hidden form field to the form instead of using a session. That way the reaction is always linked to the correct ID when the form is posted.
You should not use a session for that as the session will span all open windows and tabs in the browser so it is not suitable to maintain the state of a specific tab.

Login systems with php and mysql

When a user logs in, how do I get all of their mysql information? I have a registering system and login system. When they log in they type their username and password, those are the only two variables i can use, because they type them in. How do I get all the other variables, not typed in by the user, for that profile?
Their usernames are unique. How do i get the rest of their variables to use throughout all of my php files?
My login file:
<?
/*Use of Sessions*/
if(!session_id())
session_start();
header("Cache-control: private"); //avoid an IE6 bug (keep this line on top of the page)
$login='NO data sent';
/*simple checking of the data*/
if(isset($_POST['login']) && isset($_POST['pass']))
{
/*Connection to database logindb using your login name and password*/
$db=mysql_connect('localhost','teachert_users','dogs1324') or die(mysql_error());
mysql_select_db('teachert_users');
/*additional data checking and striping*/
$_POST['login']=mysql_real_escape_string(strip_tags(trim($_POST['login'])));
$_POST['pass']=mysql_real_escape_string(strip_tags(trim($_POST['pass'])));
$_POST['pass']=md5($_POST['pass']);
$_POST['pass']=strrev($_POST['pass']);
$_POST['pass']=md5($_POST['pass']);
$_POST['pass'].=$_POST['pass'];
$_POST['pass']=md5($_POST['pass']);
$q=mysql_query("SELECT * FROM profiles WHERE username='{$_POST['login']}' AND password='{$_POST['pass']}'",$db) or die(mysql_error());
/*If there is a matching row*/
if(mysql_num_rows($q) > 0)
{
$_SESSION['login'] = $_POST['login'];
$login='Welcome back, '.$_SESSION['login'];
$login.='</br> we are redirecting you.';
echo $login;
echo '<META HTTP-EQUIV="Refresh" Content="2; URL=/php/learn/selectone.php">';
exit;
}
else
{
$login= 'Wrong login or password';
}
mysql_close($db);
}
//you may echo the data anywhere in the file
echo $login;
?>
I can use their login and password in all other files with the $_SESSION['var'];
How do i get the rest? Like their age? or their Name? or any variable stored in my mysql files.
Yes i know MD5 isn't the best, let's not turn this into a discussion on that.
------------------------edit-------------------------------
I guess i'll rephrase that:
I use this:
$q=mysql_query("SELECT * FROM profiles WHERE username='{$_POST['login']}' AND password='{$_POST['pass']}'",$db) or die(mysql_error());
How do i get variables from that particular user/profile. Like their other variables, such as their name, which in my mysql is fname.
-------------------------Edit---------------------------
I have updated to:
$mysqli = new mysqli('localhost', 'teachert_users', 'dogs1324', 'teachert_users');
if($mysqli->connect_errno) {
echo "Error connecting to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$user = $_SESSION['login'];
$get_user_info_query = $mysqli->query("SELECT * FROM profiles WHERE username = '$user'");
if($get_user_info_query->num_rows) {
while($get_user_info_row = $get_user_info_query->fetch_assoc()){
if ($get_user_info_row['math']) {
print_r($get_user_info_row['math']);
}
}
} else {
echo 'User not found';
}
but the print_r still prints all of the user's information. not just the math information. Why?
please try using mysqli or pdo, mysql_* functions are oficially deprecated
$mysqli = new mysqli($dbserver, $dbmanager, $dbpass, $dbname);
if($mysqli->connect_errno) {
echo "Error connecting to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli- >connect_error;
}
$user = $_SESSION['login'];
$get_user_info_query = $mysqli->query("SELECT * FROM profiles WHERE username = '$user'");
if($get_user_info_query->num_rows) {
while($get_user_info_row = $get_user_info_query->fetch_assoc()){
print_r($get_user_info_row);
}
} else {
echo 'User not found';
}
this will print the entire row information returned by mysql so to use one specific field use $get_user_info_row['username'] inside the while statement.
This is the code to get data information using the mysql_ approach:
$row = mysql_fetch_assoc($q);
The variable $row will have an array with the fields returned by the sql statement. Use this line after check if the exist rows.
Try to run
print_r($row)
and you will see it contents.
First, custom encryption routines are not considered secure, especially if you post your code (or a variant of it) here.
Second, your routine has no extra security over a plain MD5 (which is considered horribly insecure). Let's say your routine takes 3x longer than a plan MD5. Big deal, you can do a billion MD5s per second, so at best you've added a few seconds to the attacker's cracking time when trying the 1 billion most common passwords.
You should never try to roll your own password routines. In fact, you shouldn't be rolling your own user login and session code either. Use a framework like CakePHP. (You may need a plugin for the User Auth stuff. Make sure it uses bcrypt().)
When you use a framework, you will benifit from having lots of pre-existing examples and "best practices". You'll be programming at a higher level. In fact, frameworks often provide protection against attacks you don't even know about, like SQL injection, XSS, etc.

How to echo out info from MySQL table in PHP when sessions are being used.

I am using sessions to pass user information from one page to another. However, I think I may be using the wrong concept for my particular need. Here is what I'm trying to do:
When a user logs in, the form action is sent to login.php, which I've provided below:
login.php
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$con = mysql_connect("xxxx","database","pass");
if (!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
session_start();
$_SESSION['loggedin'] = 1; // store session data
$_SESSION['loginemail'] = fldEmail;
header("Location: main.php"); }
}
mysql_close($con);
Now to use the $_SESSION['loggedin'] throughout the website for pages that require authorization, I made an 'auth.php', which will check if the user is logged in.
The 'auth.php' is provided below:
session_start();
if($_SESSION['loggedin'] != 1){
header("Location: index.php"); }
Now the point is, when you log in, you are directed BY login.php TO main.php via header. How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php? Will I have to connect again just like I did in login.php? or is there another way I can simply echo out the user's name from the MySQL table? This is what I'm trying to do in main.php as of now, but the user's name does not come up:
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
$row = mysql_fetch_array($result);
echo '<span class="backgroundcolor">' . $row['fldFullName'] . '</span><br />' ;
Will I have to connect again just like I did in login.php?
Yes. This is the way PHP and mysql works
or is there another way I can simply echo out the user's name from the MySQL table?
No. To get something from mysql table you have to connect first.
You can put connect statement into some config file and include it into all your scripts.
How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php?
You will need some identifier to get proper row from database. email may work but it's strongly recommended to use autoincrement id field instead, which to be stored in the session.
And at this moment you don't have no $loginemail nor $loginpassword in your latter code snippet, do you?
And some notes on your code
any header("Location: "); statement must be followed by exit;. Or there would be no protection at all.
Any data you're going to put into query in quotes, must be escaped with mysql_real_escape_string() function. No exceptions.
so, it going to be like this
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$loginemail = mysql_real_escape_string($loginemail);
$loginpassword = mysql_real_escape_string($loginpassword);
$query = "SELECT * FROM Members WHERE fldEmail='$loginemail' and Password='$loginpassword'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if($row = mysql_fetch_assoc($result)) {
session_start();
$_SESSION['userid'] = $row['id']; // store session data
header("Location: main.php");
exit;
}
and main.php part
session_start();
if(!$_SESSION['userid']) {
header("Location: index.php");
exit;
}
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$query = "SELECT * FROM Members WHERE id='$sess_userid'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_assoc($result));
include 'template.php';
Let me point out that the technique you're using has some nasty security holes, but in the interest of avoiding serious argument about security the quick fix is to just store the $row from login.php in a session variable, and then it's yours to access. I'm surprised this works without a session_start() call at the top of login.php.
I'd highly recommend considering a paradigm shift, however. Instead of keeping a variable to indicate logged-in state, you should hang on to the username and an encrypted version of the password in the session state. Then, at the top of main.php you'd ask for the user data each time from the database and you'd have all the fields you need as well as verification the user is in fact logged in.
Yes, you do have to reconnect to the database for every pageload. Just put that code in a separate file and use PHP's require_once() function to include it.
Another problem you're having is that the variables $loginemail and $loginpassword would not exist in main.php. You are storing the user's e-mail address in the $_SESSION array, so just reload the user's info:
$safe_email = mysql_real_escape_string($_SESSION['loginemail']);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$safe_email'");
Also, your code allows SQL Injection attacks. Before inserting any variable into an SQL query, always use the mysql_real_escape_string() function and wrap the variable in quotes (as in the snippet above).

how can i share data between PHP pages?

I have a PHP page and I want to share some data between pages like UserID, password.
I'm learning about sessions and I'm not sure if Im using it correctly.
<?php
require_once('database.inc');
$kUserID = $_POST['kUserID'];
$kPassword = $_POST['kPassword'];
if (!isset($kUserID) || !isset($kPassword)) {
header( "Location: http://domain/index.html" );
}
elseif (empty($kUserID) || empty($kPassword)) {
header( "Location: http://domain/index.html" );
}
else {
$user = addslashes($_POST['kUserID']);
$pass = md5($_POST['kPassword']);
$db = mysql_connect("$sHostname:$sPort", $sUsername, $sPassword) or die(mysql_error());
mysql_select_db($sDatabase) or die ("Couldn't select the database.");
$sqlQuery = "select * from allowedUsers where UserID='" . $kUserID . "' AND passwordID='" . $kPassword . "'";
$result=mysql_query($sqlQuery, $db);
$rowCheck = mysql_num_rows($result);
if($rowCheck > 0){
while($row = mysql_fetch_array($result)){
session_start();
session_register('kUserID');
header( "Location: link.php" );
}
}
else {
echo 'Incorrect login name or password. Please try again.';
}
}
?>
For the love of all that is holy, don't use addslashes to prevent SQL injection.
I just owned your site:
Image of your ownt site http://localhostr.com/files/8f996b/Screen+shot+2010-02-23+at+7.49.00+PM.png
Edit: Even worse.
I just noticed that you're attempt at preventing injection via addslashes, isn't even being used!
<?php
$kUserID = $_POST['kUserID'];
$user = addslashes($_POST['kUserID']); // this isn't used
$sqlQuery = "select * from allowedUsers where UserID='"
. $kUserID . "' AND passwordID='" . $kPassword . "'";
Be aware that session_register() is deprecated in favor of assigning values to the $_SESSION superglobal, e.g.
<?php
$_SESSION['hashedValue']= '437b930db84b8079c2dd804a71936b5f';
?>
Also be aware that anything stored in a session, especially in a shared-server environment, is fair game. Never store a password, regardless of whether it's hashed or encrypted. I would avoid storing a username as well. If you must use some authentication mechanism between pages using a session variable, I'd recommend using a second lookup table, e.g. logins, and store the username, login time, etc in that table. A hashed value from that table is stored in the session, and each page request checks the time in the table and the hashed value against the database. If the request is either too old or the hash doesn't match, force re-login.
All this and more is available to you in the PHP manual section on sessions.
You might also wanna rename "database.inc" to "database.inc.php", or properly setup your host to treat ".inc" as PHP:
http://www.namemybabyboy.com/database.inc
<?php
$sDatabase = 'shayaanpsp';
$sHostname = 'mysql5.brinkster.com';
$sPort = 3306;
$sUsername = 'shayaanpsp';
$sPassword = 'XXXX';
$sTable = 'allowedUsers';
?>
First, you need to put session_start() at the very beginning of your script. It also needs to go at the start of every script that uses session data. So it would also go at the top of babyRegistration.php.
Second, I would strongly recommend against using session_register() as it relies on register_globals which is off by default for security reasons. You can read more here: http://php.net/manual/en/security.globals.php. You can add/access session variables by using the $_SESSION superglobal:
$_SESSION['kUserID'] = $kUserID;
Last, not really session related, just an observation, your isset check at the top is redundant; empty will return true for an unset/NULL variable, just as you might expect.
At the top of a page
session_start();
$_SESSION['yourvarname']='some value';
then on some other page to retrieve
echo $_SESSION['yourvarname'];
// some value
Oh and about injection,use this on everything going into your db
http://us3.php.net/manual/en/function.mysql-real-escape-string.php
Just because almost everything turned into avoiding SQL injections. Escaping string is not going to save you from SQL injections. The correct way is using prepared statements.
https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php

Categories