Setting a variable via the sessions once logged in - php

Logging in we of course have set the $_SESSION['username'] and $_SESSION['password'] as usual. However I am then trying to pack that into a variable for use around the site:
$logged = mysql_query("SELECT * FROM `users` WHERE `username`='$_SESSION['username']' AND password = '$_SESSION['password']'");
$logged = mysql_fetch_array($logged);
One previous setups, this has enabled me to then use $logged around the site for various reasons, such as calling the logged in users email to echo in a form,
However, this time, when using this method, it fails to echo anything. I have tried using the session username variable which works to echo the username, but then I tried using the session to echo the email and it didn't work.
If someone could help me pinpoint why this is, I'd be grateful.
It just doesn't seem to be pulling any information from the user as it should.

For me this just seems like an escape-thing. Try
$logged = mysql_query("SELECT * FROM users WHERE username='".$_SESSION['username']."' AND password = '".$_SESSION['password']."'");
$logged = mysql_fetch_array($logged);
Also make sure to call session_start(); before sending any headers/echoing anything if you weren't aware.
Off topic-tip
As long as this query isn't used in anything public, it's fine. But if you're gonna use this code for anything, be sure to slash your query variables. If not, and if my credentials are not validated nor hashed, you could do some nasty SQL injection by setting your password to be something like '; DELETE * FROM USERS;# as the query would then say SELECT * FROM users WHERE username='JohnDoe' AND password = ''; DELETE * FROM USERS;#'

for the usage of session
if(!session_id())
session_start();
the above session start is a must in every page.
use print_r($_SESSION); to check the session variables initialized..
once done (try using mysqli insted of mysql)
$sql='SELECT col1, col2, col3 FROM table1 WHERE condition';
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$arr = $rs->fetch_all(MYSQLI_ASSOC);
}
foreach($arr as $row) {
echo $row['co1'];
}
comment your progress for further changes..

Related

PHP SQL IF statement problems

Ok so I'm trying to pull some data from my SQL database and use it in an IF statement.
I have a database called DB_Default
and I have a table called Users
Inside Users I have all the normal columns such as id, username, password but I also have a column called isadmin.
I want to be able to do a mysql query through PHP selecting all users with the username $_SESSION[username] and isadmin = 1.
What I aim on doing is including a few navigation links for escalated privileged users only. So as the page that the code is going to be put into is for logged in users only I thought right, lets use the already defined username session i,e if my sessions username was set to Admin.
the statement should be
$result = mysql_query("SELECT * FROM users WHERE user_name='" . $_SESSION["user_name"] . "' and isadmin = '". $admin."'");
I have set $admin = "1"; so that it should only be able to return results if the user logged in has isadmin set to 1.
Instead I'm either having the navigation links show to any user regardless of their isadmin status or not at all.
To be honest the code is very messy as it's 5:40am and I haven't been coding for a while so quite rusty so I'm more than aware of how easy this should be of a fix.
I'm 99% sure it has to do with the fact I just set $admin = "1"; but for the life of me can't figure out where I've gone wrong. Going to give it a rest for today and come back tomorrow. Hopefully by then someone will have posted a resolution and obviously I'll vote up the best answer otherwise I'll give the code a lookover and see if I can't fix it myself!
Thanks!
UPDATE - Included code
<?php
$admin = 1;
$conn = mysql_connect("localhost","root","password");
mysql_select_db("DB_Default",$conn);
$result = mysql_query("SELECT * FROM users WHERE user_name='" . $_SESSION["user_name"] . "' and isadmin = '". $admin."'");
$row = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["isadmin"] = $row[isadmin];
} else {
}
if($_SESSION["isadmin"] == '1'){
//has admin privs
} else {
//does not have admin privs
}
I have not yet set up the navigation links as I haven't gotten to that stage yet however the links would be inside the if statement admin links in the admin part and not in the non admin part.
My guess right now is going to be the following: You set the $_SESSION variable when you log in as Admin. After that the $_SESSION is never changed. Which pretty much means that if you log in as Admin and then re-log in as someone else, $_SESSION['isadmin'] will already be set to 1 thus providing full access. So what you will need to do is change the else part to:
if(is_array($row))
{ $_SESSION["isadmin"] = $row[isadmin]; }
else
{ $_SESSION['isadmin'] = 0; }

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 get the session id

please help i have the following php code for my login session but i am trying to get the $_session['user_id'] instead of the $_session['email']. i tried print_f function to see what i can use but user_id array says 0 which cannot be right unless i read it wrong.
session_start();
$email = strip_tags($_POST['login']);
$pass = strip_tags($_POST['password']);
if ($email&&$password) {
$connect = mysql_connect("xammp","root"," ") or die (" ");
mysql_select_db("dbrun") or die ("db not found");
$query = mysql_query("SELECT email,pass FROM members WHERE login='$email'");
$numrows = mysql_num_rows($query);
if ($numrows!=0) {
// login code password check
while ($row = mysql_fetch_assoc($query)) {
$dbemail = $row['login'];
$dbpass = $row['password'];
}
// check to see if they match!
if ($login==$dbemail&&$password==$dbpass) {
echo "welcome <a href='member.php'>click to enter</a>";
$_SESSION['login']=$email;
} else {
echo (login_fail.php);
}
} else {
die ("user don't exist!");
}
//use if needed ==> echo $numrows;
} else {
die ("Please enter a valid login");
}
i am trying to get the $_session['user_id'] instead how can get this to use instead of $_session['email']. tried using $_session['user_id'] but instead i got undefined error msg.
Well, you don't define $_session['user_id'] anywhere in this script, so it's no surprise that it's not defined. You have to assign it a value before you can refer to it.
Also, note that there all kinds of security problems with this code.
You're running your MySQL connection as the root user. This is NOT a good idea.
You're trusting user input, which opens your script up to a SQL injection attack. Stripping HTML tags from the user input does not make it safe. Suppose that I came to your site, and filled in the "email" field with this:
bob#example.com'; GRANT ALL PRIVILEGES ON *.* TO 'evil_bob' IDENTIFIED BY '0wned_joo';
As currently written, your script would happily run its query as normal, and also create an account called "evil_bob" with full privileges to all the information in all of the databases on your server.
To avoid this, NEVER assume that user input is safe. Validate it. And to be extra sure, don't stick variables straight into SQL you've written. Use bound parameters instead. There are a few cases where it's hard to avoid -- for example, if you need to specify the name of a column rather than a piece of data, a bound parameter will not help and you'll have to do it some other way. However, for any piece of data you're using as part of a query, bind it.

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