PHP - Accessing my user class from the whole app - php

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.

Related

Automatically log out php application after 2 mins

I have finished designing an application but would like to make the application logout out after 5 minutes of inactivity.
The first page is:
<?php
session_start();
require_once("class.user.php");
$login = new USER();
if($login->is_loggedin()!="")
{
$login->redirect('user.php');
}
?>
This is the user page:
<?php
require_once("session.php");
require_once("class.user.php");
$auth_user = new USER();
$user_pin = $_SESSION['user_session']; ?>
The session.php page
<?php
session_start();
require_once 'class.user.php';
$session = new USER();
if(!$session->is_loggedin())
{
$session->redirect('index.php');
}
?>
This are the classes:
require_once('dbconfig.php');
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function is_loggedin()
{
if(isset($_SESSION['user_session']) )
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function doLogout()
{
session_destroy();
unset($_SESSION['user_session']);
return true;
}
}
?>
Theres multiple ways to achieve this:
You can make a verification with a cookie or a session with a Timestamp to verify if the user has not changed paged within 2 minutes and it will log him out the moment he access that page. The Con in this method is that for all intents and purposes the user is still considered "Online" until he changes page.
My preferred method is to make a pooling with JQuery and Ajax request.
Basically every X seconds you send a request with AJAX to the user to see if hes still there and update his timestamp on the database. And then with a server side script if the timestamp has reach 2 minutes difference set the user offline and force log him out.
There is always websockets, at the moment im exploring this method with rachetphp but it allows you to track a connection in real time, which is also pretty sweet.
Check this link for methods.

Normal php login to YII login

i have a normal php login which connects to a database authenticates the user, now i need to convert this to a login that uses yii framework, can anybody tell me in order to do so.. what are the first things that i should do and can i convert this to yii login. following is the current login function that i have to call
function login($usr,$pwd) {
$query = "SELECT * FROM login WHERE us.username='$usr' AND us.password='$pwd'; ";
$dataReader=$command->query();
$row = mysql_fetch_array($dataReader);
$log = new stdClass();
if($row) {
$pro->accountID = (int)$row['accountID'];
$pro->accountname = $row['accountname'];
$pro->usertype = (int)$row['usertype'];
$string = rand() . 'SURVAYLAND' . rand() . $usr. $pwd;
$_SESSION['SURVEY_AUTHENTICATE_KEY'] = md5($string);
} else {
$pro = false;
}
}
Whenever you call Yii::app()->user, you get an instance of CWebUser. This is the way Yii represents the user that it currently viewing your application.
This user can be logged in or access the app without login (in other words, be a guest).
Class CWebUser has a method called login, which, as you expected, logs in a user.
Method login() takes as argument an object that implements IUserIdentity interface.
The easiest way to make your own is to create a simple class (call it MyIdentity for exemple):
//this class' constructor takes a username and a password
class MyIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
// check username and password in DB
// return true or false to signal whether user should be logged in
}
public function getId()
{
return $this->_id;
}
}
Then use what you just created to actually log in an user:
// Login a user with the provided username and password.
$identity=new MyIdentity($username,$password);
if($identity->authenticate())
Yii::app()->user->login($identity);
else
echo $identity->errorMessage;

cannot access object user from another php page

I'm trying to learn MVC pattern but,even if I'm trying hard, it seems I still got big issues.
I have got a controller,named baseController that do the following:
class baseController {
public $model;
public $user;
...
$activeuser = $this->model->getlogin();
if ($activeuser != 'invalid user' && $activeuser != "") {
$this->user=$activeuser;
header("Location:home.php");
}
I have got a model.php file which contains the getlogin() function:
public function getlogin() {
if (isset($_REQUEST['username']) && isset($_REQUEST['password'])) {
$username = mysql_real_escape_string($_REQUEST['username']);
$pwd = mysql_real_escape_string($_REQUEST['password']);
$pwd = md5($pwd);
$query = mysql_query("SELECT * FROM users WHERE username='$username' AND password ='$pwd' AND attivato =1;");
if (mysql_num_rows($query) == 1) {
require_once 'User.php';
$sql=mysql_fetch_array($query);
$activeuser = new User();
$activeuser->username=$sql['username'];
$activeuser->email=$sql['email'];
return $activeuser;
} else {
return 'invalid user'; //TO-DO
}
}
}
The home.php create a new homeController and calls its invoke() function.The homeController file include the view page,that's called afterlogin.php.
In the afterlogin.php I've got the "ERROR":
if (isset($activeuser)){
echo "<p>Utente ".$activeuser->username."</p>";
echo "<p>Email ".$activeuser->email."</p>";}
//echo "<p>Pass ".$activeuser->pwd."</p>";
echo"<h1> HOMEPAGE, LOGIN OK </h1>";
It seems the homeController,and so the afterlogin page cannot access the user created in the baseController file. If I try an echo inside the baseController of $this->user->username everything is working. What should I do?? HELP!!
The client-server lifecycle is effectively stateless; on every page load, your variables and objects are wiped out.
There are the client-sourced $_POST and $_GET superglobals, which is part of the standard form submission and url query processes.
The server has databases, file writing (sketchy from a security POV) and the $_SESSION superglobal. These are the ways the server can manage a data state between pageloads.
Understand that if you're using objects, you need to have them instantiated on every page load for them to work. You can store your user_ID in $_SESSION['user_ID'] and instantiate the user object from it every time, making appropriate changes according to how the data changes.

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

The way to use OOP on a login procedure

In the current login method:
$sth = $this->db->prepare("SELECT id, username, active FROM user WHERE username = ? AND password = ?");
$sth->setFetchMode(PDO::FETCH_OBJ);
$sth->execute(array($username, $password));
if (($obj = $sth->fetch()) !== FALSE)
return $obj;
And on the login.php file.
$auth = new Auth($db);
$user = $auth->login('username', 'password');
if ($user) {
if ($user->active == 0) { die('You must activate your account')}
//If all is okay... Set the session variables...
}
But I was told that I rather would set the session variables in the login() method, but If I do so, how should I instead handle the checks like if the user is activated or not?
I'd probably create a structure like this:
class Auth {
public function login($user, $pass);
public function logout();
public function loggedIn();
private function getUserSession();
private function updateUserSession();
private function deleteUserSession();
}
login() checks against the database and on authentication success (if the user is active, user:password match and other tests) runs updateUserSession(). Ends by returning the result of $this->loggedIn().
logout() unsets the session with deleteUserSession().
loggedIn() checks against the session with getUserSession() and returns true or false if the user is logged in.
You could do it in either procedure. The session vars are the same.
To check for an active user just add a " and userActive = 1" in your query. To deactivate a user just change this column to a 0 for that user.

Categories