| | |

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!)

Similar Posts

21 Comments

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

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

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

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

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

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

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

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

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

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

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

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

  9. Thanks a lot.
    After searching lot on google, i found your article. It is perfect. Thanks for explaining all the aspects in detail. I want to add one more thing. If your session is still not working then please check the session save path. I am using the ipower hosting where session save path was not declared. So i contact the server adminstrator.

    Thank once again.

  10. Man, this is driving me crazy.

    I developed some kind of shopping cart for my store in WordPress. It’s very simple and works wonderfully in all browsers, except for Firefox. I made a lot of research and found out that this sessions problem with WordPress was not only with me. Then I tried all the solutions that Google gave me, including the very same code in this post. No success.

    The sessions problem with WordPress comes from a function named wp_unregister_GLOBALS, it’s set in wp-includes/load.php, called in wp-settings.php and is there to prevent problems with the register_globals directive. This functions unset all sessions, making my cart be always empty when a page is loaded. I can be sure that register_globals is set to off in my server, so i just commented the content of this function out. Still no success.

    The most bizarre part of my drama is that, in my own pc, the shopping cart works like if I never had a problem with it. Every other computer fails in completing any order in Firefox, because the cart is always empty when it’s sent to the payment method.

    Here’s what i have done:

    wp-includes/load.php

    /**
    * Turn register globals off.
    *
    * @access private
    * @since 2.1.0
    * @return null Will return null if register_globals PHP directive was disabled
    */
    function wp_unregister_GLOBALS() { /*
    if ( !ini_get( 'register_globals' ) )
    return;

    if ( isset( $_REQUEST['GLOBALS'] ) )
    die( 'GLOBALS overwrite attempt detected' );

    // Variables that shouldn't be unset
    $no_unset = array( 'GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES', 'table_prefix' );

    $input = array_merge( $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset( $_SESSION ) && is_array( $_SESSION ) ? $_SESSION : array() );
    foreach ( $input as $k => $v )
    if ( !in_array( $k, $no_unset ) && isset( $GLOBALS[$k] ) ) {
    $GLOBALS[$k] = null;
    unset( $GLOBALS[$k] );
    }
    */ }

    my theme’s functions.php:

    function init_session() {
    if (!session_id())
    session_start();
    }
    add_action('init', 'init_session', 1);

    I hate the idea of messing with the WordPress code and tried to solve all problems in a clean way, but this is making me go berserk.

    Any idea?

    1. @Henrique – I think what you really want to do is to write a small plugin to handle most of this. This becomes more important if you want to use multisite, and you have some sites you want this, and others you do not.

      There are many good tutorials on writing simple plugins, but this is beyond the scope of this page on sessions.

      About working on your local browser. Usually when you have something that works on your local browser but not on others, it is because you are calling a file on your local hard drive. For testing, try re-naming your local directory. For example:

      Say your files are in a directory called:

      /home/me/website/supershoppinglist

      Try renaming this to:

      /home/me/website/supershoppinglistTEST

      or this:

      /home/me/site/supershoppinglist

      If it fails, you have a call to a local file! Check your code!

      Note: If you are still using an inferior (IMO) drive based OS like Windows (instead of a Superior Professional OpenSource OS like Ubuntu), your directory system may look more like:

      c:\me\website\supershoppinglist

      If you have any code in your website that points to “c:\” or “d:\” – that would be incorrect.

  11. appreciate this as I’m looking for a way to change the header picture and the videos that I use every time somebody goes to a different page rather than doing it on a daily basis like I now do.

    Haven’t got it working yet, but this is a step in the right direction.

    By the way, I used to toggle the switches on a Sperry Univac UYK-20 (Navmacs) system to get it to do a data dump.

    Long time ago when I was in the navy from 76 – 82

    1. I change header pictures with a modified TuKod theme.

      Nice to know someone else is reading from back in the 70’s

  12. Hello,

    thank You very much for this article. I’m starting session from another plugin (BreezingForms), so I don’t have any problem with this. But I need to redirect to other site in the same domain, which isn’t based on WordPress. I’ve noticed that session_id() (it’s only data that I need) is empty after redirect to this page. Between sites based on WP it works perfectly.
    Any idea why it happens?

    Best wishes
    Eve

Leave a Reply

Your email address will not be published. Required fields are marked *