Move mysql Information from one page to another in PHP - php

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']!";
}

Related

Setting a variable via the sessions once logged in

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..

Reusing session variables across multiple pages

I am passing the following variables from a query through a link:
<a href="middle.php?name=<?php echo $name; ?>&id=<?php echo $id1; ?>&rowid=<?php echo $rowid; ?>&record=<?php echo $record; ?>">
The variables are being passed to this page:
session_start();
//$id = ($_GET['id']);
if (isset($_GET["record"])) {
$_SESSION["record"] = $_GET["record"];
}
if (isset($_GET["id"])) {
$_SESSION["id"] = $_GET["id"];
}
if (isset($_GET["rowid"])) {
$_SESSION["rowid"] = $_GET["rowid"];
}
if (isset($_GET["name"])) {
$_SESSION["name"] = $_GET["name"];
}
if (isset($_GET["store"])) {
$_SESSION["store"] = $_GET["store"];
}
and then users are redirected to this page where Im trying to use the assign the session variables to variables in the page like this:
session_start();
$id = $_SESSION[id];
$rowid = $_SESSION[rowid];
$name = $_SESSION[name];
$record = $_SESSION[record];
The variables arent accessible as I need them to be on this page. Am I missing quotes? What is the best way to use the session variables again?
FYI they're mainly being used in other queries like this:
"SELECT * FROM mgap_orders WHERE mgap_ska_id = '" . $_SESSION['id'] . "' AND mgap_status = 0 GROUP BY mgap_ska_report_category LIMIT 5";
Am I missing quotes?
Yes. You say you're accessing them like this:
$id = $_SESSION[id];
That should be this:
$id = $_SESSION['id'];
But even more to the point, why do you need to use session here at all? The way you describe the situation is:
User makes a request with query string values in the link.
In the response you forward the user to another page (presumably using the location header?).
On the last page the values need to be present.
If they're query string values, keep them as query string values in the redirect. So where you may have something like this:
header('Location: somePage.php');
you can include the values:
header('Location: somePage.php?name=' . $name');
and so on for the remainder of the values, just like you do when building the original link for the page which performs the redirect.
Also, while you don't show your data access, you do show your query which appears to be vulnerable to SQL Injection attacks. Ultimately the values you're using are coming from user input (query string) so you shouldn't directly concatenate them into SQL queries.

PHP If Statements With mySQL Results

The code below is supposed to check if there is a person in the database with a row in the database with the username it gets from the cookie login.And if there is it is supposed to include a page and if there isn't a person in the database with this user_id it is supposed to echo.Here is my code so far please tell me how I would do this.I also already know before someone tells me that mySQL statements like I have it are becoming depreciated.Here is My code:
<?php
include("dbconnect.php");
mysql_select_db("maxgee_close2");
$username = $_COOKIE['maxgee_me_user'];
$result = mysql_query("select user_id from users where username = '$username'");
$row = mysql_fetch_array($result);
mysql_free_result($result);
$check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row['user_id']'") or die(mysql_error());
if(1==1){
if (mysql_num_rows($check)>0)
{
include("example.php");
}
else
{
echo "example";
}
}
?>
In the double-quoted string, your array variable $row['user_id'] is being incorrectly parsed due to the fact that you have quoted the array key without surrounding the whole thing in {}. It is permissible to omit the {} in a double-quoted string if you don't quote the array key, but the {} adds readability.
check = mysql_query("SELECT * FROM events_main WHERE user_id ='{$row['user_id']}'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
// Also acceptable, but not as tidy, and troublesome with multidimensional
// or variable keys - unquoted array key
check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row[user_id]'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
As mentioned above, $_COOKIE is never considered a safe value. You must escape its values against SQL injection if you continue to use the old mysql_*() API:
$username = mysql_real_escape_string($_COOKIE['maxgee_me_user']);
2 Things right off the bat, like Waleed said you're open to SQL injection, not very nice thing to have happen to you. I would look into reading tutorials about MySQLi and PDOs, from there try and dive into a better way or running queries.
Also you are choosing to use cookies instead of sessions to store the username? Cookies can be modified client-side to say anything a smart user with firebug would want them to be. Sessions are stored server-side and the client (end-user) is only given an id of the session. They cannot modify the username if you send it as a session. (They could try and change the session id to another random bunch of numbers but thats like pissing into the wind, pardon my french.
Heres some pseduo code that will get you on your way I think
<?php
include("dbconnect.php");
$database = "maxgee_close2"; //Set the database you want to connect to
mysql_select_db($database); //Select database
$username = $_SESSION['maxgee_me_user']; //Grab the username from a server-side stored session, not a cookie!
$query = "SELECT user_id FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "' LIMIT 1"; //Note the user of mysql_real_escape_string on the $username, we want to clean the variable of anything that could harm the database.
$result = mysql_query($query);
if ($row = mysql_fetch_array($result)) {
//Query was ran and returned a result, grab the ID
$userId = $row["user_id"];
mysql_free_result($result); //We can free the result now after we have grabbed everything we need
$query_check = "SELECT * FROM `events_main` WHERE `user_id` = '" . mysql_real_escape_string($userId) . "'";
$check = mysql_query($query_check);
if (mysql_num_rows($check)>0) {
include("example.php");
}
else {
echo "example";
}
}
?>
That code may/may not work but the real key change is that fact that you were running
mysql_free_result($result);
before your script had a chance to grab the user id from the database.
All in all, I would really go back and read some more tutorials.

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