PHP: Maintain session data with a class object - php

I am a PHP OOP newbie and I am currently learning sessions. I have created a session class which is supposed to check if session variable $_SESSION['userID'] is set, and set the login status to true; as well as set the user id.There is also a function, setVars() to set other object properties when called:
session.php
<?php
class Session
{
public $log_in_status=false;
public $userID;
public $fname;
public $class_id;
public $email;
public function __construct()
{
session_start();
if ($_SESSION['userID'])
{
$this->log_in_status = true;
$this->userID = $_SESSION['userID'];
}
else
{
$this->log_in_status = false;
unset($_SESSION['userID']);
}
}
public function setVars($classID, $email, $fname)
{
$this->class_id = $classID;
$this->email = $email;
$this->fname = $fname;
}
}
$session = new Session();
The above class is in a require_once statement in init.php file:
<?php
#init.php
require_once("session.php");
Page1.php sets some properties in the $session instance by calling the setVars method, and after echo them to the screen. However, page2.php is not able to echo these same values from the object properties:
<?php
# page1.php
require_once("init.php");
$class_id = 1;
$email = "test#test.com";
$fname = "Toto The Dog";
$session->setVars($class_id, $email, $fname);
?>
<!DOCTYPE html>
<html>
<head>
<title>Testing sessions</title>
</head>
<body>
<?php
echo "Page 1 <br> <br>";
echo "objectClassID: " .$session->class_id . "<br>";
echo "objectEmail : " . $session->email . "<br>";
echo "objectFname : " . $session->fname . "<br> <br>";
echo "<a href='page2.php'>Go to Page 2</a>";
?>
</body>
</html>
//--------------------------------------------
<?php
# page2.php
require_once("init.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>Testing sessions</title>
</head>
<body>
<?php
echo "Page 2 <br> <br>";
echo "objectClassID: " . $session->class_id . "<br>";
echo "objectEmail : " . $session->email . "<br>";
echo "objectFname : " . $session->fname . "<br> <br>";
echo "<a href='page1.php'>Go to Page 1</a>";
?>
</body>
</html>
How can I get page2.php to be able to display the $session object properties?

If you want to persist the vars across pages, you need to store them in the $_SESSION array. For example
<?php
class Session {
public $log_in_status = false;
public $userID;
public $fname;
public $class_id;
public $email;
public function __construct() {
session_start();
if (isset($_SESSION['userID'])) {
$this->log_in_status = true;
$this->userID = $_SESSION['userID'];
}
$this->class_id = isset($_SESSION['class_id']) ? $_SESSION['class_id'] : null;
$this->email = isset($_SESSION['email']) ? $_SESSION['email'] : null;
$this->fname = isset($_SESSION['fname']) ? $_SESSION['fname'] : null;
}
public function setVars($classID, $email, $fname) {
$this->class_id = $_SESSION['class_id'] = $classID;
$this->email = $_SESSION['email'] = $email;
$this->fname = $_SESSION['fname'] = $fname;
}
}
$session = new Session();

Related

Calling Function on an object Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR)

Hello I have been trying to call a function on an object "person" multiple different ways in PHP to no success. There is a similar question on SO which has a solution that does not work for me. Calling any function with '->' operator results in error. Tested in multiple browsers so not a cache problem. Running PHP 5.6.30
Many thanks
<html>
<?php
class Person
{
public $Name;
public $Surname;
public $City;
public function __construct( )
{
//$this->Name = $p1;
//$this->Surname = $p2;
}
public function FullName()
{
echo "FULL NAME FUNCTION";
//return $this->Name . " " . $this->Surname;
}
}
?>
<head>
<title> Information Gathered </title>
</head>
<body>
<?php
echo "ALIVE" ;
$userName = $_POST['username'];
$surname = $_POST['surname'];
$city = $_POST['city'];
//echo "Hello". $userName . "</br>";
//echo $surname . "</br>";
//echo "from" . $city . "</br>";
//$SubmitedPerson = new Person($userName, $surname);
$SubmitedPerson = new Person;
$m_instance = SubmitedPerson->instance();
//SubmitedPerson::instance();
//SubmitedPerson->FullName();
//echo $fullname;
?>
</body>
You are missing dollar sign $ in front of SubmitedPerson.
Your code should look like this:
$SubmitedPerson = new Person;
$SubmitedPerson->FullName();

Need to add session_start() in every method in controller

I use simple mvc in my project. This is my base Controller
<?php
class Controller {
function __construct() {
$this->view = new View();
}
public function loadModel($name, $modelPath = 'models/') {
$path = $modelPath . $name .'_model.php';
if(file_exists($path)) {
require $modelPath . $name .'_model.php';
$modelName = $name . '_Model';
$this->model = new $modelName();
}
}
}
this is base View class
<?php
class View {
function __construct(){
}
public function render($name) {
require 'views/layouts/header.php';
require 'views/' . $name . '.php';
require 'views/layouts/footer.php';
}
}
I added session_start(); on the top header.php
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
....
and this is how I display error from controller in the view
<?php
if (isset($_SESSION['errors']) && count($_SESSION['errors']) > 0) {
echo '<div class="row"><div class="col-lg-10 col-lg-push-2">';
echo '<div class="alert alert-dismissible alert-danger"><button type="button" class="close" data-dismiss="alert">×</button><strong>Error!</strong><ul class="errors-list">';
foreach ($_SESSION['errors'] as $error) {
echo '<li>' . $error['message'] . '</li>';
}
echo '</ul></div></div></div>';
}
?>
but anyway I need to add session_start(); in the methods in controller, otherwise $_SESSION['errors'] isn't set
<?php
class User extends Controller {
function __construct(){
parent::__construct();
}
public function create() {
$name = $_POST['name'];
session_start();
unset($_SESSION['errors']);
unset($_SESSION['variables']);
$_SESSION['errors'] = array();
$_SESSION['variables'] = array();
$count = $this->model->checkIfUserExists($name);
if($count > 0) {
$_SESSION['errors'][] = array(
'message' => 'User Already exists',
);
$_SESSION['variables'] = array(
'name' => $_POST['name'],
'password' => $_POST['password'],
);
header('location: ' . URL . 'user/registration');
exit;
}
if(empty($_POST['name']) || empty($_POST['password'])) {
$_SESSION['errors'][] = array(
'message' => 'Fill required fields',
);
$_SESSION['variables'] = array(
'name' => $_POST['name'],
'password' => $_POST['password'],
);
header('location: ' . URL . 'user/registration');
exit;
}
$data = array();
$data['name'] = $_POST['name'];
$data['password'] = $_POST['password'];
$data['role'] = 2;
$userId = $this->model->create($data);
if($userId) {
$_SESSION['errors'] = $data['role'];
$_SESSION['loggedIn'] = true;
$_SESSION['userid'] = $userId;
header('location: ' . URL);
exit;
}
$_SESSION['errors'][] = array(
'message' => 'Error. Try again',
);
$_SESSION['variables'] = array(
'name' => $_POST['name'],
'password' => $_POST['password'],
);
header('location: ' . URL . 'user/registration');
exit;
}
}
and I don't understand why I need to add session_start(); in every method to make session works?
UPD
When I add check to method in controller
public function create() {
$name = $_POST['name'];
if(isset($_SESSION)) {
echo "yes";
} else {
echo "no";
}
die();
it displays 'no'
But when I tried to add session_start(); in construct
class User extends Controller {
function __construct(){
parent::__construct();
session_start();
}
I got an error
Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\test\views\layouts\header.php on line 1
Session needs to be initiated on every page call if you want to use it. This is a facility so you can have pages render faster if session is not needed and there is no overhead.
If you do not want to use session explicitly you can call that in your parent controller or bootstrap file which calls the class files.
On the other hand you can explicitly keep session on from your php.ini settings.

Cookies and variables

I've created a login class for my web app and it does work, but now I've created that infamous "keep me logged in" - checkbox and don't get it to work. Here's my class for login:
<?php
error_reporting(E_ALL ^ E_NOTICE);
class Login {
private $error;
private $connect;
private $email;
private $password;
public $row;
public function __construct(PDO $connect) {
$this->connect = $connect;
$this->error = array();
$this->row = $row;
}
public function doLogin() {
$this->email = htmlspecialchars($_POST['email']);
$this->password = htmlspecialchars($_POST['password']);
$this->rememberme = $_POST['rememberme'];
if($this->validateData()) {
$this->fetchInfo();
}
return count($this->error) ? 0 : 1;
}
public function validateData() {
if(empty($this->email) || empty($this->password)) {
$this->error[] = "Täyttämättömiä kenttiä";
} else {
return count($this->error) ? 0 : 1;
}
}
public function fetchInfo() {
$query = "SELECT * FROM users WHERE email = :email AND activation_token IS NULL";
$stmt = $this->connect->prepare($query);
$stmt->execute(array(
':email' => $this->email,
));
if($stmt->rowCount() == 0) {
$this->error[] = "Väärä käyttäjätunnus tai salasana";
return 0;
} else {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['email'] = $row['email'];
$_SESSION['name'] = $row['name'];
$_SESSION['profilepic'] = $row['profilepic'];
if(isset($this->rememberme)) {
setcookie("loggedin", "yes", time() + 25200);
}
}
if (Register::cryptPass($this->password) != $row['password']) {
$this->error[] = "Virheelliset kirjautumistiedot";
} else {
return true;
}
return count($this->error) ? 0 : 1;
}
public function displayErrors() {
if(!count($this->error)) return;
echo "<div class='login_error'>";
foreach($this->error as $key=>$value) {
echo "<p>".$value."</p>";
}
echo "</div>";
}
public function doLogout() {
session_destroy();
}
}
?>
And here's a small part of my code from my another file where I'm checking if the session or cookie is set:
<?php
if (isset($_SESSION['email']) || isset($_COOKIE['loggedin'])) {
?>
<div id="header_container_isloggedin">
<div class="container_12">
<header id="header">
<div class="grid-12">
<ul id="menu">
<li class="profile-name">
<a href="profile.php?id=<?php echo $_SESSION['user_id']; ?>">
<span class="header_username">
<img src="images/thumbnails/<?php echo $_SESSION['profilepic']; ?>"
class="profile_evensmaller"/>
<span class="header_name"><?php echo $_SESSION['name']; ?></span></span></a>
</li>
</ul>
<?php } ?>
The problem is that everytime the cookie is set, it doesn't display my profile picture or name since they've saved inside of $_SESSION variable. So how should I approach this and get this to work. I know that right now it's not the safest method, since I'm not generating any hashes for that cookie, but right now the only thing I'm interested in, is to get this one to work.

Need to edit and delete using DAO

I was wondering if anyone could help me with this problem i'm having.
I have a ReminderDAO class with methods to delete, edit, insert etc and a Reminder class with a constructor and get and sets.
I then have a a view reminders where it just lists all the reminders out.
I want to be able to add an edit and delete to this view page.
To use the delete and edit functions in my ReminderDAO class, i need to pass a reminder object through the function and i'm not quite sure how to do this.
If anyone could help me that would be of great help, i'm new to this language so i apologise if it's not great code.
Thank you in advance!
Reminder DAO
class ReminderDAO extends DAO {
public function __construct() {
parent::__construct();
}
public function insert($reminder) {
if (!isset($reminder)) {
throw new Exception("Reminder required");
}
$sql = "INSERT INTO Reminders(member_id, title, details, reminder_type) VALUES (?, ?, ?, ?)";
$params = array($reminder->getMember_id(), $reminder->getTitle(), $reminder->getDetails(), $reminder->getType());
$stmt = $this->link->prepare($sql);
$status = $stmt->execute($params);
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not save Reminder: " . $errorInfo[2]);
}
$sql = "SELECT LAST_INSERT_ID()";
$stmt = $this->link->prepare($sql);
$status = $stmt->execute();
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not retrieve new reminder's id: " . $errorInfo[2]);
}
$row = $stmt->fetch();
$id = $row[0];
$reminder->setId($id);
}
public function delete($reminder) {
if (!isset($reminder)) {
throw new Exception("Reminder required");
}
$id = $reminder->getId();
if ($id == null) {
throw new Exception("Reminder id required");
}
$sql = "DELETE FROM Reminders WHERE id = ?";
$params = array($reminder->getId());
$stmt = $this->link->prepare($sql);
$status = $stmt->execute($params);
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not delete reminder: " . $errorInfo[2]);
}
}
public function update($reminder) {
if (!isset($reminder)) {
throw new Exception("Reminder required");
}
$id = $reminder->getId();
if ($id == null) {
throw new Exception("Reminder id required");
}
$sql = "UPDATE Reminders SET member_id = ?, title = ?, details = ?, reminder_type = ? WHERE id = ?";
$params = array($reminder->getMember_id(), $reminder->getTitle(), $reminder->getDetails(), $reminder->getType());
$stmt = $this->link->prepare($sql);
$status = $stmt->execute($params);
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not update Reminder: " . $errorInfo[2]);
}
}
public function getReminder($id) {
$sql = "SELECT * FROM Reminders WHERE id = ?";
$params = array($id);
$stmt = $this->link->prepare($sql);
$status = $stmt->execute($params);
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not retrieve Reminder: " . $errorInfo[2]);
}
$reminder = null;
if ($stmt->rowCount == 1) {
$row = $stmt->fetch();
$id = $row['id'];
$member_id = $row['member_id'];
$title = $row['title'];
$details = $row['details'];
$type = $row['reminder_type'];
$reminder = new ReminderDAO($id, $member_id, $title, $details, $type);
}
return $reminder;
}
public function getReminders() {
$sql = "SELECT * FROM Reminders";
$stmt = $this->link->prepare($sql);
$status = $stmt->execute();
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not retrieve reminders: " . $errorInfo[2]);
}
$reminders = array();
$row = $stmt->fetch();
while ($row != null) {
$id = $row['id'];
$member_id = $row['member_id'];
$title = $row['title'];
$details = $row['details'];
$type = $row['reminder_type'];
$reminder = new Reminder($id, $member_id, $title, $details, $type);
$reminders[$id] = $reminder;
$row = $stmt->fetch();
}
return $reminders;
}
}
?>
Reminder Class
<?php
class Reminder {
private $id;
private $member_id;
private $title;
private $details;
private $reminder_type;
public function __construct($i, $m_id, $title, $det, $type) {
$this->id = $i;
$this->member_id = $m_id;
$this->title = $title;
$this->details = $det;
$this->reminder_type = $type;
}
public function getId() { return $this->id; }
public function getMember_id() { return $this->member_id; }
public function getTitle() { return $this->title; }
public function getDetails() { return $this->details; }
public function getType() { return $this->reminder_type; }
public function setId($i) { $this->id = $i; }
public function setMember_id($mID) { $this->member_id = $mID; }
public function setTitle($t) { $this->title = $t; }
public function setDetails($d) { $this->details = $d; }
public function setType($type) { $this->reminder_type = $type; }
}
?>
View Reminders
<?php
ob_start();
require_once 'includes/Member.php';
require_once 'includes/MemberDAO.php';
require_once 'includes/Reminder.php';
require_once 'includes/ReminderDAO.php';
require_once 'includes/session.php';
confirm_logged_in(); // needs to come before any html because it does a redirect
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
require 'toolbar.php';
$member = ($_SESSION['member']);
$reminderDAO = new ReminderDAO();
$reminders = $reminderDAO->getReminders();
echo "<p>Hello " . $member->getFN() . "</p>";
echo "<p>These are the current reminders: </p>";
foreach ($reminders as $rem) {
echo "<b>Title:</b> " . $rem->getTitle() . "<br />";
echo "<b>Details:</b> " . $rem->getDetails() . "<br />";
echo "<b>Type: </b>" . $rem->getType() . "<br />";
echo "</p>";
}
echo $display; ?>
Add Reminder?
</body>
</html>
<?php ob_flush(); ?>
edit_reminder_form.php class
<?php
ob_start();
require_once 'includes/session.php';
require_once 'includes/Member.php';
require_once 'includes/MemberDAO.php';
require_once 'includes/Reminder.php';
require_once 'includes/ReminderDAO.php';
require_once 'includes/session.php';
confirm_logged_in(); // needs to come before any html because it does a redirect
?>
<?php
$reminderDAO = new ReminderDAO();
$reminder = $reminderDAO->getReminder($_GET['id']);
?>
<html>
<head>
<title>Edit Reminder</title>
</head>
<body>
<table>
<tr>
<td>
<h2>Edit Reminder</h2>
<?php if (isset($_GET['errorMessage'])) echo "<p>".$_GET['errorMessage']."</p>"; ?>
<form action="edit_reminder.php" method="POST">
Title: <input type="text" name="title" value="<?php $reminder->getTitle(); ?>" /><br/>
Details: <input type="text" name="details" value="<?php $reminder->getDetails()?> " /><br/>
<select name="reminder_type" value="<?php $reminder->getType();?>">
<option value="Choose">Please choose a reminder type!</option>
<option value="Bill">Bill</option>
<option value="Shopping">Shopping</option>
<option value="Event">Event</option>
<option value="Birthday">Birthday</option>
<option value="Other">Other</option>
</select>
<br />
<input type="submit" name="reminder" value="Edit Reminder" />
</form>
<br />
Cancel
</td>
</tr>
</table>
</body>
<?php
//5.Close connection
if(isset($connection)) {
mysql_close($connection);
}
?>
</html>
<?php ob_flush(); ?>
You could send the ID of the reminder to the next page where you edit/delete a reminder.
foreach ($reminders as $rem) {
echo "<b>Title:</b> " . $rem->getTitle() . "<br />";
echo "<b>Details:</b> " . $rem->getDetails() . "<br />";
echo "<b>Type: </b>" . $rem->getType() . "<br />";
echo "[<a href='edit.php?id=" . $rem->getID() . "'>Edit</a>] ";
echo "[<a href='delete.php?id=" . $rem->getID() . "'>Delete</a>] ";
echo "</p>";
}
In edit.php you get the reminder object using the ID (e.g. $_GET['id']), load the data from the database using ReminderDAO and create a form populated with the reminder values. In that form, you should also put the reminder id, so when he submit the form to Save changes, you can identify the reminder that was edited.
After saving the changes, you can redirect him back to the list of reminders using header function.
Similar, in delete.php you can delete the reminder using the ID (e.g. $_GET['id']) and then redirect the user to the list of reminders.

PHP logging out

I am doing the Lynda.com learning PHP 2 videos and have run into a problem, in that the instructor seems to have neglected to tell us one of the steps he does in the video. I have uploaded the relevant video here http://www.youtube.com/watch?v=fFKgAa7RAjo but will also describe the problem. At 6:40 of the video, after logging in to our application, he arrives at public/admin/index.php which has two links on it. one link allows him to "view log file" which takes him to public/admin/logfile.php and the other link allows him to log out. He doesn't tell us how to make these links. I can obviously make a link to view logfile
View Logfile
but I don't know how to make the link that will log me out, because that will obviously involve some PHP.
I have included below the login.php file, the index.php file (it's redirected to index.php after logging in) and the functions.php file. Do you know how I would logout from this?
This is the login.php file
<?php
require_once("../../includes/initialize.php");
if($session->is_logged_in()){
redirect_to("index.php");
}
//Remember to give your form's submit tag a name="submit" attribute
if (isset($_POST['submit'])) {//Form has been submitted.
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//Check database to see if username/password exist
$found_user = User::authenticate($username, $password);
if ($found_user) {
$session->login($found_user);
log_action('Login', "{$found_user->username} logged in.");
redirect_to("index.php");
} else {
//username/password combo was not found in the database
$message = "Username/password combination incorrect.";
}
} else {//Form has not been submitted.
$username = "";
$password = "";
}
?>
<?php include_layout_template('admin_header.php'); ?>
<h2>Staff Login</h2>
<?php echo output_message($message); ?>
<form action="login.php" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input type="text" name="username" maxlength="30" value="<?php
echo htmlentities($username); ?>" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" maxlength="30" value="<?php
echo htmlentities($password); ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="login" />
</td>
</tr>
</table>
</form>
</div>
<?php include_layout_template('admin_footer.php'); ?>
Functions.php
<?php
function strip_zeros_from_date( $marked_string=""){
//first remove the marked zeros
$no_zeros = str_replace('*0', '', $marked_string);
//then remove any remaining marks
$cleaned_string = str_replace('*', '', $no_zeros);
return $cleaned_string;
}
function redirect_to( $location= NULL) {
if($location != NULL) {
header("Location: {$location}");
exit;
}
}
function output_message($message=""){
if (!empty($message)) {
return "<p class=\"message\">{$message}</p>";
} else {
return "";
}
}
function __autoload($class_name) {
$class_name = strtolower($class_name);
$path = LIB_PATH.DS."{$class_name}.php";
if(file_exists($path)){
require_once($path);
} else {
die("The file {$class_name}.php could not be found.");
}
}
function include_layout_template($template=""){
include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
function log_action($action, $message=""){
$logfile = SITE_ROOT.DS.'logs'.DS.'log.txt';
$new = file_exists($logfile) ? false : true;
if($handle = fopen($logfile, 'a')) { //apppend
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
$content = "{$timestamp} | {$action}: {$message}\n";
fwrite($handle,$content);
fclose($handle);
if($new) {chmod($logfile, 0755); }
} else {
echo "Could not open log file for writing.";
}
}
?>
Index.php
<?php
require_once('../../includes/initialize.php');
if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php include_layout_template('admin_header.php'); ?>
<h2>Menu</h2>
</div>
<?php include_layout_template('admin_footer.php'); ?>
Update
Initialize.php
<?php
//Directory_separator is a PHP pre-defined constant
// (\ for windows, / for Unix)
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
defined('SITE_ROOT') ? null :
define('SITE_ROOT', DS.'hsphere'.DS.'local'.DS.'home'.DS.'c263430'.DS.'quoralist.com');
// define('SITE_ROOT', realpath(dirname(__FILE__).'/../'));
//echo SITE_ROOT."<br/>";
defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes');
// die(LIB_PATH);
//echo LIB_PATH."<br/>";
require_once(LIB_PATH.DS."config.php");
require_once(LIB_PATH.DS."functions.php");
require_once(LIB_PATH.DS."session.php");
require_once(LIB_PATH.DS."database.php");
require_once(LIB_PATH.DS."database_object.php");
require_once(LIB_PATH.DS."user.php");
//echo("You die here");
?>
User.php
<?php
require_once(LIB_PATH.DS.'database.php');
class User extends DatabaseObject{
protected static $table_name="users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public function full_name() {
if(isset($this->first_name) && isset($this->last_name)) {
return $this->first_name . " " . $this->last_name;
} else {
return "";
}
}
public static function authenticate($username="",$password="") {
global $database;
$username = $database->escape_value($username);
$password = $database->escape_value($password);
$sql = "SELECT * FROM users ";
$sql .= "WHERE username = '{$username}' ";
$sql .= "AND password = '{$password}' ";
$sql .= "LIMIT 1";
$result_array = self::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false;
}
//common database methods
public static function find_all(){
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
global $database;
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql=""){
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record){
$object = new self;
//$object->id = $record['id'];
//$object->username = $record['username'];
//$object->password = $record['password'];
//$object->first_name = $record['first_name'];
//$object->last_name = $record['last_name'];
foreach($record as $attribute=>$value) {
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
$object_vars = get_object_vars($this);
return array_key_exists($attribute, $object_vars);
}
}
?>
Session.php
<?php
class Session {
private $logged_in=false;
public $user_id;
function __construct() {
session_start();
$this->check_login();
if($this->logged_in){
//actions to take right away if user is logged in
} else {
//actions to take right away if user is not logged in
}
}
public function is_logged_in() {
return $this->logged_in;
}
public function login($user) {
//database should find user based on username/password
if($user){
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->logged_in = true;
}
}
public function logout(){
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}
private function check_login(){
if(isset($_SESSION['user_id'])){
$this->user_id = $_SESSION['user_id'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session();
?>
<?php
session_start();
session_destroy();
?>
That should destroy all variables stored in the session. It is really primitive logging out, but it should work. After you do that just redirect to "index.php" or whatever page you want.

Categories