PHP MVC - session not persisting - php

I'm building my own MVC framework in order to learn the ropes properly.
Ive managed to get a login system working, but sessions dont seem to be persisting across page changes.
Ive done some reason reading around and am running session_start() in the controller as a few people seem to be directing.
On login, my processLogin method runs successfully and stores the session data as expected. I know this has happened because Im doing a var_dump on it in the main header file and its there when the login form loads (im not destroying it at any point).
The trouble I have is when it comes to do a location change after successful login, it runs the 'gallery' method, the session array is still there, but empty.
Its exasperating and Id really appreciate any help.
Heres my extended controller class for reference:
session_start();
class Home extends Controller {
public function index() {
require 'application/views/_templates/header.php';
require 'application/views/home/index.php';
require 'application/views/_templates/footer.php';
}
// login function (validation carried out client side)
public function processLogin() {
if (isset($_POST['loginUsername'])) {
$home_model = $this->loadModel("HomeModel");
$home_model->processLogin($_POST['loginUsername'], $_POST['loginPassword']);
}
}
public function gallery() {
require 'application/views/_templates/header.php';
require 'application/views/home/gallery.php';
require 'application/views/_templates/footer.php';
}
}

First thing you should use session_start() at the beginning of main file, usually index.php and not in Controller (because we don't know how your framework is build.
You should make sure that everywhere in your webpage you use the same domain - for example with www. or without www. Otherwise you should use session_set_cookie_params() to set it other way (for example for all subdomains)

Related

Why are my cookies not persisting in Laravel (using Homestead, Vagrant)?

I've been using Laravel from command prompt in Windows 10, but the difficulty of switching between projects has made me switch to using Homestead. However, in a new project I have started there, I can't for the life of me get cookies to persist.
Here is my current code (for debugging this problem only):
use Illuminate\Support\Facades\Cookie;
// ......
public function __construct(Request $request) {
$customer_id = Cookie::get('customer_id');
if(!$customer_id) {
Cookie::queue('customer_id', time(), 3600);
}
dd($customer_id);
}
Expected output: On consecutive page loads, the visitor will see the same unix timestamp they initially opened the page at (I understand this is not a good way of handling it, again, this is just for reproducing the error.)
Reality: Every pageload will produce a different timestamp.
I've looked up as many discussions as I could find. Solutions that I tried:
Using the Route method of declaring cookies
Using good-old PHP setcookie
Using Cookie:make, and Cookie:forever
Adding 'customer_id' in the exceptions among EncryptCookies
Placing the route in the web middleware
Erasing php artisan cache, restarting vagrant
Making the session folder editable through chmod
Yet still, after applying all the above, the cookie is still gone after every page load.
Since I had no prior problem like this through Xampp's PHP, I have to assume there is a (hopefully) trivial and obvious problem with Vagrant that I don't yet know. Any advice is appreciated!
Queued cookies are only sent with responses, so be sure that your controller function does return one.
use Illuminate\Support\Facades\Cookie;
// ......
public function __construct(Request $request) {
$customer_id = Cookie::get('customer_id');
if(!$customer_id) {
Cookie::queue('customer_id', time(), 3600);
}
}
public function foo() {
...
return response('some text');
}
Also, if using some kind of api you have to add a middleware to include the cookies on the response. See Laravel 5.4 - Cookie Queue

Ion auth Codeigniter Login throwing errors after logging in

This is my first project using both Codeigniter and Ion Auth and I've finished this tutorial: http://www.rappasoft.com/tutorials/view/5#.U1bJLeZdWpo
But now that I've reached the end, I have an error that is appearing when all of my code looks identical to the tutorial. The error is:
Message: Creating default object from empty value
Filename: core/MY_Controller.php
Line Number: 13
But the odd thing is that the code from the MY_Controller file is copied right from the tutorial. Here's the code I have:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
if (!$this->ion_auth->is_admin()) {
redirect('auth/login');
} else {
//Store user in $data
$data->user_info = $this->ion_auth->user()->row();
//Load $the_user in all views
$this->load->vars($data);
}
}
}
?>
The correct view loads underneath the error but obviously I'd like to know what's wrong. Since this is my first turn time working with ion-auth and I'm relatively new to code igniter as well, I was wondering if anyone knew how to go about debugging an error like this. Teach a man to fish, feed him for a lifetime! I'd really appreciate not just solutions but methods so I can learn and do this on my own.
Are you working on PHP 5.4+ ?
In that case, you must declare $data before using it:
Change:
$data->user_info = $this->ion_auth->user()->row();
to
$data = new stdClass();
$data->user_info = $this->ion_auth->user()->row();
and try again. Hpe it helps!
I think I might have figured it out. I think the issue might be that the default login information (the ones provided by ion auth) do not have any additional information in the database. This means that when the $data variable goes to set the additional account information, it doesn't find anything. It's not a strong enough error to crash the page but it is warning me that there is no other account information available even though it is supposed to be looking for more info.
So how to fix this? Create a user for testing purposes with a full compliment of account information and see if that solves the problem. The only problem is that I don't know how to add new users using ion auth and my views aren't sophisticated enough yet to make that process easy.
I've looked at the create_user() method in the auth.php file but when you press submit after filling out the form, it kicks you back to the same page with all the info. I have a feeling an edit needs to be done here although I don't quite know what to change. I've been looking on the ion auth documentation but it seems a bit... sparse. I think I'm on the right track although I'd really like to hear if someone else has a better explanation or solution. As of now, I haven't actually fixed it yet. Just deduction.

PHPUnit Selenium 2 extension setting cookies

I'm trying to set cookies before test but for some reason they are not set.
Here is my example code:
class WebTest extends PHPUnit_Extensions_Selenium2TestCase
{
protected function setUp()
{
$this->setBrowser('firefox');
$this->setBrowserUrl('http://dev.local/');
}
public function testTitle()
{
$session = $this->prepareSession();
$session->cookie()->remove('language_version');
$session->cookie()->add('language_version', 'en')->set();
$this->url('/');
$this->assertEquals('Title in English', $this->title());
}
}
Does anyone know how to do it? Any help greatly appreciated.
I have found an answer to my question in Selenium documentation:
If you are trying to preset cookies before you start interacting with a site and your homepage is large / takes a while to load an alternative is to find a smaller page on the site, typically the 404 page is small (http://example.com/some404page)
Now my tests look something like this:
$this->url('/unit_tests.php');
$this->cookie()->remove('language_version');
$this->cookie()->add('language_version', 'en')->set();
$this->url('/');
$this->assertEquals('Title in English', $this->title());
The /unit_tests.php is an empty PHP file that lets me initially set the cookie for the page.
The cookie shouldn't exist so the remove will fail. Selenium runs the browser with a new empty profile on each run of a test suite.
.

Any set backs if I initialize codeigniter session every time controller gets called?

I having issues with Codeigniter sessions dying on IE randomly, I search everywhere and tried everything, the bug just wouldnt dissappear, i tried the function to check if ajax and wont sess_update() not working either, so my question is, what is the setback if I initialize the CI session every controller call? I have both native and CI sessions, but It would take me a few more days to change everything to Native sessions. its a temp fix.
class Transactions extends Controller {
function Transactions()
{
session_start();
parent::Controller();
$this->load->model('Modelcontracts');
$this->load->model('Modelsignup');
$this->load->model('Modeltransactions');
$this->session->set_userdata('account_id',$_SESSION['account_id']);
$this->session->set_userdata('email',$_SESSION['email']);
$this->session->set_userdata('account_type',$_SESSION['account_type']);
$this->session->set_userdata('parent_account_id',$_SESSION['parent_account_id']);
$this->session->set_userdata('accountrole_id',$_SESSION['accountrole_id']);
$this->session->set_userdata('user_type_id',$_SESSION['user_type_id']);
}
function index()
{
I never experience any problems with CodeIgniters sessions. Have you created the MySQL table for ci_sessions?
The setback is basicly that it's an unlogical call. If that doesn't matter, then I can't see any setbacks with it.
You could ease up the code like this though:
$arr = array('account_id', 'email', 'account_type', 'parent_account_id', 'accountrole_id', 'user_type_id');
foreach($arr as $h)
if (isset($_SESSION[$h]))
$this->session->set_userdata($h, $_SESSION[$h]);
// else echo "Session [{$h}] doesn't exist!";
Or extend your session library to do a
foreach(array_keys($_SESSION) as $h)
$this->CI->session->set_userdata($h, $_SESSION[$h]);
When loaded.
I don't think you should be using session_start() if you're having CodeIgniter manage your sessions (which you are if you're using CodeIgniter's set_userdata() / get_userdata() functions).
It says right at the top of the CI user docs that CI doesn't use PHP's native session handling, so this may be causing you trouble. The session is started automatically by loading the session library, either automatically if you put it in the config file or explicitly with $this->load->library('session');.
http://codeigniter.com/user_guide/libraries/sessions.html
-Gus
Edit: I came across a CI forum post regarding IE/CI session issues. Apparently it's a well-known issue. http://codeigniter.com/forums/viewthread/211955/

CodeIgniter: Can't Get My New Controller/View To Show

I am learning how to use codeIgniter as my php framework. I am reading through the documentation and watching the intro video and just generally following along with the first tutorial, but it's not working for me.
I have created a controller called "test.php" and a view called "test_view". The controller for this class is exactly like "welcome.php" and the view file just has some static html. However, when I go to index.php/test I get a 404 error.
I have also tried manipulating the original welcome files so that instead of calling a view it just echos "testing", yet I still see the original welcome message! I've tried clearing my browsing cash and refreshing, but to no avail.
Any suggestions? Thanks.
Edit: Here's the code for controllers/test.php
<?php
class Test extends Controller {
//Just trying to get it to echo test
public function index()
{
echo "test";
//$this->load->view('test_view');
}
}
?>
Try looking at this page in the documentation - this might solve your problem.
This basically means you should try typing index.php?/test/ instead (notice the question-mark).
First of all, check the above link. Might be useful.
If not, then...
Try changing the default controller in the config file ('routes.php') to something else (probably, to 'test'), then try loading index.php. Just to test whether the whole system works (or not).
Check whether mod_rewrite is loaded (in your server .conf-file, if you're using Apache).
Try using the latest build of the framework. AFAIK, the name of the controller class for now is "CI_Controller".
Finally, try removing the word 'public' before the declaration of the function. AFAIR, CI enable you to make private functions in controllers just by using prefix (which is set in the config file) at the beginning of the name of the function (thus making all the other functions public).
But most certainly the problem is with the mod_rewrite. If not, try debugging with die('Page found'); instead of echo - this will allow you to track possible redirects on the page.

Categories