Solved

Session Variables in WordPress

Posted on 2015-02-12
23
257 Views
Last Modified: 2015-02-13
I can't get session variables to work in WordPress.

I added recommended code to functions.php ( in theme), as follows:

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

The attatched php program (not in a WordPress page, this is a standalone), sets $_SESSION variables as indicated (proc_sa2.php).

In a subsequent page, the values are all zero. Attached is a sample of the custom php for a subsequent page (page-service-plans-with-backflow-test.php).

What's wrong?
proc-sa2.php
page-service-plans-with-backflow-test.ph
0
Comment
Question by:Richard Korts
  • 14
  • 9
23 Comments
 
LVL 70

Expert Comment

by:Jason C. Levine
ID: 40606084
The attatched php program (not in a WordPress page, this is a standalone), sets $_SESSION variables as indicated (proc_sa2.php).

You have a second call to session_start() in page-service-plans and that will reset the session variables.  The code in functions.php is the only one you need:

 <div id="content_wrap" class="<?php echo $sidebar_class; ?>">
							<?php session_start(); ?>

Open in new window

0
 

Author Comment

by:Richard Korts
ID: 40606098
Jason,

So I don't use session_start() ANYWHERE else, just in functions.php. NOT in proc_sa2 either?

Or just not in the WordPress pages?

Thanks
0
 
LVL 70

Expert Comment

by:Jason C. Levine
ID: 40606108
So I don't use session_start() ANYWHERE else, just in functions.php.


For anything running under WordPress, yes.  Calling session_start() again starts a new session (who'd a thunk it?) but that means the existing session relationship with the user is lost.

NOT in proc_sa2 either?

That one is a little weird because of wp-load. Try it without it first.  I haven't had my coffee yet and I would have to look up the loading order from wp-load to see if it triggers the init hook or not.
0
 

Author Comment

by:Richard Korts
ID: 40606131
Tried it both ways; doesn't work either way. Amounts still zero.

I also found somewhere that this needs to go in wp-config:

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

Does it?

Thanks
0
 
LVL 70

Expert Comment

by:Jason C. Levine
ID: 40606157
Does it?

Depends on if your server is using register_globals or not.  This is the tutorial I used when learning about this:

http://silvermapleweb.com/using-the-php-session-in-wordpress/

As far as things being zero, make sure the first script sends some output to the browser so you know the query is working and assigning properly as a debugging step.  Then let it redirect.
0
 

Author Comment

by:Richard Korts
ID: 40606312
Jason,

I put echos into proc_sa2 (see attached, echos commented out). It showed all the proper values in the database. I had done that before. Note that I echoed the session variables, so I assume that means they were set.

I put

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

into wp-config. Still fails.

Based on the link (that is also where I found out about putting that code into wp-config), it said don't put it anywhere later. So I took it out of functions.php.

Still fails.

I could get around this if I could just pass ONE value around, because I could make another db table & key it with date-time (to the second), that would uniquely identify the customer & I could pick up that value later.

Can I define a global variable (somewhere) & put that kind of thing in there?

I'm not hung up on session variables if there is another way.

Thanks.
proc-sa2.php
0
 

Author Comment

by:Richard Korts
ID: 40606346
Jason,

One more thing. register_globals is Off in php.ini
0
 

Author Comment

by:Richard Korts
ID: 40606469
Jason,

What do you think of this?

https://eamann.com/tech/introducing-wp_session/
0
 
LVL 70

Expert Comment

by:Jason C. Levine
ID: 40606489
Here's a review of it:

https://pippinsplugins.com/storing-session-data-in-wordpress-without-_session/

You can try it.  I've had a real-life issue come up and have to cut short EE activity for a few days so I'm going to have to unsub.
0
 

Author Comment

by:Richard Korts
ID: 40606596
Jason,

Sorry about your personal situation.

I posted another question hoping someone else can help.

FYI, the plugin does EXACTLY the same thing, returns zero.

My gut feel is the combination of the non WordPress php program & WordPress php somehow doesn't fit together.

Thanks,

Richard
0
 
LVL 70

Expert Comment

by:Jason C. Levine
ID: 40607253
Okay, so it looks like I'm sitting in a waiting room for a large chunk of tonight and can pick this up again. Caveat is I may disappear later tonight or tomorrow for a while so we might have to stretch this out.

One more thing. register_globals is Off in php.ini

That's okay.

What I would like to do is simplify this a little bit to make sure things are working in WordPress before you pass the sessions from the external script to it.  So let's change this up a bit.

1) Make sure this is in functions.php

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

Open in new window


2) Remove all other attempts to mess with sessions (wp-config, plugins, everything).  Clear caches.

3) Make page-service-plans-with-backflow-test.php use this code:

<?php get_header(); 

    // assign to session superglobal
    $_SESSION['platinum_plan'] = 300;
    $_SESSION['gold_plan'] = 200;


?>


      <!--Page-->
		<div id="main">
			<?php while ( have_posts() ) : the_post();?>
            <?php $post_option_select_title_bar = get_post_meta(get_the_ID(), 'post_option_select_title_bar', true);  ?>
            <?php if($post_option_select_title_bar != 'no'): ?>
            <div id="main_title_wrap" data-module="true">
                <div class="container main_title_wrap_inn">
                    <p class="breadcrumbs pull-right visible-desktop">
                    <?php if (function_exists('show_full_breadcrumb')) show_full_breadcrumb(); ?>

                    </p>
                    <div id="main_title">
                        <h1 class="main_title"><?php the_title(); ?></h1>
                    </div>
                </div>
            </div><!--End #main_title_wrap-->
			<div class="title_wrap_line"></div><!--End .title_wrap_line-->
            <?php endif; ?>
			
            <?php
			$post_option_select_specing = get_post_meta(get_the_ID(), 'post_option_select_specing', true);
			$specing_style = "";
			if($post_option_select_specing){
				if($post_option_select_specing != 'no'){
					$specing_style = "";
				}else{
					$specing_style = "margin-top:0px;";
				}
				
			}
			
			?>
			<div id="content" class="container" style=" <?php echo $specing_style; ?>">
                <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                
                <?php 
                $post_option_select_sidebar  = get_post_meta(get_the_ID(), "post_option_select_sidebar", true);
        
                if($post_option_select_sidebar == 'post_sidebar_left'){
                    $sidebar_class = 'span8 pull-right';
                }elseif($post_option_select_sidebar == 'post_sidebar_no'){
                    $sidebar_class = 'span12';
                }else{
                    $sidebar_class = 'span8';
                }?>
                
                    <div class="row">
                        <div id="content_wrap" class="<?php echo $sidebar_class; ?>">
							<form method="POST" action="http://www.rain1.com/new-site/proc_sa4.php" name="st">
                            We offer two service plans that provide you with hassle-free maintenance of your system all season long:
							<br><br>
							<ul>
								<li><b>Platinum plan:</b>  includes system start-up, backflow test, mid-summer check-up and winterization. $<? print number_format($_SESSION['platinum_plan'],2); ?>&nbsp;Choose Plan&nbsp;<input type="radio" name="bftplan" value="p"><br><br></li>
								<li><b>Gold plan:</b>  includes system start-up, backflow test and winterization. $<? print number_format($_SESSION['gold_plan'],2); ?>&nbsp;Choose Plan&nbsp;<input type="radio" name="bftplan" value="g"><br><br></li>  
							</ul>			
							<b>Backflow testing / certification.</b>   Annually required backflow inspection to ensure the device is up to code, submit form and results to the  proper government agency<br><br>
							<b>Spring start-up and system tune-up.</b>  Includes activating the system and making necessary adjustments to get it ready for the watering season. Activation of water supply, check backflow unit for  proper seal, check all sprinkler heads for proper  adjustment and operation, inspect mainline and lateral lines for leaks, program controller<br><br>
							<b>Mid-summer service check-up.</b>   Assures the system is working properly, adjusts for under-watering and over-watering conditions depending on weather conditions.  Keeps plants healthy during the hottest part of the season. All sprinkler heads checked mid-season for proper adjustment and operation, inspect mainline and lateral lines for leaks, reprogram controller for seasonal watering times.<br><br>
							<b>Fall winterization.</b>   We flush the water from the system to prepare it for winter.  Avoids broken pipes and freeze damage. Shut off main water supply to sprinkler system, purge all water from system with compressed air, shut down controller.

								<br><br><br>
									<input type="submit" value="Continue">
							</form>

                            
                        </div>
                        
                        <?php if($post_option_select_sidebar != 'post_sidebar_no'): ?>
                        <aside id="sidebar" class="span4" data-module="true">
                            <ul class="sidebar_widget">
                                <?php $post_option_select_sidebars = get_post_meta(get_the_ID(), "post_option_select_sidebars", true); 
                                if($post_option_select_sidebars != 'none'){
                                    if( !function_exists('dynamic_sidebar') || !dynamic_sidebar($post_option_select_sidebars) ) : endif;
                                }else{
                                    dynamic_sidebar('sidebar_default');
                                    
                                }?>	
                            </ul>
                        </aside>
                        <?php endif; ?>
                        
                    </div>
                </div>
			</div><!--End #content-->
            <?php endwhile; ?>
		</div><!--End #main-->
        
        
<?php get_footer(); ?>

Open in new window


4) Test by going right to that page.  We should see the session values as set at the top echo in the body.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:Richard Korts
ID: 40608206
Jason,

It worked; page shows the values $200 & $300.

See attached.

See also attached current code in proc_sa2 (sets session variables). Maybe I should try it with session_start() removed. Since wp-load is at the top?
proc-sa2.php
working--sessions.jpg
0
 

Author Comment

by:Richard Korts
ID: 40608224
Jason,

I just realized that I DID NOT put this code into functions.php before I ran the prior test.

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

I just put it in.

Richard
0
 

Author Comment

by:Richard Korts
ID: 40608265
Jason,

I changed proc_sa2.php so it DOES NOT include session_start() & I commented out the hard code $_SESSION['etc'] = values in service-plans-with-backflow-test.

Now does not work (values are zero).
0
 
LVL 70

Expert Comment

by:Jason C. Levine
ID: 40608299
session_start is needed in the proc_sa2.php file because  wp-load does not trigger the init action, so no session is called.

So what I expect to happen here is the values fail to pass because we're still calling two session_start() functions...one in proc_sa2.php and one when WordPress actually loads.  The second resets the first.  What we need to do instead is make one overarching session call that handles internal to WordPress and external to WordPress

Let's try this:

1) Remove the code from functions.php and remove any references to session_start() in proc_sa2.php.

2) Add this to the top of wp-config.php:

if (!session_id())
    session_start();

Open in new window


and re-test with echos on each page.  It still may not work properly because of some WordPress internals but really we want to see it work on proc_sa2.php at this point and the worry about the internals.
0
 

Author Comment

by:Richard Korts
ID: 40608394
Jason,

OK, I did that.

The echo's in proc_sa2.php show the correct values. See attached.

But the other page, service-plans-with-backflow-test, still shows them as $300 & $200, I presume because the session has not ended, I took the code that set them in there OUT.

BTW, can we cause the session to end somewhere (for testing)? It's confusing to have those values still show up.

Thanks

PS - Are you in LA?
echoed-values.jpg
proc-sa2.php
0
 
LVL 70

Expert Comment

by:Jason C. Levine
ID: 40608536
still shows them as $300 & $200, I presume because the session has not ended,

No, because the code was still setting them each time.  Taking it out and closing the browser completely (all windows/tabs) should regenerate the session after the browser is reopened.

BTW, can we cause the session to end somewhere (for testing)?

Yes, that's the next step.  We'll need to add session_destroy() or session_unset() at the appropriate place.  For now, we concentrate on getting the values to pass.
0
 

Author Comment

by:Richard Korts
ID: 40608620
I rebooted my computer about a half hour ago. The code setting those session variables INSIDE of page-service-plans-with-backflow-test.php hase been commented out.

Should I just try it again?

Or what next?
0
 
LVL 70

Expert Comment

by:Jason C. Levine
ID: 40608625
Should I just try it again?

Yes.

Also, turn off any caching plugins on the WordPress side, or exclude the test page from caching.  Those will make testing much harder as you won't know if the page is generating dynamic values or pulling from the cache.
0
 

Author Comment

by:Richard Korts
ID: 40608634
How do I exclude the test page from caching? What is "the" test page, there are a lot.

I'll see if there are any caching plugins & turn them off
0
 

Author Comment

by:Richard Korts
ID: 40608727
Jason,

When I though you would be unavailable for a number of days, I found another non-EE resource that claimed he could solve this.

He is suggesting, in essence, that I have no "out of Word Press" pages; when a form is submitted, I submit it directly to another WordPress page & put the logic in php that was in proc_sa2.php, for example,  at the top of that file; look up values in the database, etc..

He also suggests that I pass the results (the data I was trying to put into $_SESSION variables) into hidden fields, pass them that way to the next page, etc,, retrieve them as $_POST['etc'], etc.

Does that make sense to you?
0
 
LVL 70

Accepted Solution

by:
Jason C. Levine earned 500 total points
ID: 40608857
He is suggesting, in essence, that I have no "out of Word Press" pages; when a form is submitted, I submit it directly to another WordPress page & put the logic in php that was in proc_sa2.php, for example,  at the top of that file; look up values in the database, etc..

Well, yeah.  But you seemed insistent on generating the non-WP page so I've been answering that way.

If you do this entirely within WordPress, you can use $_SESSION with the init hook in functions.php only or process hidden fields into variables.
0
 

Author Closing Comment

by:Richard Korts
ID: 40608868
Thanks for all your help with this & other things.

I hope your personal situation will resolve positively.

Stay tuned, I find WordPress to me a "Monster", something tells me that going this route may have it's pitfalls too.

Richard
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Question about WP RSS Aggregator 1 42
Customizing themes 14 67
Wordpress theme to easily (hopefully!) make this type of site 1 34
Form Submit falis 6 25
If you are looking for plug-ins to add functions to your WordPress small business web site, take some time to read though this comprehensive list.  These are all the plugins I use for my customers WordPress web sites, as well as my own.  Be sure to …
WordPress can be pretty daunting, especially for a beginner, so I thought it might be a good idea to write an article to show how easy it is to get started in WordPress and to design a custom theme.  The first step is to check with your hosting comp…
The purpose of this video is to demonstrate how to add AdSense Ads to a WordPress Website, and how to set up WordPress to automatically place Ads in Sidebars. This will be demonstrated using a Windows 8 PC. Log into your AdSense account. : Cli…
The purpose of this video is to demonstrate how to integrate Mailchimp with WordPress, by placing a Mailchimp signup form on a WordPress Page or Post. This will be demonstrated using a Windows 8 PC. Mailchimp will be used. Log into your Mailchi…

919 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

12 Experts available now in Live!

Get 1:1 Help Now