setting up php session (session_set_save_handler) - php

I am trying to set up a user login/logout system using php and mysql. I have found some documentation on the subject here: http://phpmaster.com/writing-custom-session-handlers/. I am trying to follow along with it (I have also been pulling from other sources too - but this is the main one).
Here is some of my code from "my_session_handler.php":
class MySessionHandler implements SessionHandlerInterface {
private $path = session_save_path();
private $name = session_name();
private $sessionId = session_id();
function open($path, $name) {
$db = new PDO("mysql:host=localhost;dbname=itit", "root", "bonjour3");
$sql = "INSERT INTO session SET session_id =" . $db->quote($sessionId) . ", session_data = '' ON DUPLICATE KEY UPDATE session_lastaccesstime = NOW()";
$db->query($sql);
...
My question is, where are the "$path" and "$name" variables coming from in the example I cited above? I declared them as private variables and used some functions to do what I am thinking needs to be done. But on the website that I am following along with - neither of these variables get declared - along with $sessionId. I see that the read function returns $data. So I used it in the "write" function like this:
function write($sessionId, this.read($sessionId)) {
$db = new PDO("mysql:host=localhost;dbname=itit", "root", "bonjour3");
$sql = "INSERT INTO session SET session_id =" . $db->quote($sessionId) . ", session_data =" . $db->quote($data) . " ON DUPLICATE KEY UPDATE session_data =" . $db->quote($data);
$db->query($sql)
}
Am I doing this right?

These parameters are used by the default session save handler, which saves the session data in files. They come from the php.ini file, and are used to form the filenames. They're supplied to your handler when PHP calls the open() method.
If you're writing a custom handler, you can ignore them, as the code on that web page does.

Related

Passing variable/array into WordPress the_content()

I'm looking to pass an array from a separate database within wordpress and echo it out into the content, having a bit of trouble understanding how.
Here is my current code in functions.php:
function get_lead() {
$wpdb = new wpdb('root','password','database', 'localhost');
if ($wpdb->connect_errno) {
die("Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error);
}
// Get lead info
if(isset($_SESSION['lead_id'])) {
global $lead;
$table_name = $wpdb->prefix . 'customers';
$lead = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = '".$_SESSION['lead_id']."'", ARRAY_A));
$error = $wpdb->print_error();
return $lead;
}
}
I originally tried this in a custom php file included in a custom wordpress header via require_once 'filename.php';, here is the code for that:
if(isset($_SESSION['lead_id'])) {
$lead_query = $db->query("SELECT * FROM customers WHERE id = '".$_SESSION['lead_id']."'");
$lead = $lead_query->fetch_assoc();
$lead_query->free();
}
I know this gets the data fine and passing the variable if I place it in header.php and echo out there, but I can't get WordPress to load it into the content within the editor, it's just an empty if I echo $lead['postcode']; there for example.
I've tried setting up a shortcode but can't seem to return an array with that, and the function action doesn't seem to work either, I just get NULL when I var_dump($lead);
It's a 3 step form with a thank you page at the end. I want to echo one piece of data into the first step of the form and two pieces of data onto the thank you page.
Hope this makes sense, any help would be great :)

How do I set the SESSION in function, to use this SESSION everywhere? This isn't working

I've got a problem with a SESSION, inside a function.
How can I set $_SESSION['idUser'] = $result['idUser']; to a SESSION, which I can use for upcoming activity's.
<?php
// Session starts
session_start();
class DB_Functions {
public function getUserByEmailAndPassword($email, $password) {
$result = mysql_query("SELECT * FROM User WHERE emailadress = '" . $email . "'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
//This is the session I want to use
$_SESSION['idUser'] = $result['idUser'];
return $result;
Assuming this is just a snippet of a larger class, I see no reason why this line:
$_SESSION['idUser'] = $result['idUser'];
wouldn't work (again assuming that $result['idUser'] contains a value). Ensure that you have session_start(); called on all pages that you want to use the global session variable.
I suggest using the following in the first place:
Session Management Library
I highly recommend it.
Like you wanted, you could use it everywhere.
It'll keep you from using super globals like $_SESSION (not easy to debug)
Make your code more testable and it'll alleviate you from having to manage sessions manually.
Example code:
use Symfony\Component\HttpFoundation\Session\Session;
$session = new Session();
$session->start();
// set and get session attributes
$session->set('name', $result['id_user']);
$session->get('name'); //Easy to get 'id_user' in another page.
//Other examples:
// set flash messages (appears only once, for warnings/alerts)
$session->getFlashBag()->add('notice', 'Profile updated');
// retrieve messages
foreach ($session->getFlashBag()->get('notice', array()) as $message)
{
echo '<div class="flash-notice">'.$message.'</div>';
}
If you like like what you see here are the links:
Download
Install Instructions
Warning
Make sure your PHP session isn't already started before using the
Session class. If you have a legacy session system that starts your
session, see Legacy Sessions.
Delete the space before <?php. Before session_start() there shouldn't be any output.

PHP variable declaration

I have some simple system to upload files and keep track of them for each particular user, using a database.
The problem of mine is, I connect to the database in the file checklogin.php, which is responsible to handle the $_POST from main_login.php.
In file 'checklogin.php':
$current_user_name = NULL;
which is a global variable for all files. Now in file signup.php, I try to include the checklogin.php to define that variable:
require_once '/checklogin.php';
...
mysql_query("INSERT INTO " . tbl_name . " (username, userpassword, userisadmin)
VALUES (''" . $_POST['myusername'] . "',"
. "'" . md5($_POST['mypassword']). "',"
. "0)");
$current_user_name = $_POST['myusername'];
header("location:login_success.php");
As you can see, I'm trying to set the value of the variable $current_user_name = $_POST['myusername'];, but when header goes to the file login_success.php, which is having require_once '/checklogin.php'; too, the variable is set again to null.
How can I solve this problem? i.e. How can I store the current user so that it is accessible by all files?
You cannot store a variable like that. Each request will be new execution in sever. In this kind situation we have to use session please check this
And another issue with your code is SQL injection, Please read this too
You can not access the Parameter received at checklogin.php
what you can do you can check the the login status and set the current user in session.
From session variable you can access and set the current user.
you can set a session variable for it and on every you can use it like this
session_start();
if(isset($_SESSION['current_user_name']))
{
$current_user_name = $_SESSION['current_user_name'];
}
else
{
$current_user_name = NULL;
}
and set your session variable as follows
session_start();
require_once '/checklogin.php';
////...
mysql_query("INSERT INTO " . tbl_name . " (username, userpassword, userisadmin)
VALUES (''" . $_POST['myusername'] . "',"
. "'" . md5($_POST['mypassword']). "',"
. "0)");
$current_user_name = $_POST['myusername'];
$_SESSION['current_user_name'] = $current_user_name; // set your session here
header("location:login_success.php");

Move mysql Information from one page to another in 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']!";
}

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