Jump to content

Start Session only if parameter exists


StevenOliver

Recommended Posts

I've been wrestling with this logic puzzle for days... My website lists item prices as they are posted:

First item:
item# ABC1234 = Hammer $5.00

Visitor then submits (to the same page) more item numbers (e.g. item# DEF9999) and the displayed list will grow:

item# ABC1234 = Hammer $5.00
item# DEF9999 = Crowbar $6.00

---------------------------------------

However, when website gets visited via Affiliate, I want PHP to launch a Session to "remember" the First Referred Item, along with the Affiliate:

// http://www.example.com/salePrice.php?Affiliate=SomeExampleCompany&item=ABC1234

<?php
if(isset($_GET["Affiliate"])) {
session_start();
$_SESSION["Affiliate"] = sanitized($_REQUEST["Affiliate"]);
$_SESSION["item"] = sanitized($_REQUEST["item"]);
}
?>
<body>
<form action="salePrice.php" method="post">
etc. etc. etc.

The problem: Session won't stay running if visitor subsequently posts more items to the same page. (I thought once a Session starts, the Session will run as long as you don't navigate away from the page.)

Without having to put "session_start()" on the top of the page (and have Sessions running no matter what), what is the trick to get this to work?

Edited by StevenOliver
Made question more concise. One thing I've learned is that it shows respect to the reader if the person asking the question takes the time to make the question readable and concise.
  • Like 2
Link to comment
Share on other sites

The session may not be "running" but it is still there. You can session_start on a later page, and as long as the user hasn't been idle for too long (and the session got garbage collected) the data will still be there.

11 minutes ago, StevenOliver said:

One thing I've learned is that it shows respect to the reader if the person asking the question takes the time to make the question readable and concise.

omfg yes

Link to comment
Share on other sites

To make what work? If you want session data available then you have to session_start, which will create a new session if there isn't one. If you don't want session data available then don't session_start it. If you don't make it available on one page, an existing session from a previous page will still be around if you want to use it again on a later page.

Link to comment
Share on other sites

Why even worry about starting the session periodically?  Simply Start the Thing at the top of every script.  It's ONE line of code!  If you don't use it, fine.  If you do, fine.  And don't even worry about getting rid of it since when the script exits the session will be closed down (and saved for you) by PHP itself.

Link to comment
Share on other sites

ginerjm

6 hours ago, ginerjm said:

Why even worry about starting the session periodically?

Good question. Because I wanted to see if it could be done. I do my own coding because it is fun. I enjoy the challenges. I wanted to see if I could code it so that a session only started if there was an Affiliate referral. And keep that session data handy while on the page.

Unfortunately, because the page submits to itself (action="<?=$_SERVER['PHP_SELF']?>" ), there is no "if statement" to check for session data ($_SESSION["affiliateData"]) without starting a session to read the session affiliate data.

I have discovered/found this to be impossible.

But it was fun trying. If I just wanted to "get the job over with" I'd simply code my page with a hidden input (<input type="hidden" name="blah" value="EncryptedConcatenatedAffiliateAndProductName"> and be done with it.

Sure,  can go ahead and stick a permanent session_start() at the top of my page, but 1.) I still want to keep trying to NOT do that, and 2.) Silly to start a session for just one string of code.

I'm open to help on this though :-)

 

Link to comment
Share on other sites

If you want to know whether there's affiliate data, and not counting what's in the session, then you just have to pass it through the form every time. Which you're kinda doing by using PHP_SELF. Except your form is POSTing and you're looking for the affiliate in the URL. It won't be there. But in the real world the URL tends not to persist like that (PHP_SELF is discouraged for assorted reasons) so the session tends to be the answer in the end.

But yeah, just session_start() all the time. It's easy. There's no real reason not to.

Link to comment
Share on other sites

I have tried in my career to gain an understanding of things at the most granular level possible, which at time involves breaking down the components of a larger system or making an effort to demystify a process that might initially seem to be complicated and confusing.

I was reminded of this when you described a session as "running."  A session doesn't run and isn't really what you seem to think it is, but to understand this better, you also need to be clear on how HTTP protocol works, and how web servers and web browsers interact.  If you aren't clear on for example, what HTTP headers are, what cookies are and where and how cookie data is provided, and how PHP scripts work, then you might need to do some investigation into those fundamentals to fully understand my points, but I'll take a stab at the topic regardless, in hopes it might shed some light.

By default sessions are really the manifestation of 2 simple concepts:

  1. PHP can examine a client request and look for a session id.  This could be a url parameter, but by far the preferred method, is to read it from cookie data.   I will just state that for the record, the way cookies work is that when a browser makes a request, it looks at the domain it's requesting, and IF it has cookie data stored for that domain, it sends all that cookie data in every request  (in the HTTP header of its request).  For this reason, once the server provides a session id, the client will pass this Id back to the server in every request, until such a time as the cookie expires.  Essentially the session Id can be thought of as a locker key that opens a locker and can be used to add, view or remove items from the locker.  
  2. PHP has the ability to take a set of variables in memory and "serialize" them.  Take a look at the php serialize() function to understand how this works.  By default, a PHP session is nothing more or less than the $_SESSION array run through serialize and stored in a text file on the server.

What PHP does for you, is associate that serialized file with the session Id that is transparent to you.  The session files also have expirations and garbage collection rules that get triggered when a PHP script runs which may or may not remove expired session files.  

The lifetime of a PHP script is typically very short.  When a request resolves to a PHP script, the server runs the PHP script, doing whatever initialization it needs, including reading HTTP request headers and associated data into the various "superglobal" variables like $_SERVER, $_COOKIE, $_GET, $_POST etc.  IF the script starts with session_start(), then PHP looks for the session Id (which it gets from a cookie) and if found, tries to find an associated session file.  Should that session file exist, PHP reads the file from the file system, runs unserialize() on it, and stores the contents in the $_SESSION variable.

The only "magic" involved in PHP session functionality is this:  While your PHP script is running (and the session system was instantiated via session_start()) if you store something to the $_SESSION superglobal variable, PHP will overwrite the session file with the serialized contents, so in a way you could think of the saved session file as being the most current snapshot of the $_SESSION array.  

When the script completes, there is nothing running --- just a file that is sitting on the filesystem of the web server.  

A session id can be anything you want it to be, but by default it is an md5() hash of a few different things that concatenated together should be unique.   This provides enough obfuscation so that someone trying to attack the system has no real chance to guess another user's session Id.  When a request is made to a script that begins with session_start(), if a session does not exist, then PHP will generate a session id, initialize a session file for future storage, and it will then provide the session id in a set-cookie header.  

So when you understand how this all works, you might realize that there is a way to build your "session optional" mechanism, keeping in mind of course that sessions aren't some magical persistent process running on the server.   What you could do is rather than depending on a session to store your affiliate id,  store the affiliate Id as a cookie.  You would then session_start() only when the 'affiliate_id' cookie exists.  This is not that different from how PHP itself, only attempts to find and unserialize the session data, when the browser request includes the session Id cookie.

As others have pointed out, it's a lot of effort for very little gain, as the overhead is typically minimal, however it is not uncommon to see large sites implement some variation on this idea, to avoid creating sessions in cases when they are not wanted.   

 

 

 

 

Link to comment
Share on other sites

8 hours ago, gizmola said:

...making an effort to demystify a process...

A  compliment to you is in order! You saw the reason for my question when I didn't even see the reason myself.

Here's the reason: we all build "concepts" to help our minds grasp intangibles... e.g. "my Mac saves files in a folder" or in this case, "the Session is running!"

In my mind, having a session "run" in order to remember just one variable seemed like a "waste." A waste of resources, power, fuel, etc., like keeping a car "running" just to listen to the radio. I wanted to conserve the imaginary resources a "running session" uses!

(In reality, the only 'resource' used when calling "session_start()" is about .001 seconds of time, according to the timer benchmark I have on my page. Total time to load without sessions: .002 seconds. With sessions: .003 seconds.)

But you are correct -- for the reasons you described, sessions don't really "run." And I guess I lost sight of that. ("Don't leave that session running for too long, it will burn up. Not to mention the fumes").

Thank you again!

 

Edited by StevenOliver
  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.