cakephp session can't be written - php

Controller
function login() {
// Don't show the error message if no data has been submitted.
$this->set('error', false);
// Does not render the view
$this->autoRender = false;
// If a user has submitted form data:
if(!empty($this->data)) {
$someone = $this->Student->findByStudentEmail($this->data['Student']['email']);
if(!empty($someone['Student']['student_pwd']) && $someone['Student']['student_pwd'] == $this->data['Student']['password']) {
$this->Session->write('eyeColor', 'Green');
$this->Session->write('Student', $someone['Student']);
// session information to remember this user as 'logged-in'.
echo "success";
} else {
echo "failed";
}
}
function main(){
$this->set('students', $this->Student->find('all'));
$this->set('eyeColor', $this->Session->read('eyeColor'));
// Render the specified view
$this->render('/pages/main');
}
view
main.ctp
<?php print $eyeColor; ?>

<?php echo $session->read('eyeColor') ?>
It's in the manual: http://book.cakephp.org/view/1466/Methods
Admittedly, though, it's not very clear. Maybe I'll submit an update.

Related

Log in Validation alert pop up even though i'm not login yet

I try to make an alert for invalid login so I use
$this->session->set_flashdata('error', 'Invalid Credentials');
redirect("admin/login");
and i put this in my index function
$data=[];
if (isset($_SESSION['error'])) {
$data['error']=$_SESSION['error'];
}else{
$data['error']="NO_ERROR";
}
//$this->load->helper('url');
$this->load->view('adminpanel/loginview',$data);
but when i reload my login page, the alert was already execute, can anyone help me with this?
this is my full controller
public function index()
{
$data=[];
if (isset($_SESSION['error'])) {
$data['error']=$_SESSION['error'];
}else{
$data['error']="NO_ERROR";
}
//$this->load->helper('url');
$this->load->view('adminpanel/loginview',$data);
}
function login_post(){
//$this->load->helper('url'); set at autoload file
// print_r($_POST); test the post result
if (isset($_POST)) {
$email=$_POST['email'];
$password=$_POST['password'];
$query = $this->db->query("SELECT * FROM `backenduser` WHERE `username`='$email' AND `password`='$password'");
if ($query->num_rows()) {
// credential are valid
$result = $query->result_array();
//echo "<pre>";
//print_r($result); die();
$this->session->set_userdata('user_id', $result[0]['uid']);
redirect('admin/dashboard');
}
else{
//invalid credentials
$this->session->set_flashdata('error', 'Invalid Credentials');
redirect("admin/login");
}
}
else{
die("Invalid Input!");
}
}
function logout(){
session_destroy();
}
}
Your problem is here:
if (isset($_POST)) {
...
}
This will always return true because $_POST is always available, so it will always show the alert. You can check if the request is post or not by:
if(count($_POST) > 0){
...
}
also use this
if(!empty($_POST)){
...
}

How to show a specific div in a view from controller in Codeigniter?

I am trying to use two divs in a view. If I am logged in as a user I want to show the div named as 'user'. If logged in as an admin I want to load a view which has div named as 'admin'. I want to do this in CodeIgniter.
My sample code is as follows,
if ($Admin == 0)
{
$data['visible']=$this->login_model->show_menu();
}
else
{
echo "I'm Admin";
$this->load->view('home');
}
Take 2 variables
$showAdmin and $showUser
In controller
function showView() {
$showAdmin = FALSE;
$showUser = FALSE;
if ($isAdminLoggedInYourCode) {
$showAdmin = TRUE;
}
else if ($isUserLoggedInYourCode) {
$showUser = TRUE;
}
$data['showAdmin'] = $showAdmin;
$data['showUser'] = $showUser;
$this->load->view('home', $data);
}
And in view,
if ($showAdmin) {
// Show Admin div
}
else if ($showUser) {
// Show User div
}
The doc : http://www.codeigniter.com/user_guide/general/views.html
Adding Dynamic Data to the View
Let's try it with your controller file. Open it add this code:
<?php
class Blog extends CI_Controller {
function index()
{
$data['title'] = "My Real Title";
$data['heading'] = "My Real Heading";
$this->load->view('blogview', $data);
}
}
?>
Now open your view file and change the text to variables that correspond to the array keys in your data:
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
</body>
</html>
So, in your case, you can do something like that :
if ($Admin == 0)
{
$data['visible']=$this->login_model->show_menu();
}
else
{
$data['visible']='admin';
echo "I'm Admin";
$this->load->view('home', $data);
}
And in your view :
if($visible == 'admin') {
echo '<div>Your admin display</div>';
}
else {
echo '<div>',$visible,'</div>';
}
Have you tried this ?
if ($Admin == 0)
{
$data['visible']=$this->login_model->show_menu();
}
else
{
echo "I'm Admin";
$this->load->view('home');
}
Use two different views for user and admin
class MY_Controller extends CI_Controller
{
public function index()
{
$data = getSomeStuff();
$admin = checkAdmin();
if($admin == 0) {
$this->load->view('user', $data);
} else {
$this->load->view('admin', $data);
}
}
}

jquery & php + if session is dead an error is returned

I've noticed if the session is dead (on an Jquery AJAX PHP Request) the data returned is preceeded with an error message if the session is needed in the request.
How do other sites deal with this?
Similar code is shown below - eg: its using a SESSION variable in the code which doesn't exist as the session is dead.
public function internal($variable) {
if($_SESSION['data'] == $variable) {
echo TRUE;
}else{
echo FALSE;
}
}
Should I use isset to check if the variable exists?
Should I be coding for dead sessions?
thx
You need to add the isset also:
public function internal($variable) {
if(isset($_SESSION['data']) && $_SESSION['data'] == $variable) { //add here
echo TRUE;
}else{
echo FALSE;
}
}
Try this
public function internal($variable) {
if($_SESSION['data']!="" && $_SESSION['data'] == $variable) { //add here
echo TRUE;
}else{
echo FALSE;
}
}
You can also do like this,
public function internal($variable) {
if(!empty($_SESSION['data']) && $_SESSION['data'] == $variable) { // modify here
echo TRUE;
}else{
echo FALSE;
}
}

Zend flash messenger

I have a form and the submit button check if true or false.
If it's true redirect to another page.
If it's false stay on the same page and print the error message.
The error message is print out with a flash messenger.
But, in some case it doesn't print in the first try when submit is false, it always print out on the second click.
Did I did something wrong?
And also, is there a way to set difference flash messenger name? Because, on my others pages that have flash messenger, print out the error when page is refreshed.
Here's the code:
if(isset($_POST['submit'])) {
// code to inputfields
if(true) {
//redirect to some page
} else {
// print the flash error on the same page
$this->_helper->flashMessenger->addMessage(" This email is already taken");
$this->view->messages = $this->_helper->flashMessenger->getMessages();
}
}
HTML:
<center>
<div style="color:red">
<?php if (count($this->messages)) : ?>
<?php foreach ($this->messages as $message) : ?>
<div id="field_name">
<strong style="text-transform:capitalize;">Email </strong>
- <?php echo $this->escape($message); ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</center>
flashmessenger is really designed to be used on a redirect of some kind, so any message you see probably comes from the prior action's execution. Your current code would not flash any message during the first 'post'.
you may have some luck if you try something like:
public function init()
{
//This will catch any messege set in any action in this controller and send
//it to the view on the next request.
if ($this->_helper->FlashMessenger->hasMessages()) {
$this->view->messages = $this->_helper->FlashMessenger->getMessages();
}
}
public function someAction()
{
if(isset($_POST['submit'])) {
// code to inputfields
if(true) {
//redirect to some page
} else {
// print the flash error on the same page
$this->_helper->flashMessenger->addMessage(" This email is already taken");
//will redirect back to original url. May help, may not
$this->_redirect($this->getRequest()->getRequestUri());
}
}
}
Here's an action I coded that demonstrates what you seem to be attempting.
public function updatetrackAction()
{
//get the page number
$session = new Zend_Session_Namespace('page');
$id = $this->getRequest()->getParam('id');
//get the entity object
$model = new Music_Model_Mapper_Track();
$track = $model->findById($id);
//get the form
$form = new Admin_Form_Track();
$form->setAction('/admin/music/updatetrack/');
//test for 'post' 'valid' and update info
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();
$newTrack = new Music_Model_Track($data);
$update = $model->saveTrack($newTrack);
//add message
$this->message->addMessage("Update of track '$update->title' complete!");
//redirects back to the same page number the request came from
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));
}
} else {
//if not post display current information
//populate() only accepts an array - no objects -
$form->populate($track->toArray());
$this->view->form = $form;
}
}

Carrying a value stored in a session from one page to another

I was watching a lesson on lynda.com and the code works for them but will not work when I try it. This is the exact code they use. Could use some help to why it is not working.
<?php
class Session
{
public $message;
function __construct(){
session_start();
$this->check_message();
}
public function get_message($msg="") {
if(!empty($msg)) {
// then this is "set message"
$_SESSION['message'] = $msg;
} else {
// then this is "get message"
return $this->message;
}
}
private function check_message() {
// Is there a message stored in the session?
if(isset($_SESSION['message'])) {
// Add it as an attribute and erase the stored version
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();
?>
and on the calling page
<?php
require_once("session_class.php");
function output_message($msg="") {
if (!empty($msg)) {
return "<p>$msg</p>";
} else {
return "";
}
}
if (isset($_SESSION['message'])) {
echo "session is set";
} else {
echo "session is not set";
}
$message = $session->get_message("working");
//$message = "Working";THIS WILL WORK
echo output_message($message);
?>
You haven't created an object instance on the calling page. Try this:
require_once("session_class.php");
$session = new Session();
EDIT
When you take out check_message() from the __construct, the SESSION is set because in your check_message() method, you have this:
unset($_SESSION['message']);
It basically destroys your session, that's why you see that message "session is not set".
If you want the session to be set, simply delete that line.

Categories