Use session variable as object in PHP - php

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.

Related

how to get session values in layout in Zend framework 1?

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 inside every function?

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();

PHP - Accessing my user class from the whole app

I am currently writing a login script because I am trying to learn PDO using OOP. I have a index.php page which only contain a login form. Then I have a User class, it looks like this:
<?php
include_once('database.php');
session_start();
class User{
public $id;
public $username;
public $password;
public $firstname;
public $lastname;
public function Login($username, $password) {
$db = new Database;
$db = $db->dbConnect();
$query = "SELECT * FROM users WHERE username = ? AND password = ?";
$statement = $db->prepare($query);
$statement->bindParam(1, $username);
$statement->bindParam(2, $password);
$statement->execute();
$rows = $statement->rowCount();
$data = $statement->fetchAll();
if( $rows == 1 ) {
$this->id = $data[0]['id'];
$this->username = $data[0]['username'];
$this->password = $data[0]['password'];
$this->firstname = $data[0]['firstname'];
$this->lastname = $data[0]['lastname'];
$_SESSION['SESSID'] = uniqid('', true);
header("location: dashboard.php");
}
}
}
?>
When the user is signed-in he/she goes to dashboard.php. I want to access the current User class from there, so I can use echo $user->username from there. But in dashboard.php, I have to declare the User class as new, so it doesn't keep all the variables.
Do you have any ideas on how i can access the User class variables in Dashboard.php which was declared in the Login-function?
Sorry for the bad explanation, but I hope you understand. Thank you in advance!
First off put your user class definition in another file and load it in like you do your database.php. In there you want only your class definition none of the session start business... <?php class User {....} ?> (the closing ?> is optionial).
so what you have now on your pages that need access to the user object is
<?php
include_once('database.php');
include_once('user.php');
session_start();
Then after a user has successfully logged you tuck the user in the session.
$_SESSION["user"] = $user;
Then when you want to get at it just say
$user = $_SESSION["user"];
echo $user->username;
What you could do is, put your user object into the session:
$obj = new Object();
$_SESSION['obj'] = serialize($obj);
$obj = unserialize($_SESSION['obj']);
or you could create a singleton, check out this link:
Creating the Singleton design pattern in PHP5
You have 2 options:
a) You store all the login info in a session.
b) You only store the user ID and some sort of identifier that the user has / is logged in, and create another method that will load the information from the database each time you load the page (bad idea really)
For example, you could add the following methods to your class in order to implement the above mentioned functionality and some more:
function createUserSession(array $userData) {
// Create / save session data
}
function readActiveUserSession() {
// Read current user information
}
function destroyActiveUserSession() {
// Call to destroy user session and sign out
}
Of course, you will have to add the appropriate code to the methods.

Setting Sessions inside PHP Class

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

How to use Zend\Session in zf2?

Does anybody try zf2? I can not understand new mechanism of using sessions in zf2. How can I write and read to/from the session in new zend framework?
Also I can not find any examples in the internet.
Some examples of zf2 sessions usage:
Session creation:
use Zend\Session\Container;
$session = new Container('base');
Check that key exists in session:
$session->offsetExists('email')
Getting value from the session by key:
$email = $session->offsetGet('email');
Setting value in session:
$session->offsetSet('email', $email);
Unsetting value in session:
$session->offsetUnset('email');
And other easy way to use session are:
$session = new Container('foo');
// these are all equivalent means to the same end
$session['bar'] = 'foobar';
$session->bar = 'foobar';
$session->offsetSet('bar', 'foobar');
Definitely yes, you should use Zend\Session\Container
Container extends of ArrayObject and instantiates with ARRAY_AS_PROPS flag that means you can easily iterate through properties and read/write them, e.g.
use Zend\Session\Container as SessionContainer;
$this->session = new SessionContainer('post_supply');
$this->session->ex = true;
var_dump($this->session->ex);
First argument is session namespace and second — Manager. Manager is a facade for Storage and SaveHandler and it's configured with ConfigInterface in order to save your session data in DB or Memcache server.
I'm currently working with zf2. I found usage of Sessions in:
Zend\Authentication\Storage\Session.php
Maybe you can find your answer there.
If you are trying to use session in your login action, you can use: "Zend\Authentication\AuthenticationService". It Authenticates the user and store session as well.
getStorage()->write($contents) will store the session.
well here is the brief example. i have implemented regarding maintaining session on successful authentication of user.
<?php
$registry = Zend_Registry::getInstance();
$DB = $registry['DB'];
$authAdapter = new Zend_Auth_Adapter_DbTable($DB);
$authAdapter->setTableName('user');
$authAdapter->setIdentityColumn("user_name");
$authAdapter->setCredentialColumn("user_password");
//get values
$username = $request->getParam('username');
$password = $request->getParam('password');
//set values
$authAdapter->setIdentity($username);
$authAdapter->setCredential($password);
$auth = Zend_Auth::getInstance();
//to store in session
$auth->setStorage(new Zend_Auth_Storage_Session('front'));
$authResult = $auth->authenticate($authAdapter);
if ($authResult->isValid()) {
$authAdap = $authAdapter->getResultRowObject(null, "Password");
$auth->getStorage()->write($authAdap);
$this->_redirect('/login/controlpannel');
} else {
$this->_redirect('/login/login');
}
?>
getting values or check data stored in session related to user
<?php
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('front'));
if($auth->hasIdentity()){
$data = $auth->getStorage()->read();
print_r($data);
}else{
$this->_redirect('/login/login');
}
?>
hope this could help someone
use Zend\Session\Container;
public function createAction(){
$session = new Container('name');
$session->offsetSet('session_variable', $value);
}
//the above codes are used for create session.
public function take_valuesAction(){
$session = new Container('name');
echo $value = $session->offsetGet('session_variable');
}
//the above codes are used for take values from session.
public function destroyAction(){
$session = new Container('name');
$session->getManager()->destroy();
}
//the above codes are used for destroy the session.
To start a session you need to use
zend\session\container

Categories