I have the following code to identify a session for language_id OR set a session if a $_GET varaiable is passed. The following function detectLanguage() is called in my component Controller.php file inside init();
private function detectLanguage()
{
if(isset($_GET['language_code']) && !empty($_GET['language_code'])){
$language = Language::model()->find(array(
'condition' => 'iso_code = :iso_code',
'params' => array(':iso_code' => $_GET['language_code']),
));
if($language != NULL){
Yii::app()->session['language_id'] = $language->id;
$this->redirect(Yii::app()->request->urlReferrer);
} else {
$this->redirect(Yii::app()->request->urlReferrer);
}
} else {
$currentLang = (isset(Yii::app()->session['language_id']))? Yii::app()->session['language_id'] : 1;
if(Language::model()->find(array('condition' => "id = :id AND country_id = :country_id",'params' => array(':id' => $currentLang, 'country_id' => $this->country_details['ID'])))){
return $currentLang;
} else {
Yii::app()->session['language_id'] = 1;
return 1;
}
}
}
When I go to the URL ...?language_code=ru, it successfully sets the session and redirects to the referrer URL, but when I then refresh the page, it resets the language_id session to 1.
I do not understand, as far as I can see, my logic in this function is fine.
EDIT: Also tried with cookies and there is no other code interacting with these SESSION variables which could be interferring.
Related
Using sessions we can achieve this, but need this without sessions or cookies.
<?php
class Employees extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew()
{
$response = array();
$this->auth(); // this value is always null returned by auth() method
}
}
?>
This is more of a OOP programming basics question. If you want to re-use a variable in another function of the same controller object, you have to set the variable globally for the Employees class and then set/get its value in your functions by using $this->yourVariableName. But the set value of the object instance can only be reused in that instance only. Which means that after the auth() function, another function should be called subsequently to "access" the $this->yourVariableName.
Another way is to pass the $jwtoken as a parameter to a function.
But the following code answers your question "How to pass calculated/final value of one function to other functions in a controller of Codeigniter application", if it doesn't, then your question should be corrected I guess.
Edit:
Ow ok, first the auth() function is being called, then you would like to pass the $jwtoken value to another function, am I right? Well once a function is finished executing, the variable "disappears" if not passed to another function. If you would like to process the $jwtoken value immediately within the auth() function, then the answer is to pass the $jwtoken value to another function from within the auth() function:
<?php
class Employees extends CI_Controller
{
public function __construct() {
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
// this is one way you can pass the value to another function, depending on what you want to do, you can also place a condition and continue only if the return value of the following function is respected:
$this->addNew($jwtoken);
// What is the addNew() supposed to do?
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew($jwtoken = "default_value_if_not_set") {
echo $jwtoken;
}
}
Since you are creating an API, I assume the API is a REST api and stateless, so there is no interference of sessions and cookies.
I assume your process works like this:
User does a login request from the app to the api and the api returns a token when the credentials check is valid
The token is stored in the app (in a local database for example) and used for other requests
So the only thing you need to do is (I assume you have a route to addNew):
public function addNew() {
$token = $this->input->get('token');
$loginData = $this->validateToken($token);
//... add new process
}
And from your app you need to pass the token with the request to the api.
How do you validate the token?
To obtain the data you have set in the token, you have to decode the token:
/**
* throws SignatureInvalidException
*/
function validateToken($token)
{
$jwt = new JWT();
return $jwt->decode($token, jwtSecretKey, 'HS256');
}
Code improvement
Avoid using sessions and cookies
Since your api is stateless, you have to avoid settings cookies or sessions. So in your controller you can remove the flash data helper:
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
# REMOVE THIS LINE
# $this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => "Wrong email or password", //CHANGE THIS LINE
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
# REMOVE THIS LINE
# $this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => "Scucessfully login!", //CHANGE THIS LINE
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
Return the output response instead of $jwtoken
In your response you have already set the the token, so you can simply return the response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($response));
Your query is vulnerable to sql injections
Use escape method around you variables or bind the params:
$sql = "select * from admin_tbl where email=? and password = ?";
$query = $this->db->query($sql, array($adminEmail, $adminPassword));
I am trying to resolve a bug on a client's application, but i can't log in.
So i go to application.dev/metier/login, with application.dev as my virtual host, metier my admin route page and login the page to log in the application.
I complete the form, click on connect, i am getting logged in, redirected to the index page (application.dev/metier/index) but immediately after the redirection i am kicked out to the login page. The url is still application.dev/metier/index, but the i am seeing the login page as i was not authenticated.
I checked session, cleared after redirection.
It is like it's working fine, I am known from database, inserted in session, known as admin, but kicked out no matter what i do. No error, no log. Zend do not enter indexAction().
I can't go to another page due to the routing, and if i try to put my informations in session before access login page, i have an error "too many redirections" (i am in authenticated so go to index, but no i am kicked out, but i am authenticated, but i am kicked out...).
I am on Zend framework 1.12.18, Windows 10, with laragon (Kaspersky as antivirus). I also tried with wamp, and on an Ubuntu VM with xampp, same problem. I tried on another computer, same problem.
It works on the developer who gave me the source code. He gave me the original code and the code with his modification (of application.ini mainly), both give me the "error".
Controller:
public function loginAction() {
try {
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$this->redirect('/metier/index/');
return;
}else{
Zend_Session::regenerateId();
}
$loginForm = new Application_Form_Admin_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($loginForm->isValid($request->getPost())) {
if ($this->_process($loginForm->getValues())) {
// We're authenticated! Redirect to the home page
$this->_helper->redirector('index', 'index');
}
} else {
Log::debug('User sent invalid data.', __FILE__, __LINE__);
Log::debug($request->getPost(), __FILE__, __LINE__);
Log::debug('Errors: ', __FILE__, __LINE__);
Log::debug($loginForm->getErrors(), __FILE__, __LINE__);
$this->view->error = Zend_Registry::get('Language')->errors->login->error;
}
}
} catch (Exception $e) {
//$this->view->error = 'Wrong username and/or password';
$this->redirect('/metier/login/');
return;
}
$this->view->form = $loginForm;
}
protected function _process($values) {
if (!trim($values['username']) || !trim($values['password'])) {
$this->view->error = Zend_Registry::get('Language')->errors->login->empty;
return false;
}
// Get our authentication adapter and check credentials
$adapter = $this->_getAuthAdapter();
$adapter->setIdentity($values['username']);
$adapter->setCredential($values['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
Log::debug('Authentication returned result code: ' . $result->getCode(), __FILE__, __LINE__);
switch ($result->getCode()) {
case Zend_Auth_Result::SUCCESS:
$mdlMetierDep = new Application_Model_DbTable_MetierDepartement();
$user = $adapter->getResultRowObject();
$metDepObj = $mdlMetierDep->fetchRow(array('id_metier = ?' => $user->id_metier, 'id_departement = ?' => $user->id_departement));
if (!$metDepObj) {
$this->view->error = Zend_Registry::get('Language')->errors->login->error;
return $this->_redirect('/metier/login/');
}
$user->Role = Acl::ROLE_ADMIN_METIER;
$user->id_metier_departement = $metDepObj->getIdMetierDepartement();
$user->metier = $metDepObj->findMetier()->toArray();
$user->department = $metDepObj->findDepartement()->toArray();
// to help thwart session fixation/hijacking
// store user object in the session
$authStorage = $auth->getStorage();
$authStorage->write($user);
$this->_redirect('/metier/index/');
break;
case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
default:
$this->view->error = Zend_Registry::get('Language')->errors->login->error;
break;
}
if ($result->isValid()) {
$user = $adapter->getResultRowObject();
//$auth->getStorage()->write($user);
return true;
}
return false;
}
The login and reporting actions (just for informations, zend do not goes in it)
public function indexAction() {
$this->go('reporting');
}
public function reportingAction() {
$this->loadJs(('/scripts/metier/general.js'));
$this->loadCss(('/styles/metier/DataTable.css'));
$this->loadJs(('/scripts/jquery.dataTables.js'));
$this->loadJs(('/scripts/metier/data-table.js'));
}
Init function :
public function init() {
/* Initialize action controller here */
parent::init();
$this->loadCss(('/styles/web/tables2.css'));
$this->loadJs(('/scripts/web/tinyMceConfigs.js'));
$this->language = Zend_Registry::get('Language');
$this->view->language = $this->language;
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$this->storage = $auth->getStorage()->read();
$this->_getLogo();
} else {
$this->view->noLogo = true;
}
//enum field for indicateurs
$this->view->frequence = array('M', 'T', 'S', 'A');
$this->view->sens = array(
'A' => 'Croissant',
'D' => 'Décroissant',
);
$this->view->formulaType = array(
0 => 'rule',
1 => 'min',
2 => 'max',
3 => 'avg');
$this->view->FormulaOperand = array(
0 => '+',
1 => '-',
2 => '/',
3 => '*');
$this->view->tableauTypes = array(Constants::TABLEAU_STRUCTURE_DETAILLE, Constants::TABLEAU_STRUCTURE_COMPTEURS, Constants::TABLEAU_STRUCTURE_GRAPH);
$this->view->operands = array('+', '-', '*', '/');
$this->view->pageTypes = array(
Constants::PAGE_GARDE,
Constants::PAGE_CONTENU,
Constants::PAGE_TABLEAUX,
);
$this->view->HautEtBasTypes = array(
Constants::HEADER => Constants::HEADER,
Constants::FOOTER => Constants::FOOTER,
);
$this->loadCss('styles/forms.css', 'form_css');
$this->view->config = Zend_Registry::get('AppConfig');
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('add-metier', 'json')
->setAutoJsonSerialization(true)
->initContext();
$this->_loggedInUser = Zend_Auth::getInstance()->getIdentity();
ini_set('display_errors', 1);
error_reporting(E_ALL);
}
Classname :
class MetierController extends Reporting_Controller {...}
After debugging, it goes to $this->_redirect('/metier/index') and then kick me out
What could be the problem ?
I am trying to determine if the database Update performed in my model was successful, pass the status of it (successful or not successful) ultimately to my view so that I can display a div appropriately. So far, it's worked as long as the model update worked, but it is not working when it's not. I'm using flashdata to pass the data through the controller.
My model:
public function editTicket($ticket)
{
$q = $this->db->where('ticketId', $ticket['ticketId']);
$q = $this->db->update('tickets', $ticket);
$results = $this->db->affected_rows();
return $results;
}
My Controller:
public function editExistingTicket()
{
$this->load->model('tickets');
$date = date("Y-m-d H:i:s");
$ticket = array(
'ticketId' => $this->input->post('ticketId'),
'category' => $this->input->post('category'),
'headline' => $this->input->post('headline'),
'description' => $this->input->post('description'),
'assigned' => $this->input->post('assigned'),
'status' => $this->input->post('status'),
'priority' => $this->input->post('priority'),
'lastUpdated' => $date
);
if ($this->tickets->editTicket($ticket)){
$this->session->set_flashdata('edit', '1');
} else {
$this->session->set_flashdata('edit', '0');
}
}
My View (the relevant parts):
var edited = '<?php echo $this->session->flashdata('edit'); ?>';
if (edited == '1') {
$('#editMessage').slideDown('slow');
setTimeout(function(){$('#editMessage').slideUp('slow')}, 3000);
//sessionStorage.setItem('edit', '0');
} else if (edited == '2') {
$('#editFailMessage').slideDown('slow');
setTimeout(function(){$('#editFailMessage').slideUp('slow')}, 3000);
//sessionStorage.setItem('edit', '0');
}
Any ideas on what I did wrong?
Thanks for the help!
Well, in the controller you are setting the flashdata to 0 if the ticket is updated unsuccessfully:
$this->session->set_flashdata('edit', '0');
But as you can see in the view you are expecting the variable visited to be 2:
} else if (edited == '2') {
and then the error box will appear.
You should fix your values and i think everything will be fine.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
im getting error for this code.it says syntax error, unexpected T_PUBLIC in C:\wamp\www\openarc\application\controllers\login.php on line 32. i think a curly bracket is missing. but cant find it where. pls help me
<?php
/**
* This class use to registered users login to the site and logout
*/
class Login extends CI_Controller{
/*load the login page*/
function index($pass_details=false)
{
//if user is already logged in restrict login page to user
if($this->isLoggedin())
{
redirect('/');
}
//if user is not logged in
else
{
//if login failed pass $pass_details message to login view
if(isset($pass_details))
{
$login_messeage['loginErrorMessage'] = $pass_details;
// $login_messeage['userName'] = $pass_details['user_name'];
}
$login_messeage['page_id'] = "login";
//pass error message and user_name to view and show login page
$this->load->view("template",$login_messeage);
}
}
}
/*take the login form values and do the back end validation and send those values to the Login_model*/
public function user_login()
{
if(!$this->isLoggedin())
{
$username = $this->input->post('lg_username');
$password = $this->input->post('lg_password');
$url = $this->input->post('hidden_url');
//load the login_model
$this->load->model('Login_model');
//create an array and pass username and password
$user_login_details =array(
'username' => $username,
'password' => sha1($password),
);
//pass $user_login_details array to the Login_model get_specific_record function
$result = $this->Login_model->get_specific_record($user_login_details);
//get executed result counter of num_rows into $numrows variable
$numrows = $result->num_rows();
//get database values to variable into variables from executed result
if($numrows>0)
{
foreach ($result->result() as $row)
{
$uname = $row->username;
$upassword = $row->password;
$userid = $row->login_id;
$usertype = $row->user_type;
$userrefid = $row->reference_id;
}
if($usertype == 'Ad')
{ //echo "ggg";exit();
//check executed result num_rows() counter is grater than 0
//user details set to sessionArray to set session
$sessionArray = array(
'username' =>$uname,
'userType' =>$usertype,
'refId' =>$userrefid,
'login_status' => true
);
//create session and redirect user to home page(index page)
$this->session->set_userdata($sessionArray);
redirect('adminpanel');
}
else if ($usertype == 'Op') {
//user details set to sessionArray to set session
$sessionArray = array(
'username' => $uname,
'userType' => $usertype,
'refId' => $userrefid,
'login_status' => true
);
//create session and redirect user to home page(index page)
$this->session->set_userdata($sessionArray);
redirect('Production');
}
else if($usertype == 'C')
{
//user details set to sessionArray to set session
$sessionArray = array(
'username' => $uname,
'userid' => $userid,
'userType' => $usertype,
'refId' => $userrefid,
'login_status' => true
);
//create session and redirect user to home page(index page)
$this->session->set_userdata($sessionArray);
$cartSessionArray = array(
'user_id' => $userid,
'status' => 'A'
);
$this->load->model('Cart_model');
$cart_result = $this->Cart_model->get_all_cart_data($cartSessionArray);
$cart_numrows = $cart_result->num_rows();
if($cart_numrows >0)
{
foreach ($cart_result->result() as $cart_row)
{
$cart_id = $cart_row->id;
$cart_name = $cart_row->name;
$cart_price = $cart_row->price;
$cart_qty = $cart_row->qty;
$insert_cart = array(
'id' => $cart_id,
'name' => $cart_name,
'price' => $cart_price,
'qty' => $cart_qty
);
$res = $this->cart->insert($insert_cart);
}
if($res)
{
if ($url == 'index')
{
redirect('place_order');
}
else
{
redirect($url);
}
;// redirect('/products');
}
else {
if ($url == 'index')
{
redirect('place_order');
}
else
{
redirect($url);
}
}
}
else
{
redirect($url);
}
}
else if($usertype == 'Ma')
{
//user details set to sessionArray to set session
$sessionArray = array(
'username' => $uname,
'userid' => $userid,
'userType' => $usertype,
'refId' => $userrefid,
'login_status' => true
);
//create session and redirect user to home page(index page)
$this->session->set_userdata($sessionArray);
redirect('management/monthly_order_count');
}
}
else
{
$pass_details = "<div class='alert alert-error'>Username or password is Wrong</div>";
$this->index($pass_details);
}
}
else
{
redirect('/');
}
}
/*logout the loged user*/
public function logout()
{
if($this->isLoggedin())
{
//unset session data for user logout
$this->session->sess_destroy();
//redirect to the home page
redirect('/');
}
}
}
}
?>
Typo:
}
}
} <---this bracket is closing your object
/*take the login form values and do the back end validation and send those values to the Login_model*/
public function user_login()
Since you've got an extra bracket, your class definition prematurely terminates, making public useless, since that's valid only inside a class definition.
You are closing the class definition on line 31...
...
28 $this->load->view("template",$login_messeage);
29 } // end if
30 } // end function index
31 } // misplaced end class definition
Get rid of the line 31.
I have created a Facebook App that i need people to only enter their data to once.
It's all working and the database is being populated, but i need to make sure people don't keep coming back and re-entering their data endlessly.
What's the best way to check if the user has already submitted their data ?
The signed_request could still have been submitted and their data not entered so i need the check for both to work.
Ideally the PHP would just check for FB ID + other data, and only display a confirmation / thankyou page.
Currently my php to send to the database is:
class Users_Model extends CI_Model {
protected $_name = 'users';
function add($id,$key,$value) {
$data = array(
'id' => $id,
'name' => $key,
'value' => $value
);
return $this->db->insert($this->_name, $data);
}
function update($id,$key,$value) {
$data = array(
'value' => $value
);
$this->db->where(array(
'id' => $id,
'name' => $key
));
return $this->db->update($this->_name, $data);
}
function exists($id,$key=null) {
if($key == null) {
$this->db->where(array(
'id' => $id
));
} else {
$this->db->where(array(
'id' => $id,
'name' => $key
));
}
$query = $this->db->get($this->_name);
if($query->num_rows() > 0) {
return true;
}
return false;
}
function remove($id) {
$data = array(
'id' => $id,
);
return $this->db->delete($this->_name, $data);
}
function all() {
$query = $this->db->get($this->_name);
$results = array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$results[]=$row;
}
}
return $results;
}
}
Any help much appreciated...
What's the best way to check if the user has already submitted their data ?
Check if you already have a record for the user’s Facebook id in your database.