Yes, you can but you will get errors about the header already being sent unless you hook into init or admin_init (or elsewhere prior to the headers being sent). I haven’t tested it, but you may be able to hook your session function into the send_headers
action1 which seems like the most appropriate place since session is ultimately sending headers.
On a template page, I think it will work if you start the session before calling get_header()
.
Here is an example from a plugin I previously built.
Setting up the session:
// Must run session_start() during admin_init to use $_SESSION variables later
add_action('admin_init','register_session');
function register_session() {
if( !session_id()
&& current_user_can( 'manage_options' )
&& current_user_can( 'client_tools' ) )
session_start();
session_unset();
}
This is part of a function that is used to set the session variables where I needed them.
// Update notifications
add_action( 'admin_post_mmc_update_notification', 'mmc_update_notification' );
function mmc_update_notification() {
//Check the nonce
check_admin_referer( 'mmc_notification_nonce' );
// Set a session variable
if ( isset( $_POST[ 'client-manager-lname' ] ) )
$_SESSION['client-manager-lname'] = $_POST['client-manager-lname'];
}
This allowed me to use these session variables on a sub menu page for this plugin like so:
//Define variables to be used in search results. Make sure each is set first.
if( isset($_SESSION['client-manager-lname'])
&& $_SESSION['client-manager-lname'] != '' ) {
$last_name = $_SESSION['client-manager-lname'];
}
You can unset session variables at the end of the script when it is no longer needed with unset ($_SESSION['varname']);
. All session variables can be unset with session_unset();
which is a good idea to run right after starting a session if you need to ensure that you are setting fresh variables for each session without leftovers from prior sessions.
Destroy the session with session_destroy();
.
I recommend reading PHP: session_unset – Manual.
Update: I looked a bit more closely at why you are considering using PHP sessions and saw Hybrid Web Dev’s answer. There is an option to remember credentials when your user is logged in (authenticated) via wp_signon()
2.
As stated, always use a wp_nonce_field()
3 in your forms and verify it with wp_verify_nonce()
4 in your form handling script.
I just happened upon a good article regarding Cookies and PHP Sessions in WordPress with an overview some cache and security related problems with relying on $_SESSION variables. Other Stuff Archives – WP Engine
All in all, it seems best to avoid PHP sessions in WordPress where possible. In some cases, it may be ideal to store temporary data via the Transient API5.