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
Related
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..
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.
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.
I have the following code in view.php, I would like to take the information to edit.php without compromising on security or show what is contained in the variables. edit.php has a form to edit the information from the database.
while ($row = mysql_fetch_assoc($result))
{
echo "" . $row['first_name'] ." " . $row['surname'] . "";
echo "<br />";
}
You are already compromising in security - see SQL injection and escaping strings.
Also, it is common practice to include other modules of the application by requiring (see require_once() and require() functions) files. It itself is not a security vulnerability, but indeed encloses all the global variables, functions and classes to that script.
If you really need that, you can unset (see unset()) all the variables you have set, but leave only data you want to be passed.
Learn how to write clean and secure code and it will be secure. Including one PHP file into another is not an insecure practice.
EDIT:
Some start may be creating classes with private or protected properties and public methods, then using them to store sensitive information and execute some actions. By using encapsulation you may achieve what you need.
You should allow only logged in users to see or edit that information, also you might get an SQL injection with:
$first_name = $_POST['first_name'];
$sql_query = "SELECT * FROM employee_master WHERE first_name = '$first_name'";
$result = mysql_query($sql_query, $connection);
You should have instead:
$first_name = mysql_real_escape_string( $_POST['first_name']);
$sql_query = "SELECT * FROM employee_master WHERE first_name = '$first_name'";
$result = mysql_query($sql_query, $connection);
The best way to do this would be(assuming you cant do anything else other than to use a standard anchor link to pass the variable) have an md5 of id of each of your record in the table. So that you can do
while($row = mysql_fetch_assoc($res))
{
echo "" . $row['first_name'] ." $row['surname'] . "";
}
now in edit.php retrieve this and compare it with the hash.
An even more secured way would be to concatenate the id of the record with another unique data such as join date or dob and hash the entire string. It would be highly secure that way.
Option 1: Just past the id from the database via your link. If user knows the id, but doesn't know any other information, than it's useless to it. Using something else will just bring few more code lines.
Option 2: Set user's id in SESSION
$first_name = mysql_real_escape_string( $_POST['first_name']);
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['first_name'] = $first_name;
Then to set other values from the database as session variables, e.g. the user's surname:
$_SESSION['surname'] = $row['surname'];
Then from any other page you can do
if ($_SESSION['loggedin'] == true) {
echo "Welcome $_SESSION['first_name'] $_SESSION['surname']!";
}
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).