Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress session variable not working

I have an issue with a WordPress session. I have a file 'test.php' that is used post a variable to a WordPress site. It has the condition: "if the session variable is set then the user can access the whole WordPress site, and if the session variable is not set then user can't access the site".

When I post the variable to the WordPress site using test.php the homepage works fine, but when I access inner pages like 'xyz.com/contact' I get an error Not Access which means that the session variable was cleared on the next page.

Here is the test.php file:

<form action="wordpress-site-link" method="POST">
    <input type="submit" name="var" value="go"/>
</form>

In the file themes/theme-name/header.php I wrote this code:

session_start();

if(isset($_SESSION['var'])) {
      echo 'Welcome'; 
}  else if(isset($_POST['var'])) {
       $_SESSION['var'] = $_POST['var']; 
} else {
       echo 'No access...';
       exit; 
}
like image 276
Boyrock75 Avatar asked Oct 06 '15 19:10

Boyrock75


People also ask

What are WordPress session cookies and how do they work?

According to the WordPress Codex, a couple of different session cookies are set: On login, WordPress uses the wordpress_[hash] cookie to store authentication details (limited to the /wp-admin/ area). After login, WordPress sets the wordpress_logged_in_[hash] cookie. This indicates when you’re logged in and who you are.

Can I use PHP sessions in kinsta?

We don’t recommend using PHP sessions and they will usually not work in our Kinsta environment. PHP sessions also have other security implications that should be considered. If you see code using session_start on your site, this means its using PHP sessions.

What is the difference between session cookies and persistent cookies?

Session cookies are stored temporarily in memory and are automatically removed when the browser closes or the session ends. Suggested reading: How to Improve PHP Memory Limit in WordPress. Persistent cookies, as you might have guessed, are those that contain an expiration date.

What is the problem with using PHPSESSID in WordPress?

Imagine that was required in order for the WordPress login system to work. In that scenario, every single page view would have to bypass cache so that the wordpress_logged_in cookie was set correctly both for logged in and logged out users. That’s the problem with using PHPSESSID.


Video Answer


1 Answers

Just hook a function on "init" in your functions.php like this :

function ur_theme_start_session()
{
    if (!session_id())
        session_start();
}
add_action("init", "ur_theme_start_session", 1);

Then u can use your session variables.

I hope that help u.

like image 89
Nozifel Avatar answered Sep 19 '22 04:09

Nozifel