Solved

where is $sid defined?

Posted on 2014-03-06
26
259 Views
Last Modified: 2014-03-13
from larry ulman php tutorial

where is $sid defined?

<?php # Script 3.1 - db_sessions.inc.php

/* 
 *  This page creates the functional interface for 
 *  storing session data in a database.
 *  This page also starts the session.
 */

// Global variable used for the database 
// connections in all session functions:
$sdbc = NULL;

// Define the open_session() function:
// This function takes no arguments.
// This function should open the database connection.
// This function should return true.
function open_session() {
    global $sdbc;
    
    // Connect to the database:
    $sdbc = mysqli_connect ('localhost', 'username', 'password', 'test');
    
    return true;
} // End of open_session() function.
 
// Define the close_session() function:
// This function takes no arguments.
// This function closes the database connection.
// This function returns the closed status.
function close_session() {
    global $sdbc;
    
    return mysqli_close($sdbc);
} // End of close_session() function.

// Define the read_session() function:
// This function takes one argument: the session ID.
// This function retrieves the session data.
// This function returns the session data as a string.
function read_session($sid) {
    global $sdbc;

    // Query the database:
    $q = sprintf('SELECT data FROM sessions WHERE id="%s"', mysqli_real_escape_string($sdbc, $sid)); 
    $r = mysqli_query($sdbc, $q);
    
    // Retrieve the results:
    if (mysqli_num_rows($r) == 1) {
        list($data) = mysqli_fetch_array($r, MYSQLI_NUM);
        
        // Return the data:
        return $data;

    } else { // Return an empty string.
        return '';
    }
} // End of read_session() function.

// Define the write_session() function:
// This function takes two arguments: 
// the session ID and the session data.
function write_session($sid, $data) {
    global $sdbc;

    // Store in the database:
    $q = sprintf('REPLACE INTO sessions (id, data) VALUES ("%s", "%s")', mysqli_real_escape_string($sdbc, $sid), mysqli_real_escape_string($sdbc, $data)); 
    $r = mysqli_query($sdbc, $q);

	return true;
} // End of write_session() function.

// Define the destroy_session() function:
// This function takes one argument: the session ID.
function destroy_session($sid) {
    global $sdbc;

    // Delete from the database:
    $q = sprintf('DELETE FROM sessions WHERE id="%s"', mysqli_real_escape_string($sdbc, $sid)); 
    $r = mysqli_query($sdbc, $q);
    
    // Clear the $_SESSION array:
    $_SESSION = array();

    return true;
} // End of destroy_session() function.

// Define the clean_session() function:
// This function takes one argument: a value in seconds.
function clean_session($expire) {
    global $sdbc;

    // Delete old sessions:
    $q = sprintf('DELETE FROM sessions WHERE DATE_ADD(last_accessed, INTERVAL %d SECOND) < NOW()', (int) $expire); 
    $r = mysqli_query($sdbc, $q);

    return true;
} // End of clean_session() function.

# **************************** #
# ***** END OF FUNCTIONS ***** #
# **************************** #

// Declare the functions to use:
session_set_save_handler('open_session', 'close_session', 'read_session', 'write_session', 'destroy_session', 'clean_session');

// Make whatever other changes to the session settings, if you want.

// Start the session:
session_start();

Open in new window



<?php # Script 3.2 - sessions.php

/*  This page does some silly things with sessions.
 *  It includes the db_sessions.inc.php script
 *  so that the session data will be stored in a database.
 */
 
// Include the sessions file:
// The file already starts the session.
require('db_sessions.inc.php');
?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>DB Session Test</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<?php
// Store some dummy data in the session, if no data is present:
if (empty($_SESSION)) {

    $_SESSION['blah'] = 'umlaut';
    $_SESSION['this'] = 3615684.45;
    $_SESSION['that'] = 'blue';
    
    // Print a message indicating what's going on:
    echo '<p>Session data stored.</p>';
    
} else { // Print the already-stored data:
    echo '<p>Session Data Exists:<pre>' . print_r($_SESSION, 1) . '</pre></p>';
}

// Log the user out, if applicable:
if (isset($_GET['logout'])) {

    session_destroy();
    echo '<p>Session destroyed.</p>';
    
} else { // Otherwise, print the "Log Out" link:
    echo '<a href="sessions.php?logout=true">Log Out</a>';
}

// Reprint the session data:
echo '<p>Session Data:<pre>' . print_r($_SESSION, 1) . '</pre></p>';

// Complete the page:
echo '</body>
</html>';

// Write and close the session:
session_write_close(); 
?>

Open in new window



Open in new window

0
Comment
Question by:rgb192
  • 9
  • 9
  • 8
26 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39911701
It isn't. $sid is the unique session ID used to identify the session being worked with.

I imagine this could be any unique identifier you use to identify a session with.

If you want to know in this particular example where $sid is coming from then look to see where write_session is called from - that should give a clue.

Failing that - any unique identifier that matches the type of the id field in the database will work.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39912167
PHP has a predefined constant SID.  Is that what you're looking for?
http://www.php.net/manual/en/session.constants.php
0
 

Author Comment

by:rgb192
ID: 39913203
So there is a function write_session which is missing from code block?
Is $sid pre defined?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39913435
$sid is a PHP user variable name.  It has no meaning out of context, any more than $xyz would have.  It's undefined in the code snippets.  My guess is that it is some kind of session ID, but that's just a guess.

Why not use the PHP session handler?
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11909-PHP-Sessions-Simpler-Than-You-May-Think.html
0
 

Author Comment

by:rgb192
ID: 39913582
I voted Ray article helpful. I saw session_write_close(). In tutorial Where is $sid defined.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39913629
$sid is not defined in anything we have here.  It's used as an argument in function definitions in the code snippet.  It could just as well be $xyz, so long as the variable is used in a consistent manner with the same semantic meaning.  My guess is that there is some other part of these scripts that would help you make sense of $sid.
0
 

Author Comment

by:rgb192
ID: 39914186
$sid is not defined in anything we have here.  It's used as an argument in function definitions in the code snippet.  It could just as well be $xyz, so long as the variable is used in a consistent manner with the same semantic meaning

I think I am asking the value that gets passed to function and stored as $sid.
From your quote I know that $sid is a predefined constant.


from the larry ulman tutorial
i run in nusphere phped ide
Script 3.2 - sessions.php
which only calls
Script 3.1 - db_sessions.inc.php

select id,data,last_accessed from sessions
23n4bpd37374rf7ng5piutjtf1	blah|s:6:"umlaut";this|d:3615684.450000000186264514923095703125;that|s:4:"blue";	2014-03-06 23:39:42
94pof7nqupfoch6j4t6096t7u1	blah|s:6:"umlaut";this|d:3615684.4500000002;that|s:4:"blue";	2014-03-06 23:37:32
lgjcej7osg69dcusjphbc1knk7	blah|s:6:"umlaut";this|d:3615684.450000000186264514923095703125;that|s:4:"blue";	2014-03-06 23:38:40

Open in new window


I can not find the sessions.id value hardcoded anywhere in the script

I have run in nusphere ide, internet explorer, google chrome

how does the script know sessions.id
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39914303
From your quote I know that $sid is a predefined constant.
What quote?

The $sid is not a predefined constant - it cannot be constant.

$sid is the name of a parameter to a function.
function write_session($sid, ...) {
}

Open in new window

Which means I can call it like this
write_session('123455666', ...);

Open in new window

Or like this
$id = session_id();
write_session($id, ...);

Open in new window

Or anyway I like. The parameter does not imply that anything is defined - all it is saying is the function accepts a parameter called $sid.

We can deduce from the code that this value is a unique session ID that is being used to save a session to a databse but we cannot know

a) What the author is using as a session ID (how it is generated)
b) What the name of the variable passed to the function is on the calling side.

What you need to be doing is searching your script for the functions
write_session
delete_session

Open in new window

etc

And then look to see what those variables those function calls are passing through.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39914394
In PHP, variables start with the dollar sign.  Since $sid starts with a dollar sign, it is recognizable as a variable.  A variable is not the same thing as a constant.

Variables:
http://php.net/manual/en/language.variables.php

Constants:
http://php.net/manual/en/function.define.php
http://php.net/manual/en/language.constants.php

The sessions.id seems to be a data base table name, followed by a column name.  Not sure of that, but that would be one explanation.  It's not a PHP data construct as far as I can tell.

I think if I were you, I would put this whole thing aside until you find that the standard PHP session handler cannot meet your requirements.  You're working hard on something that will have very little applicability in the "real world."
0
 

Author Comment

by:rgb192
ID: 39915133
http://www.experts-exchange.com/viewCodeSnippet.jsp?refID=39914186&rtid=20&icsi=1

each of my 3 browsers has the same session.id
where is this hardcoded

is there a cookie?


You're working hard on something that will have very little applicability in the "real world."
I wish I knew which parts of the larry ulman book were important, but I do not know yet because I do not fully understand the tutorial
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39915722
is there a cookie?
Yes
Sessions have to use cookies or URL parameters. Cookies are more common.

I think the book sample is still relevant - it depends on how you want to manage your sessions.

If you use the default PHP functionality - your sessions will be maintained in memory by PHP. The session terminates when your browser session terminates or a session timeout occurrs - usually a period of inactivity.

This may be suitable for your requirements and in some cases desirable - for instance - you do not want a session to persist when accessing your bank online.

But in other instances it may not be suitable. For instance a shopping site - if your clients put items in their cart and then close the browser - you may want to remember that cart the next time they visit the site. Conventional sessions won't work. In this case you need to persist your session data in a database using the session ID as an index. The session ID is stored in the cookie and retrieved everytime a visitor visits your site. If present it is used to load state information from the database.

I suspect the tutorial you looking at now covers this aspect of sessions - persisting the data in a database so that it is available the next time the visitor visits the site.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39915781
each of my 3 browsers has the same session.id
I find that very hard to expect in any kind of a real-world application, unless the "3 browsers" are instances of the same browser program (eg, 3 instances of Firefox).  In that case it would make perfect sense, as was previously explained in the article about sessions.  I don't fully understand what is in the file you linked - the query posted above says select id,data,last_accessed from sessions and the id fields seem to contain these 3 different values, implying that there are different session.id values:

23n4bpd37374rf7ng5piutjtf1      
94pof7nqupfoch6j4t6096t7u1      
lgjcej7osg69dcusjphbc1knk7

where is this hardcoded
The session id does not need to be hardcoded, and should not be hardcoded.  It is typically generated by the server and sent to the browser in a cookie.  On the browser it becomes a tool that lets the client say, in effect, "Here I am again."  On the server, it is a key to a row in a data base or a /tmp/ file that contains the session data. The session must uniquely identify the client, so that the server can connect its stored client data to a new client request.  It follows that a hardcoded session id would not really make sense.  The article here about client/server protocols may help you understand how that works.

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html

And the article here about PHP client authentication may help, too.  See the part about the "remember me" cookie.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

is there a cookie?
Yes, almost certainly.

One would never want to use a PHP session for a shopping cart.  It's not built for that (although if you look around you can find plenty of unsuccessful shopping cart sites that use the PHP session, probably because they were built by amateurs who did not understand human-computer interaction and did know any better).  The PHP session is a shorthand way to persist stateful information across subsequent, repeated requests, and as such, is very limited in scope.  To see the difference between the professional solutions and the amateur solutions, visit http://www.amazon.com and put something in your shopping cart, then visit http://www.culinarycookware.com/ and do the same.  Go get a sandwich (anything that keeps you away from the computer for more than 24 minutes).  Then come back and see what is in your shopping cart.  The professional solution remembers your information; the lame amateur "solution" has already forgotten you.
0
 

Author Comment

by:rgb192
ID: 39915981
okay, now I am understanding better

I found the cookie
where is the command to assign the value in the cookie
 to
sessions.id in mysql
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39916127
It's somewhere in the Ullman book.  It's not anywhere in the code posted here.  In the code posted here $sid is undefined.
0
 

Author Comment

by:rgb192
ID: 39916549
sorry I forgot to post 3.2 sessions.php

<?php # Script 3.2 - sessions.php

/*  This page does some silly things with sessions.
 *  It includes the db_sessions.inc.php script
 *  so that the session data will be stored in a database.
 */
 
// Include the sessions file:
// The file already starts the session.
require('db_sessions.inc.php');
?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>DB Session Test</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<?php
// Store some dummy data in the session, if no data is present:
if (empty($_SESSION)) {

    $_SESSION['blah'] = 'umlaut';
    $_SESSION['this'] = 3615684.45;
    $_SESSION['that'] = 'blue';
    
    // Print a message indicating what's going on:
    echo '<p>Session data stored.</p>';
    
} else { // Print the already-stored data:
    echo '<p>Session Data Exists:<pre>' . print_r($_SESSION, 1) . '</pre></p>';
}

// Log the user out, if applicable:
if (isset($_GET['logout'])) {

    session_destroy();
    echo '<p>Session destroyed.</p>';
    
} else { // Otherwise, print the "Log Out" link:
    echo '<a href="sessions.php?logout=true">Log Out</a>';
}

// Reprint the session data:
echo '<p>Session Data:<pre>' . print_r($_SESSION, 1) . '</pre></p>';

// Complete the page:
echo '</body>
</html>';

// Write and close the session:
session_write_close(); 
?>

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39916815
sorry I forgot to post 3.2 sessions.php
No you didn't it is in your original post

This code has no relation to the original code you posted other than it happens to deal with sessions.

It does not call any of the functions defined db_sessions.inc.php
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39916924
Looks like $sid is still undefined.  You can discern this by using a "find" command in your text editor or IDE.  Make sure your current line pointer is at the top of the file, and the direction of the scan is pointed down, then execute a find command to look for the string $sid.

You might also want to be careful about code like this.  It almost looks like the code mistakenly assumes that session_destroy() implements the logout functionality.  That's not the case.  
// Log the user out, if applicable:
if (isset($_GET['logout'])) {

    session_destroy();
    echo '<p>Session destroyed.</p>';
    
}

Open in new window

To make a client be "logged out" your script must remove two things that are not removed by session_destroy().  It must remove the data from the $_SESSION array (or your database, if you've complicated your life by trying to write your own session handler).  And it must remove the session cookie from the client browser.  

The first removal can be done with something like this, but be careful if you want to keep other persistent information in the session:
$_SESSION = array();

Open in new window

The second removal can be done with setCookie().  It's exact sequence is documented in this article.  It will look something like this:
setcookie(session_name(), '', time()-86400, '/');

Open in new window

0
 

Author Comment

by:rgb192
ID: 39917957
where is the command in either of the files that reads the cookie to get id

and Ray wrote about setting cookie.  

I can not find the command that sets the cookie


Are these spl libraries where code is hidden.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39918295
I must apologise - I missed this line of code in the script for db_sessions
// Declare the functions to use:
session_set_save_handler('open_session', 'close_session', 'read_session', 'write_session', 'destroy_session', 'clean_session');

Open in new window

The above line is assigning custom functions for the reading, opening, writing and destroying of the session.

So to answer your question $sid is being passed into these functions by PHP in other words

If you were using default session handling in PHP then PHP would make use of its own internal functions to write / update / delete sessions. All you would need to do was have a
session_start()

Open in new window

In your code. In this example you define the code to open / read / write / destroy - and PHP passes the session ID to you - PHP manages the cookie for you.

In this example the author is demonstrating two things

1. How to create your own custom session handling functions and how to wire them into PHP's internal session management

2. How to persist session data in a database

The second part is illstrative only - if you wanted to implement a useful version you would need to maintain your own cookies to ensure the sesssion persists beyond a browser close - but don't worry about that for now.

Rather focus on the session_set_save_handler and the concept of defining your own session handling functions.

You can read more here http://lv1.php.net/manual/en/function.session-set-save-handler.php
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39918353
where is the command in either of the files that reads the cookie to get id
Scan the source code for $_COOKIE.  It's a reserved name in PHP (unlike $sid) so it may give you a strong clue.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39919633
I doubt you will find COOKIE in the code for reasons I raised in my previous post.
0
 

Author Comment

by:rgb192
ID: 39920854
I do not understand larry ulman chapter 3 code 3.1 and 3.2

Is there some sort of magic method

like __autoload(), __tostring() that connects to a library I can not see


maybe 3.2 line 52 session_write_close()
creates a cookie or looks at existing cookie for sessions.id
or magically calls
3.1 line 40 with a parameter $sid
function read_session($sid) {


running in nusphere php ide line by line debugger
I understand every step until code reaches 3.1 line 40 and there is already a method call with a parameter so $sid has a value inside function/method read_session($sid) {

what calls this?
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 39921409
I don't know.  I don't know how to help you research this, beyond what I've written already.

There is no assignment of $sid in the code of 3.1 or 3.2.
There is no use of COOKIE in the code.

Maybe you can find some ideas in the user-contributed notes here.  It looks like most of the documentation is for PHP 5.4+ but some of the notes reach back to earlier releases.
http://php.net/manual/en/function.session-set-save-handler.php

There are a couple of instances of use of $_SESSION in the code of 3.2, but it's not clear to me whether this would make any sense.  Here is some of the code.  It seems to be able to modify these array elements, but only if the $_SESSION array is empty.
<?php
// Store some dummy data in the session, if no data is present:
if (empty($_SESSION)) {

    $_SESSION['blah'] = 'umlaut';
    $_SESSION['this'] = 3615684.45;
    $_SESSION['that'] = 'blue';
    
    // Print a message indicating what's going on:
    echo '<p>Session data stored.</p>';
    
} else { // Print the already-stored data:
    echo '<p>Session Data Exists:<pre>' . print_r($_SESSION, 1) . '</pre></p>';
}

Open in new window

Like I said earlier,
I think if I were you, I would put this whole thing aside until you find that the standard PHP session handler cannot meet your requirements.
I know this is supposed to be a learning exercise for you, but sometimes it's' best to just move on if you're stuck.  You can come back to it later with "fresh eyes."
0
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
ID: 39921558
maybe 3.2 line 52 session_write_close()
creates a cookie or looks at existing cookie for sessions.id

Don't get sidetracked with the cookie issue.

The session_write_close function does the following.

It replaces the internal session management functions in PHP with functions you write your self in this case the
function open_session()
function close_session()
function read_session()
function write_session()
function destroy_session()
function clean_session()

Open in new window

These functions are called by PHP to handle various aspects of the session management process. In each case PHP passes through $sid - a session variable it manages in the background.
All this tutorial is doing is showing you how to override the default session management process in PHP with your own session management code. However, PHP still manages the session ID aspect of this for you i.e. it tracks the cookie and looks after that side for you - all your code needs to do is handle the various session operations when required.
0
 

Author Closing Comment

by:rgb192
ID: 39928430
thanks for advice I will move on to other chapters.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39928496
For anyone reading this thread the correct answer was 39921558

The question was where is $sid defined - the answer is it is not - it is passed to the session management functions by PHP. The tutorial is to demonstrate how to setup custom session handler functions.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
This article discusses how to create an extensible mechanism for linked drop downs.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now