Friends Flags…

Free counters!

Sessions

No Sessions

Adding Sessions in WordPress

Please Note: This Is Being Written Into a MUCH BETTER Plugin called TuKod Sessions. Follow The ToKod Sessions Link to see the status of this plugin (Due before April 1, 2012 – No Joke!)

I have been actually writing computer code for four decades (that is 40 years for people who are not aware what a decade it!) :) For those that do not know, that means I was writing computer code before PHP was invented, before search engines, before the Internet, before self starting micro computers were invented too.

“I remember when you had to start them with a crank!”

Well, maybe not that bad! However, I do remember starting a computer by setting switches and pressing enter to get one instruction into memory. Do that for a while to load your “bootstrap” which would then allow you to load a paper tape. A long ribbon of oiled paper that had a series of holes representing computer code. I also remember “Five Cards”, card that had holes read by a computer reader. And amazing audio drives – read that as a cassette tape recorder. Computer Mag-Tape drives, 8 inch “floppy” disks that actually flopped! And all those other amazing computer devices along the way.

So, I am an authentic living Computer Dinosaur! And still writing programs!

I am also quite an expert at search engines. My wife says if the information exists on the Internet, I can find it. Basically, she is right. Imagine what she thought when after days of searching on a number of search engines, I could find no solution on how to add phpBB3 sessions, and their session variables, to WordPress! She quietly said the unthinkable… “Maybe it is Impossible!”

“Maybe it is Impossible!”

That sounds like a challenge and now I have a quest to add phpBB3 sessions to WordPress!

If you have been following what I have been posting lately, my last post involved How to Add PHP Code in Post, Pages, Widgets and even the Excerpt parts of pages. That being solved, I am now taking a step toward getting those phpBB3 session variables into WordPress. The next step is making a reliable way to just have simple sessions.

Session Use

Now WordPress is a “stateless” program. I know that sounds as if it were a refugee of some kind from a tiny lost country! It actually means it just starts each time you call it and end each time it is through. It short, data does not carry over from one access to the next.

However, this could be useful in a plugin, or some code like a shopping cart or a number of other reasons. So let me just make it clear. WordPress does NOT use sessions for the little housekeeping it does. The good news is that you can use sessions, the bad news is it is not so clear how to get them started.

A search around Google and you will quickly find a whole lot of people advising a quick, easy, simple way to start sessions. They say all you need to do is open the wp-config.php file and add a few lines like this…

	// Make session use possible.
	if (!session_id())
		 session_start();

Indeed, at this point in WordPress you could likely get away with just adding the session start. There is really no need to test as WordPress has no sessions and nothing else is started at this point. So this code would work as well.

	session_start();

Then all these people add a line in their blog that says something like:

“I think the best place to add these lines is at the top of the config file, so immediately after the php starting tag (<?php).”

That line came from the “Frank Verhoeven Webdevelopment Blog”

I can just imagine people adding session_start(); to the bottom of the wp-config.php file and it doesn’t work, so they move it to the top and it works! Now all the boggers tell each other and pretty soon, it is a standard. I have read sites that say…
“the session_start(); MUST be on the very next line following the <?php” – Sorry but I do not believe that!

Actually, you can put the session_start(); code inside your wp-config.php file anywhere before the line that has the require_once(ABSPATH . ‘wp-settings.php’); code.  Go ahead, try it, it works! However, the top after the <?php line should be a good place.

Sessions Aren’t Configurations

Of course, session_start(); is NOT a configuration! Ever notice how nice and neat WordPress is organized. That is part of what makes it so powerful. It is organized!

Now go back to those blogs with the above recommendation and you will find people who say, thanks a lot and others who say, it didn’t work for me. Why does it work on some and not on others. Why doesn’t it work for everybody. Simply, because it is in the wrong place.

Register Globals Strikes Again!

In Star Wars, The Empire Strikes Back, but in WordPress, Register Globals Strikes Again.

Ask the average WordPress owner if they have register_global enabled and you will get a bit of a blank stare and something like, “What’s that?”

For the record, you are better to have register_global disabled. Not to worry, if register_global is enabled, WordPress will take care of it for you! After it loads your configuration file, it starts checking all the settings. WordPress calls function wp_unregister_GLOBALS(). Inside this function (inside wp-includes/load.php), if register_global is enabled, it “unregisters” it and the content of the session variable will be deleted.

So if you start sessions in the wp-config.php file, and register_global is enabled, then the session you just started will be deleted before you can use it!

INIT To The Rescue!

The best solution seems to me is to initialize or call the “session_start()” from the “init” action hook. Sure, you could go off hacking a lot of files. Perhaps the header file, or any number of other places you could add this before output to the client starts. It just seems like a very bad idea to modify WP Core files for the ability to use sessions.

If you were writing a plugin you could add a few lines like this…

function alan_init_session()
{
	if (!session_id())
		session_start();
}

	add_action('init', 'alan_init_session', 1);

Of course aLan is my name so feel free to change that to something else. If you want, my dog gives you express permission to use her name, Chester! (Yes, she is a girl!)

That “1″ at the end of the add_action tells WordPress to make sure this runs first. For example, before any plugins or widgets send anything to the client!

You could put that code inside your theme’s function.php file. Of course, every time you upgrade your theme you will have to do it all over again. And if you forget you will break your site. If you are making your own theme this may be a good option. But if you are using someone else’s theme… Think again.

A Sessions Plugin!

The very obvious solution is to simply write a sessions plugin! You would just upload it like any other plugin and it would only have one job, to start sessions!

I’ll start on that plugin after a good night’s sleep…

================

Here it is. Just copy this into a file called alan_sessions.php and upload it to your plugin directory. Then activate it on your WordPress Plugins page.

Please Note: This Is Being Written Into a MUCH BETTER Plugin called TuKod Sessions. Follow The ToKod Sessions Link to see the status of this plugin (Due before April 1, 2012 – No Joke!)

alan_sessions.php

<?php
/*
Plugin Name: Alan Init Session
Plugin URI: http://alantait.net/2011/03/17/adding-sessions-in-wordpress/
Description: This Plugin simply starts PHP Sessions at the right place and time.  It can be used for those who need sessions on custome pages or in a custom plugin.  This seems like a simple program and it is, but it is also valuable to those who need it.
Version: 1.0
Author: aLan Tait
Author URI: http://alantait.net/
*/

function alan_init_session()
{
	if (!session_id())
		session_start();
}

add_action('init', 'alan_init_session', 1);

Please Note: This Is Being Written Into a MUCH BETTER Plugin called TuKod Sessions. Follow The ToKod Sessions Link to see the status of this plugin (Due before April 1, 2012 – No Joke!)

Testing The Sessions Plugin!

If you are Using the Exec-PHP Plugin From My Last Post you can put this in a Text Widget to test if sessions are really on or not. It just says Sessions or No Sessions.

Text Widget

<?php
if ( !session_id() ) {
     echo 'No Sessions';
}else{
     echo 'Sessions';
}
?>

I hope you enjoy this!

 

Codifically,

Lan

Please Note: This Is Being Written Into a MUCH BETTER Plugin called TuKod Sessions. Follow The ToKod Sessions Link to see the status of this plugin (Due before April 1, 2012 – No Joke!)

13 comments to Adding Sessions in WordPress

  • I have your plugin installed, but the text widget does not return anything.
    I am using WordPress 3.1.3
    Do you have any suggestions?

    Thanks

  • Lan

    Do you have the Exec-PHP Plugin From My Last Post – see the link in Testing The Sessions Plugin above. the Exec-PHP Plugin must be installed and working…

  • Hatem

    Hi ..

    I do this action on my own plugin. and still the sessions not working. I’ll try to output my session variable but it couldn’t !!!!!

  • davidm

    Hi What happened if the paper tape tore or you dropped the deck of punched cards with your program on them? especially a long program with more than a couple of hundred cards?
    Those where the days I’ve been at this since the 1960s and it’s still magic.
    Back to PHP sessions. Mine aren’t working.
    I put your code for session start in functions.php,
    I’m using something called “shortcode exec php” I assume that’s the exec php you’re talking about.
    Well I’ve entered the following code there to get the page id:

    extract(shortcode_atts(array(‘arg’ => ‘default’), $atts));
    $_SESSION['pageID'] = get_the_ID();
    echo “page id =” . $_SESSION['pageID'] . PHP_EOL;
    if ( !session_id() )
    echo “no session_id” . PHP_EOL;

    and its outputting:

    page id=112 no session_id

    Why do you think that’s happening?

    Thanks for any help

    David

    • Lan

      Exec-PHP is a plugin you can find here:

      http://wordpress.org/extend/plugins/exec-php/

      If the paper tape tore we would tape it together and hand punch the holes and immediately punch a copy, of course in production we kept backup tapes.

      I dropped a stack of cards once and spent hours sorting them by hand! Later I dropped a tray of cards, and figured out a way to use the machine sorter to re-stack them. It took about 20 passes, but was finished in just over an hour with only one error (a card was lost under a cabinet). After that I learned why the trays have lids and never carried a tray without a lid again!

  • davidm

    The reason I’m using sessions is to pass the page id from page A to page B – so I know where I’m coming from, if you know a simpler way that would also help

    Thanks

    David

    • Lan

      Sorry about the slow reply, I was just laying around on vacation (read that Perceptual Succor Hospital having a surgery!).

      PHP has a lot of ways to pass info from page to page. Like hidden inputs or URL parameters. You could also use the http-referer – but people can mess with that so be aware of that.

  • Hi, it helps to have someone to talk to. My session is now working, why? I’m not sure, here’s what happened maybe you can explain it to me.
    I went to the wordpress dashboard appearence>editor
    found functions.php put your code in and nothing happened no session started. Then I went to the control panel > File Manager root/wp-content/themes/myTheme and edited Functions.php expecting to find your code there but there was nothing so I inserted your code and now everything works – thank you.
    My question now is how come it’s not the same functions.php file and how do I know which one to use?
    Have a nice day

    David

    • Lan

      Hummm… Good question…

      Actually David, I have not used that dashboard appearance > editor. Perhaps it puts it in a database to late to be any good? That is just a wild guess!

      I have an aversion to editing theme files, because all my sites are on multi-site / multi-networks. Edit one theme page and it effects 30+ sites!

      That is why I wrote it into the small plugin – safe and secure. My guess is when you added it to the real functions.php page, it got loaded earlier and so you had no problems.

      If I were you I would still use the plugin, or add the code to your own custom plugin, it is easier and gets run where it needs to be.

      Lan

  • I’ve tested it and it works perfect, thanks. Just wanted to mention that if you’re copy pasting everything from your post, you still need to change the single quotes, they are replaced somehow by not working characters.
    All my errors disappeared with deleting and retyping the quotes.

    • Lan

      Thanks Parbir and Pieter!

      Yes, the single quotes need to be replaced by single quotes! Or you may replace them with double quotes if you know the difference! :)

      The problem started with a plugin called SyntaxHighlighter Evolved, it evolved into a worse and worse problem. For a reason I do not know, it changed the single quotes into stylized single quotes, which will not work! I finally decided to just stop using and remove SyntaxHighlighter Evolved. That solved the problem I was having but it created another problem… This problem!

      All single or double quote characters need to be replace if you copy any code that is between [php][/php] brackets on this website or T8S.ORG

      I am getting them fixed.

      Likewise I will be releasing this as a ToKod Plugin to make it easier.

      The project site is at:

      http://tukod.com/to-code-projects/tokod-sessions/

  • Parbir

    I have a unresolved problem. In my main page on the form action=”/myprofile” , the the form data does not get inserted into my custom db (not the wp db). The minute I change the action=”" the page loads to itself and the data is inserted. Method used is POST. So I did the data insert on the myprofile page (a wp page) as it gets loaded, the first time around. Incidentally the myprofile page has links to 5 other forms which when filled up and submitted are supposed to return control back to the myprofile page and insert the data back to the DB. When I come back to the myprofile page from the other pages I have lost all previous info.
    Can you be of some help here?

Leave a Reply

  

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>