I'm creating a user class to handle my logins. As I wish to set the sessions inside the class after the username and password are validated, do I have to use session_start() at the top of the class, inside the public function where the sessions are to be set, or where the instance is created? Perhaps it could go inside function _construct()?
This is how I would like to call the class:
<php
include('user_class.php');
$user = new user;
$user->login($username,$password);
?>
You can just add session_start(); at the top of the file you're including the class in.
So
<?php
session_start();
include('user_class.php');
$user = new user;
$user->login($username,$password);
?>
would work.
Next to your user-class create yourself a session-class as well.
The user-class then is just storing itself into the session class and does not need to take care about calling session_start or not, that's the job of the session-class.
<php
include('session_class.php');
include('user_class.php');
$session = new session;
if ($session->hasRegisteredUser()) {
$user = $session->getRegisteredUser();
} else {
$user = new user;
$user->login($username, $password);
$session->setRegisteredUser($user);
}
Does this answer your question or do you need now to know how to do it with the session class?
Yes you can use sessions inside your classes because sessions are global variables in php.
Code Example(adding a new session variable):
<?php
class sessionControle{
...
...
public function addSession($index, $value){
$_SESSION[$index] = $value;
return $_SESSION[$index];
}
}
?>
in your main php file you can include the function $_SESSIONS are global
Code in your main file:
<?php
session_start();
include_once("myClass.php");
$Se = new sessionControle;
echo $Se->addSession('User', 'Crx');
//Double check here !!
echo $_SESSION['User'];
?>
Output: Crx
Related
Need some assistance. I am getting the following errors
Fatal error: Call to a member function getName() on string in......
This refers to the line on by index.php
$session->getName()
The code.
index.php
include 'classes/user.php';
$session = isset($_SESSION['userObj']) ? $_SESSION['userObj'] : "";
include 'login.php';
$session->getName()
login.php
session_start();
$user = new User();
$user->setAll($db_id,$db_fullname,$db_username,$db_rights, $db_last_login,$db);
$_SESSION['userObj'] = $user;
How do you pass objects correctly via session vars? I've checked on this site and its advised to do it like i have.
I know i'm not doing the else statement right on the isset part. Should i be doing.
else{ $session = new User();}
Use serialize()
//Set object as session
$user = new User();
$_SESSION['userObj'] = serialize($user);
//Get object
$user = unserialize($_SESSION['userObj']);
FYI, don't forget to write session_start(); on first line of every page to use $_SESSION.
i have a problem calling a session variable from another script. can anybody help me on this matter.
Below is the script that i create the session and store the time in a session variable.
<?php
session_start();
$orgtimestamp = date("Y-m-d h:i:sa");
$_SESSION['orgtimestamp'] = $orgtimestamp;
?>
Here is the script that i try to access this session variable from a function of it. till now nothing worked
<?php
include '../../mydomain/myscript.php';
class survey_Tracksciprt
{
public static function timeofclick(){
session_start();
$time_org = $_SESSION['orgtimestamp'];
echo $time_org;
}
}
this hasnt worked upto now, nothing prints...can anybody give tips to sought this out and its compulsory to have this function timeofclick
You're not creating your class on your second file add:
//I don't know what this does but if it already starts a session remove the session start inside the class.
include '../../mydomain/myscript.php';
$survey = new survey_Tracksciprt();
$survey::timeofclick();
class survey_Tracksciprt
{
public static function timeofclick(){
session_start();
$time_org = $_SESSION['orgtimestamp'];
echo $time_org;
}
}
I also advice putting session_start at the top of your file.
<?php
session_start();
include '../../mydomain/myscript.php';
class survey_Tracksciprt
{
public static function timeofclick(){
$time_org = $_SESSION['orgtimestamp'];
echo $time_org;
}
}
Always use the session_start(); at the top line of the page.
First, you need an init-session.php file, containing:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Second, you need to include this file at the start of your loader/layout (whatever you have there), so no operation will be executed before you initialize your session.
Third, you should initialize $orgtimestamp like this:
<?php
$orgtimestamp = date("Y-m-d h:i:sa");
$_SESSION['orgtimestamp'] = $orgtimestamp;
?>
Fourth, you need to call survey_Tracksciprt::timeofclick().
I defined a session class,which uses values from the $_POST variable in an array called $sessionVars. When a user logs-in a new instance of the session class is created, a construct function sets session variables.I checked that this is working correctly.Problem: When i try to access those variables from a different page the session shows that its not started and those variables are undefined. Confused cause I thought $_SESSION being a super global means its accessible all the time(i.e scope doesn't matter) . I suspect im doing something wrong when I try to access the $_SESSION variables since they are in a class. I appreciate any help..thanks in advance.
class userSession{
public function __construct($sessionVars){
session_start();
$_SESSION['userEmail']=$sessionVars['user'];
$_SESSION['userID']=$sessionVars['userID'];
$_SESSION['userFolder']='users/user_'.$_SESSION['userID'];
}
/*just for housekeeping. not used in application*/
function showvars(){
echo $_SESSION['userEmail'].'<br><br>';
echo $_SESSION['userID'].'<br><br>';
echo $_SESSION['userFolder'];
$sessionID=session_id();
echo '<br><br>'.$sessionID;
}
}//**END USER SESSION
/*This is the login script that calls the session*/
include 'library.php';
$show=new render;
$show->index();
if(!isset($_POST['login']) ){
$show->usrLogin();
} else{
if(!empty($_POST['email'])){
$postVars=array('user'=>$_POST['email'],'pass'=>$_POST['password']);
$user=new user();
$data=$user->loginUser($postVars);
$currSession=new userSession($data);
}else{
die('No data in POST variable');}
}
/*file upload that needs the session[userFolder] variable*/
function file_upload(){
$userFolder=&$_SESSION['userFolder'];
echo '<hr>userFolder is : '.$userFolder;
function do_upload(){
if(!empty( $_FILES) ){
echo $userFolder.'<hr>';
$tmpFldr=$_FILES['upFile']['tmp_name'];
$fileDest=$userFolder.'/'.$_FILES['upFile']['name'];
if(move_uploaded_file($tmpFldr,$fileDest)){
echo 'file(s) uploaded successfully';
}
else{
echo 'Your file failed to upload<br><br>';
}
return $fileDest; //returns path to uploaded file
} else{die( 'Nothing to upload');}
}//END FUNCTION DO_UPLOAD,
/*Perform upload return file location*/
$fileLoc=do_upload();
return $fileLoc;
}
You need to instantiate an object of this class on every page that uses the session (or start the session manually). Also, you'll not want that constructor, instead some other way of setting vars. This is just for illustration of how it works with your current code, there are much better approaches:
class userSession {
public function __construct(){
session_start();
}
function set_login_vars($sessionVars){
$_SESSION['userEmail']=$sessionVars['user'];
$_SESSION['userID']=$sessionVars['userID'];
$_SESSION['userFolder']='users/user_'.$_SESSION['userID'];
}
}
//page1.php
$session = new userSession;
$session->set_login_vars($loginVars);
//page2.php
//you need to start the session, either with the class
$session = new userSession;
//or session_start();
print_r($_SESSION);
I want to access session values from layout.xml.
The code I did is
Layout.xml
<h2><?php $myprofile=new Zend_Session('user_session');
print $myprofile->username; ?> </h2>
Index Controller/index action
$userid = $this->_user->getUserId($username,$password);
$session = new Zend_Session_Namespace('user_session');
$session->username = $username;
$session->password = $password;
$session->uid = $userid;
$this->_redirect('home');
Home Controller/index action
$this->session = new Zend_Session_Namespace('user_session');
$this->view->uname = $this->session->username;
Home/index.phtml
<?php echo "The User Name is ".$this->uname?>
But it shows an error
Fatal error: Call to protected Zend_Session::__construct() from context 'Zend_View' in/var/www/shoppingcart/application/layouts/scripts/layout.phtml on line 19
I am able to get the session values in Home/index.html.
Expecting positive help.
Why using Zend_Session in the layout and Zend_Session_Namespace in the view ?
also maybe you should'n use sessions in the view/layout but pass it as param from the controller or the bootstrap file
I agree with Amine here, putting the Zend_Session in the view script is generally considered bad practice. I would indeed put it in the bootstrap as well, something like the following...
// Bootstrap.php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function _initUserSession()
{
// If not already done, bootstrap the view
$this->bootstrap('view');
$view = $this->getResource('view');
// Initialise the session
$session = new Zend_Session_Namespace('user_session');
// See if the username has been set, and if not at
// least make the variable
if (isset($session->username)
$view->username = $session->username;
else
$view->username = null;
}
}
Then in the layout you can do this:
<?php if ($this->username !== null) : ?>
The User Name is <?php echo $this->username ?>
<?php else : ?>
No username has been set.
<?php endif; ?>
does session_start() have to be called within every function of a class? like:
class User {
var $username;
function set_session_username($username) {
session_start(); # do I really need to call this again?
$_SESSION['username'] = $username;
}
function retrieve_session_username() {
session_start(); # do I really need to call this again?
$this -> username = $_SESSION['username'];
}
}
session_start();
$user = new User();
$user -> set_session_username('savagewood');
$user -> retrieve_session_username();
echo $user -> username;
No, it only needs to be called once per request. So the first script the runs post it at top of that file
No , you need to start the session only once in the page which is loaded. Not in any class or functions.
No, session_start() should be called once in your app entry point, before your app sends any output.
You could check if session is started:
if (!session_id())
session_start();