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.
Related
I am trying to add the login function to my website, but when I clicked on the login button, the page crashes and gives the following error message:
/index.php - Uncaught Error: Call to a member function prepare() on
null in
/Users/xx/Documents/INFO2300/xx333-project-3/includes/init.php:56
Stack trace:
0 /Users/xx/Documents/INFO2300/xxproject-3/includes/init.php(82): exec_sql_query(NULL, 'SELECT * FROM u...', Array)
1 /Users/xx/Documents/INFO2300/xx-project-3/includes/init.php(199): log_in('xx333', 'xx')
2 /Users/xxDocuments/INFO2300/xx333-project-3/index.php(2): include('/Users/xx/D...')
3 {main} thrown in /Users/xx/Documents/INFO2300/xx333-project-3/includes/init.php on line
56
Here is my code for index.php:
<?php
include("includes/init.php");
$db = open_or_init_sqlite_db('secure/gallery.sqlite', 'secure/init.sql');
$messages = array();
// Set maximum file size for uploaded files.
// MAX_FILE_SIZE must be set to bytes
// 1 MB = 1000000 bytes
const MAX_FILE_SIZE = 1000000;
// Users must be logged in to upload files!
if ( isset($_POST["submit_upload"]) && is_user_logged_in() ) {
// TODO: filter input for the "box_file" and "description" parameters.
// Hint: filtering input for files means checking if the upload was successful
$upload_info=$_FILES["box_file"];
$upload_desc=filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING);
if ($upload_info['error']==UPLOAD_ERR_OK){
$upload_name=basename($upload_info["name"]);
$upload_ext = strtolower( pathinfo($upload_name, PATHINFO_EXTENSION) );
$sql="INSERT INTO documents(user_id,file_name,file_ext,description)VALUES(:user_id,:file_name,:file_ext,:description)";
$params=array(
':user_id' => $current_user['id'],
':file_name'=> $upload_name,
':file_ext'=>$upload_ext,
':description'=>$upload_desc,
);
$result=exec_sql_query($db, $sql, $params);
if ($result){
$file_id=$db->lastInsertId("id");
$new_path="uploads/documents/$file_id.$upload_ext";
move_uploaded_file($upload_info["tmp_name"],$new_path);
}
}
// TODO: If the upload was successful, record the upload in the database
// and permanently store the uploaded file in the uploads directory.
// $box_file=filter_input(INPUT_POST, "box_file", FILTER_SANITIZE_STRING);
// $description=filter_input(INPUT_POST,"description", FILTER_SANITIZE_STRING);
}
?>
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Home</title>
<link rel="stylesheet" type="text/css" href="style/all.css" media="all" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu">
</head>
<body>
<h1>Fine Art Photography</h1>
<div id="content-wrap">
<?php
// If the user is logged in, let them upload files and view their uploaded files.
if ( is_user_logged_in() ) {
foreach ($messages as $message) {
echo "<p><strong>" . htmlspecialchars($message) . "</strong></p>\n";
}
?>
<h2>Upload a File</h2>
<!-- TODO: Peer review this form checking to make sure it properly supports file uploads. -->
<form id="uploadFile" action="index2.php" method="post" enctype="multipart/form-data">
<ul>
<li>
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
<label for="box_file">Upload File:</label>
<input id="box_file" type="file" name="box_file">
</li>
<li>
<label for="box_desc">Description:</label>
<textarea id="box_desc" name="description" cols="40" rows="5"></textarea>
</li>
<li>
<button name="submit_upload" type="submit">Upload File</button>
</li>
</ul>
</form>
<?php
} else {
?>
<p><strong>You need to sign in before you can upload image.</strong></p>
<?php
include("includes/login.php");
}
?>
<!-- <h2>Saved Files</h2> -->
<h2>Categories</h2>
<h2>Photos</h2>
<div class="img">
<?php
$records = exec_sql_query($db, "SELECT * FROM images")->fetchAll(PDO::FETCH_ASSOC);
if (count($records) > 0) {
foreach($records as $record) {
echo "<div class=\"content\">";
echo "<div class=\"block\">";
echo "<img class=\"pic\" src=\"uploads/images/". $record["id"] . "." . $record["image_ext"]. "\"/>";
echo "<a href=\"uploads/images/". $record["id"] . "." . $record["image_ext"] .
"\"class=\"link\">" . htmlspecialchars($record["image_name"]) . "</a>";
echo "<p class=\"link\">" . htmlspecialchars($record["description"]). "</p>";
echo "</div>";
echo "</div>";
}
}
?>
</div>
</body>
</html>
And here is my code for init.php:
<?php
// vvv DO NOT MODIFY/REMOVE vvv
// check current php version to ensure it meets 2300's requirements
function check_php_version()
{
if (version_compare(phpversion(), '7.0', '<')) {
define(VERSION_MESSAGE, "PHP version 7.0 or higher is required for 2300. Make sure you have installed PHP 7 on your computer and have set the correct PHP path in VS Code.");
echo VERSION_MESSAGE;
throw VERSION_MESSAGE;
}
}
check_php_version();
function config_php_errors()
{
ini_set('display_startup_errors', 1);
ini_set('display_errors', 0);
error_reporting(E_ALL);
}
config_php_errors();
// open connection to database
function open_or_init_sqlite_db($db_filename, $init_sql_filename)
{
if (!file_exists($db_filename)) {
$db = new PDO('sqlite:' . $db_filename);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (file_exists($init_sql_filename)) {
$db_init_sql = file_get_contents($init_sql_filename);
try {
$result = $db->exec($db_init_sql);
if ($result) {
return $db;
}
} catch (PDOException $exception) {
// If we had an error, then the DB did not initialize properly,
// so let's delete it!
unlink($db_filename);
throw $exception;
}
} else {
unlink($db_filename);
}
} else {
$db = new PDO('sqlite:' . $db_filename);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
return null;
}
function exec_sql_query($db, $sql, $params = array())
{
$query = $db->prepare($sql);
if ($query and $query->execute($params)) {
return $query;
}
return null;
}
// ^^^ DO NOT MODIFY/REMOVE ^^^
// You may place any of your code here.
// $db = open_or_init_sqlite_db('secure/site.sqlite', 'secure/init.sql');
define('SESSION_COOKIE_DURATION', 60*60*1);
$session_messages = array();
function log_in($username, $password) {
global $db;
global $current_user;
global $session_messages;
if ( isset($username) && isset($password) ) {
// check if username exists in the database
$sql = "SELECT * FROM users WHERE username = :username;";
$params = array(
':username' => $username
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// There shouldn't be repetitive username.
$account = $records[0];
// Check if password is correct
if ( password_verify($password, $account['password']) ) {
// Create session
$session = session_create_id();
// Store session ID in database
$sql = "INSERT INTO sessions (user_id, session) VALUES (:user_id, :session);";
$params = array(
':user_id' => $account['id'],
':session' => $session
);
$result = exec_sql_query($db, $sql, $params);
if ($result) {
// If result exists, session stored in DB
// Send this back to the user.
setcookie("session", $session, time() + SESSION_COOKIE_DURATION);
$current_user = $account;
return $current_user;
} else {
array_push($session_messages, "Log in failed. Something went wrong");
}
} else {
array_push($session_messages, "Invalid username or password.");
}
} else {
array_push($session_messages, "Invalid username or password.");
}
} else {
array_push($session_messages, "No username or password given.");
}
$current_user = NULL;
return NULL;
}
function find_user($user_id) {
global $db;
$sql = "SELECT * FROM users WHERE id = :user_id;";
$params = array(
':user_id' => $user_id
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// users are unique, there should only be 1 record
return $records[0];
}
return NULL;
}
function find_session($session) {
global $db;
if (isset($session)) {
$sql = "SELECT * FROM sessions WHERE session = :session;";
$params = array(
':session' => $session
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// No repetitive sessions
return $records[0];
}
}
return NULL;
}
function session_login() {
global $db;
global $current_user;
if (isset($_COOKIE["session"])) {
$session = $_COOKIE["session"];
$session_record = find_session($session);
if ( isset($session_record) ) {
$current_user = find_user($session_record['user_id']);
// The session will last for 1 more hour
setcookie("session", $session, time() + SESSION_COOKIE_DURATION);
return $current_user;
}
}
$current_user = NULL;
return NULL;
}
function is_user_logged_in() {
global $current_user;
// if $current_user is not NULL, then a user is logged in.
return ($current_user != NULL);
}
function log_out() {
global $current_user;
// Remove the session from the cookie and fgo back in time to expire the session.
setcookie('session', '', time() - SESSION_COOKIE_DURATION);
$current_user = NULL;
}
// ---- Check for login, logout requests. Or check to keep the user logged in. ----
// Check if we should login the user
if ( isset($_POST['login']) && isset($_POST['username']) && isset($_POST['password']) ) {
$username = trim( $_POST['username'] );
$password = trim( $_POST['password'] );
log_in($username, $password);
} else {
// check if the user already logged in
session_login();
}
// Check if we should logout the user
if ( isset($current_user) && ( isset($_GET['logout']) || isset($_POST['logout']) ) ) {
log_out();
}
?>
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();
Good day! I'm trying to make a forgot password function in the CodeIgniter framework but I'm getting 2 errors when i try to send the e-mail.
Some database info (I'm using phpMyAdmin):
Db name: kadokado
Db table name: users
Db email column: email
Db password column: wachtwoord
My controller file (Auth.php) :
<?php
class Auth extends CI_Controller{
public function forgot()
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('forgot');
$this->load->view('templates/footer');
}else{
$email = $this->input->post('email');
$clean = $this->security->xss_clean($email);
$userInfo = $this->user_model->getUserInfoByEmail($clean);
if(!$userInfo){
$this->session->set_flashdata('flash_message', 'We hebben dit email adres niet kunnen vinden');
redirect(site_url().'auth/login');
}
if($userInfo->status != $this->status[1]){ //if status is not approved
$this->session->set_flashdata('flash_message', 'Your account is not in approved status');
redirect(site_url().'auth/login');
}
//build token
$token = $this->user_model->insertToken($userInfo->id);
$qstring = $this->base64url_encode($token);
$url = site_url() . 'auth/reset_password/token/' . $qstring;
$link = '' . $url . '';
$message = '';
$message .= '<strong>A password reset has been requested for this email account</strong><br>';
$message .= '<strong>Please click:</strong> ' . $link;
echo $message; //send this through mail
exit;
}
}
public function reset_password()
{
$token = $this->base64url_decode($this->uri->segment(4));
$cleanToken = $this->security->xss_clean($token);
$user_info = $this->user_model->isTokenValid($cleanToken); //either false or array();
if(!$user_info){
$this->session->set_flashdata('flash_message', 'Token is invalid or expired');
redirect(site_url().'auth/login');
}
$data = array(
'voornaam'=> $user_info->voornaam,
'email'=>$user_info->email,
'token'=>base64_encode($token)
);
$this->form_validation->set_rules('wachtwoord', 'Wachtwoord', 'required|min_length[5]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[wachtwoord]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('reset_password', $data);
$this->load->view('templates/footer');
}else{
$this->load->library('wachtwoord');
$post = $this->input->post(NULL, TRUE);
$cleanPost = $this->security->xss_clean($post);
$hashed = $this->password->create_hash($cleanPost['wachtwoord']);
$cleanPost['wachtwoord'] = $hashed;
$cleanPost['user_id'] = $user_info->id;
unset($cleanPost['passconf']);
if(!$this->user_model->updatePassword($cleanPost)){
$this->session->set_flashdata('flash_message', 'Er is iets foutgegaan');
}else{
$this->session->set_flashdata('flash_message', 'Uw wachtwoord is geupdate, u kunt nu inloggen');
}
redirect(site_url().'auth/login');
}
}
}
My model file (User_Model.php) :
<?php
class user_model extends CI_model {
public function getUserInfoByEmail($email)
{
$q = $this->db->get_where('users', array('email' => $email), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$email.')');
return false;
}
}
public function getUserInfo($user_id)
{
$q = $this->db->get_where('users', array('user_id' => $user_id), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$user_id.')');
return false;
}
}
public function insertToken($user_id)
{
$token = substr(sha1(rand()), 0, 30);
$date = date('Y-m-d');
$string = array(
'token'=> $token,
'user_id'=>$user_id,
'created'=>$date
);
$query = $this->db->insert_string('tokens',$string);
$this->db->query($query);
return $token . $user_id;
}
public function isTokenValid($token)
{
$tkn = substr($token,0,30);
$uid = substr($token,30);
$q = $this->db->get_where('tokens', array(
'tokens.token' => $tkn,
'tokens.user_id' => $uid), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
$created = $row->created;
$createdTS = strtotime($created);
$today = date('Y-m-d');
$todayTS = strtotime($today);
if($createdTS != $todayTS){
return false;
}
$user_info = $this->getUserInfo($row->user_id);
return $user_info;
}else{
return false;
}
}
}
?>
My view file (reset_password.php) :
<div class="col-lg-4 col-lg-offset-4">
<h2>Reset your password</h2>
<h5>Hello <span><?php echo $firstName; ?></span>, Voer uw wachtwoord 2x in aub</h5>
<?php
$fattr = array('class' => 'form-signin');
echo form_open(site_url().'auth/reset_password/token/'.$token, $fattr); ?>
<div class="form-group">
<?php echo form_password(array('name'=>'wachtwoord', 'id'=> 'wachtwoord', 'placeholder'=>'Wachtwoord', 'class'=>'form-control', 'value' => set_value('wachtwoord'))); ?>
<?php echo form_error('password') ?>
</div>
<div class="form-group">
<?php echo form_password(array('name'=>'passconf', 'id'=> 'passconf', 'placeholder'=>'Confirm Password', 'class'=>'form-control', 'value'=> set_value('passconf'))); ?>
<?php echo form_error('passconf') ?>
</div>
<?php echo form_hidden('user_id', $user_id);?>
<?php echo form_submit(array('value'=>'Reset Password', 'class'=>'btn btn-lg btn-primary btn-block')); ?>
<?php echo form_close(); ?>
</div>
And these are the errors I'm getting:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Auth::$user_model
Filename: controllers/Auth.php
Line Number: 123
Backtrace:
File: /home/ubuntu/workspace/application/controllers/Auth.php
Line: 123
Function: _error_handler
File: /home/ubuntu/workspace/index.php
Line: 315
Function: require_once
2nd error:
A PHP Error was encountered
Severity: Error
Message: Call to a member function getUserInfoByEmail() on a non-object
Filename: controllers/Auth.php
Line Number: 123
Backtrace:
I have absolutely no clue what I'm doing wrong and I hope someone can help me.
Thanks!
Load user model in auth controller. You can load it in constructor or in the function.
class Auth extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('user_model'); // load user model
}
public function forgot(){
// your code
}
In Function
class Auth extends CI_Controller{
public function forgot(){
$this->load->model('user_model'); // load user model
// your code
}
Not tested
You need to make sure that the user_model class is loaded from the controller. Like so:
class Auth extends CI_Controller {
function __construct() {
$this->load->model('user_model');
}
}
And be sure that you have the spelling/capitalization correct in the model class.
class User_Model extends CI_Model {
// rest of code
}
#frodo again.
First Error : in your controller code, you need to initialize model first than only you can use the model property.
public function forgot(){
// Changes required
$this->load->model('user_model');
$userInfo = $this->user_model->getUserInfoByEmail($clean);
}
Second Error :
if($userInfo->status != $this->status[1]){
$this->session->set_flashdata('flash_message', 'Your account is not in approved status');
redirect(site_url().'auth/login');
}
How you get the value of $this->status[1] variable. You can simply use if($userInfo->status != true).
Please change this code and let me know if you have any error.
When I use only 1 controller in my application, user, everything works fine. When I try to use 2 or 3 to divide the code and create some structure my application always give the following error :
A PHP Error was encountered
Severity: Warning
Message: session_start(): Cannot send session cache limiter - headers already sent (output started at /Applications/MAMP/htdocs/BT_dashboard/application/controllers/Project.php:99)
Filename: Session/Session.php
Line Number: 140
Backtrace:
File: /Applications/MAMP/htdocs/BT_dashboard/application/controllers/Project.php
Line: 11
Function: __construct
File: /Applications/MAMP/htdocs/BT_dashboard/index.php
Line: 292
Function: require_once
Googled it and tried many things but can't find an answer. I'm using codeigniter 3. My User controller looks like :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* User class.
*
* #extends CI_Controller
*/
class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('url'));
$this->load->model('user_model');
$this->load->model('employee_model');
$this->load->model('customer_model');
$this->load->model('project_model');
}
public function createProject() {
if ($_SESSION['userlevel']) {
if ($_SESSION['userlevel'] < 3) {
$userid = $this->uri->segment(3);
} else {
$userid = $this->input->post('userproject');
}
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('project_name', 'project name', 'trim|required|min_length[2]|callback_is_project_name_unique[' . $this->input->post('project_name') . ']');
$this->form_validation->set_rules('project_address', 'project address', 'trim|required|min_length[2]');
$this->form_validation->set_rules('project_description', 'project description', 'trim|required|min_length[2]');
$this->form_validation->set_rules('project_city', 'project city', 'trim|required|min_length[2]');
if ($this->form_validation->run() == FALSE) {
$data['userdata'] = $this->session->userdata;
$this->load->view('header', $data);
if ($_SESSION['userlevel'] < 3) {
$this->load->view('dashboard_add_project', $data);
} else {
$data['userslist'] = $this->user_model->get_users_list();
$this->load->view('dashboard_add_project_admin', $data);
}
$this->load->view('wrapper', $data);
} else {
$Address = urlencode($this->input->post('project_address'));
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=" . $Address . "&sensor=true";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;
if ($status == "OK") {
$Lat = $xml->result->geometry->location->lat;
$Lon = $xml->result->geometry->location->lng;
$LatLng = "$Lat,$Lon";
}
//pass validation
$data = array(
'project_name' => $this->input->post('project_name'),
'project_address' => $this->input->post('project_address'),
'project_description' => $this->input->post('project_description'),
'project_city' => $this->input->post('project_city'),
'project_finished' => $this->input->post('project_finished'),
'lat' => $Lat,
'lng' => $Lon,
);
//$this->db->insert('tbl_user', $data);
if ($this->user_model->create_project($data, $userid, $this->input->post('project_name'))) {
if ($_SESSION['userlevel'] > 1) {
$data['projectlist'] = $this->user_model->get_project_list();
$data['uncompleted_projects'] = $this->user_model->get_uncompleted_projects();
$data['completed_projects'] = $this->user_model->get_completed_projects();
} else {
$data['projectlist'] = $this->user_model->get_project_list_userid($userid);
}
$data['userdata'] = $this->session->userdata;
$this->load->view('header', $data);
$this->load->view('dashboard_projects', $data);
$this->load->view('wrapper', $data);
} else {
$data->error = 'There was a problem creating your new employee. Please try again.';
$data['userdata'] = $this->session->userdata;
// send error to the view
$this->load->view('header', $data);
$this->load->view('dashboard_add_project', $data);
$this->load->view('wrapper', $data);
}
}
}
}
My second controller, the project controller. This is the controller I want to use know to paste the createproject code so this gives more structure. But when I paste it here and adapt my views it gives the error. here's my project_controller code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
* File Name: employee.php
*/
class Project extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('url'));
$this->load->model('user_model');
$this->load->model('employee_model');
$this->load->model('customer_model');
}
public function createProject() {
//same as usercontroller
My User/login code in User controller :
public function login() {
$loggedin = $this->session->userdata('logged_in');
if (!$loggedin) {
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('user_mail', 'user mail', 'required');
$this->form_validation->set_rules('user_password', 'user password', 'required');
if ($this->form_validation->run() == false) {
$data = new stdClass();
$data->error = 'Check your user and password';
$this->load->view('dashboard_login', $data);
} else {
$usermail = $this->input->post('user_mail');
$password = $this->input->post('user_password');
if ($this->user_model->resolve_user_login($usermail, $password)) {
$user_id = $this->user_model->get_user_id_from_mail($usermail);
$user = $this->user_model->get_user($user_id);
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = (string) $user->user_name;
$_SESSION['logged_in'] = (bool) true;
$_SESSION['user_gsm'] = (string) $user->user_gsm;
$_SESSION['user_address'] = (string) $user->user_address;
$_SESSION['user_city'] = (string) $user->user_city;
$_SESSION['userlevel'] = $this->user_model->get_user_level((int) $user->user_id);
$_SESSION['user_mail'] = $usermail;
$data['userdata'] = $this->session->userdata;
if ($_SESSION['userlevel'] == "3") {
$data['employeetotal'] = $this->user_model->get_amount_employees();
$data['customertotal'] = $this->user_model->get_amount_customers();
$data['projectstotal'] = $this->user_model->get_amount_projects();
}
$this->load->view('header', $data);
$this->load->view('dashboard_index', $data);
$this->load->view('wrapper', $data);
} else {
$data = new stdClass();
// login failed
$data->error = 'Wrong username or password.';
// send error to the view
$this->load->view('dashboard_login', $data);
}
}
} else {
$data['userdata'] = $this->session->userdata;
$data['employeetotal'] = $this->user_model->get_amount_employees();
$data['customertotal'] = $this->user_model->get_amount_customers();
$data['projectstotal'] = $this->user_model->get_amount_projects();
$this->load->view('header', $data);
$this->load->view('dashboard_index', $data);
$this->load->view('wrapper', $data);
}
}
In config/autoload I've got following:
$autoload['libraries'] = array('database','session');
So, what is on line 99 in your Project.php controller?
So after debugging my session array while logging into my website, I find that when posting a form, all session data is lost. The session data is wiped when the updateDetails and changePassword methods are called. Why is this?
session_start() is called before any data processing
Upon a POST request, session data is set and unset (but not the entire $_SESSION variable)
I use the following code to check for POST requests:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
}
It only happens once: Once the session has been lost, the methods can be called without the issue occuring any further (until they lose the session through expiration or closing their browser).
index.php (part)
session_start();
$page = $_GET['p'];
$query = $_GET['q'];
$req = $_GET['req'];
$user = new User();
switch($page) {
case 'account':
if($req=="logout") {
if($user->isLoggedIn())
$user->logout();
header("Location: /?p=account");
exit();
}
else if($req=="signup") {
if($user->isLoggedIn()) {
header("Location: /?p=account");
exit();
}
else {
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$form_data = array('username' => $_POST['username'],
'password' => $_POST['password'],
'password_repeat' => $_POST['password_repeat'],
'title' => $_POST['title'],
'first_name' => $_POST['first_name'],
'surname' => $_POST['surname'],
'dob_day' => $_POST['dob_day'],
'dob_month' => $_POST['dob_month'],
'dob_year' => $_POST['dob_year'],
'gender' => $_POST['gender'],
'email' => strtolower($_POST['email']),
'email_repeat' => strtolower($_POST['email_repeat']));
if($user->signup($form_data)) {
header("Location: /?p=account");
exit();
}
}
}
}
else {
if($user->isLoggedIn()==true) {
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if($req=='editdetails') {
$form_data = array(
'title' => $_POST['title'],
'first_name' => $_POST['first_name'],
'surname' => $_POST['surname'],
'gender' => $_POST['gender'],
'phone' => $_POST['phone'],
'email' => strtolower($_POST['email']),
'password' => $_POST['password']
);
if($user->updateDetails($form_data)) {
header("Location: /?p=account");
exit();
}
}
else if($req=='changepassword') {
$form_data = array(
'old_password' => $_POST['old_password'],
'password' => $_POST['password'],
'password_repeat' => $_POST['password_repeat'],
);
if($user->changePassword($form_data)) {
header("Location: /?p=account");
exit();
}
}
}
$user->retrieveUserDetails();
$details=$user->getUserDetails();
}
else {
if($req) {
header("Location: /?p=account");
exit();
}
else if($_SERVER['REQUEST_METHOD'] == 'POST') {
$form_data = array('username' => $_POST['username'], 'password' => $_POST['password']);
if($user->login($form_data)) {
$user->retrieveUserDetails();
$details=$user->getUserDetails();
}
}
}
}
break;
}
user.php (part)
class User {
private $auth;
private $details;
private $session_alert;
function User() {
if(isset($_SESSION['alert']))
$this->session_alert = $_SESSION['alert'];
$this->auth = isset($_SESSION['auth']) ? $_SESSION['auth'] : null;
if(isset($this->auth)) {
$database= new Database;
if($database->checkUserSession($this->auth['user_id'],session_id())) {
$this->logged_in=true;
}
else {
$this->addSessionAlert('global','Your login session has possibly timed out, you may login again by clicking here.',true);
unset($_SESSION['auth']);
}
}
}
function login($data) {
$return = false;
$this->form = new Form($data,0);
if(!$this->form->getError()) {
$database= new Database;
$error_msg = "The username/password entered was invalid. Please check to see if they are correct and try again, or use the relevant links to recover your account.";
$salt = $database->getSaltByUsername($data['username']);
if($salt) {
$hash = $this->hashpwd($data['password'],$salt);
// Do login
$this->auth = array();
$this->auth['user_id'] = $database->checkUserByHash($data['username'],$hash);
if($this->auth['user_id']) {
session_regenerate_id();
if($database->doLogin($this->auth['user_id'],session_id())) {
$details=$database->getUserDetailsById($this->auth['user_id']);
$this->auth['first_name'] = $details['first_name'];
$_SESSION['auth']=$this->auth;
$this->logged_in=true;
$return = true;
}
else
$this->form->pushError('Something went wrong, please try again.');
}
else
$this->form->pushError($error_msg);
}
else
$this->form->pushError($error_msg);
}
return $return;
}
function logout() {
$return = false;
if(isset($this->auth)) {
$database= new Database;
if($database->clearUserSession($this->auth['user_id'],session_id())) {
unset($_SESSION['auth']);
$this->logged_in=false;
session_regenerate_id();
$return = true;
}
}
return $return;
}
function signup($data) {
$return = false;
$this->form = new Form($data,1);
if(!$this->form->getError()) {
$database= new Database;
if($database->checkUserByUsername($data['username']))
$this->form->pushError("The username entered already exists, please try again.");
else if($database->checkUserByEmail($data['email']))
$this->form->pushError("The e-mail address entered is already in use, please try again.");
else {
$dbarray = $data;
unset($dbarray['password'],$dbarray['password_repeat'],$dbarray['dob_month'],$dbarray['dob_day'],$dbarray['dob_year']);
$dbarray['dob']=date("Y-m-d", mktime(0,0,0,$data['dob_month'], $data['dob_day'], $data['dob_year']));
$dbarray['salt']=strtoupper(md5(mt_rand()));
$dbarray['hash'] = $this->hashpwd($data['password'],$dbarray['salt']);
// Do signup
$this->auth = array();
$this->auth['user_id'] = $database->newUser($dbarray);
if($this->auth['user_id']) {
session_regenerate_id();
if($database->doLogin($this->auth['user_id'],session_id())) {
$details=$database->getUserDetailsById($this->auth['user_id']);
$this->auth['first_name'] = $details['first_name'];
$_SESSION['auth']=$this->auth;
$this->logged_in=true;
}
$return=true;
}
else {
$this->form->pushError("Something went wrong, please try again.");
}
}
}
return $return;
}
function updateDetails($data) {
$return = false;
$this->form = new Form($data,2);
if(!$this->form->getError()) {
$database= new Database;
if( $database->checkUserByEmailNotById($data['email'],$this->auth['user_id']) ) {
$this->form->pushError("The e-mail address entered is already in use, please try again.");
}
else {
$salt = $database->getSaltById($this->auth['user_id']);
if($salt) {
$hash = $this->hashpwd($data['password'],$salt);
if($database->checkUserIdByHash($this->auth['user_id'],$hash)) {
$database->updateUserById($this->auth['user_id'],$data);
$return = true;
}
else
$this->form->pushError("The password entered was incorrect, please try again.");
}
}
}
return $return;
}
function changePassword($data) {
$return = false;
$this->form = new Form($data,3);
if(!$this->form->getError()) {
$database= new Database;
$salt = $database->getSaltById($this->auth['user_id']);
if($salt) {
$hash = $this->hashpwd($data['old_password'],$salt);
if($database->checkUserIdByHash($this->auth['user_id'],$hash)) {
$salt=strtoupper(md5(mt_rand()));
$hash = $this->hashpwd($data['password'],$salt);
if($database->updateSaltHashById($this->auth['user_id'],$salt,$hash)) $this->addSessionAlert('yourdetails','Your password has been changed successfully.',false);
$return = true;
}
else
$this->form->pushError("The old password entered was incorrect, please try again.");
}
}
return $return;
}
function isLoggedIn() {
return $this->logged_in;
}
function getUserDetails() {
return $this->details;
}
}
Starting a session inside a class's contructor method, just does not sound nice.
Use session_start(); at the top of the index.php page instead.
in each page where you want to use sessions you must call session_start ();
See here:
http://codex.wordpress.org/Function_Reference/wp_update_user
Note: If current user's password is being updated, then the cookies
will be cleared!
Now, why WordPress will do this is not clear, but it is clearly stated that cookies, and therefore sessions, will be removed on setting a password through wp_update_user().
Some people have found that applying an exit(); immediately after a redirect when setting the password, will prevent the cookies from being lost.