How to display custom error message without using codeigniter session flashdata - codeigniter

On my project I am trying to create a error message for my session. I am trying to make it so that if session redirects to main page then will echo message that is on login controller.
Note: I am trying not to use session flashdata if possible. I
already know how to use flashdata.
When I login to my dashboard it displays token in url
Example http://localhost/project-session/index.php/dashboard/32118fa09a0ef2df16851d1f35e3f7d5
On my dashboard __construct() I have this code below.
if ($this->session->userdata('user_id') == FALSE) {
redirect('/');
}
The code above redirects session to home if token is false.
And if it has been redirected because session expires then below message should be activated, On login controller
$get_url_token = $this->uri->segment(2);
$get_session_token = $this->session->userdata('token');
if ((isset($get_session_token) && !isset($get_url_token)) || ((isset($get_url_token) && (isset($get_session_token) && ($get_url_token != $get_session_token))))) {
echo "Session Token Invalid";
}
Login Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->library('form_validation');
$this->load->library('encryption');
$key = bin2hex($this->encryption->create_key(16));
$get_url_token = $this->uri->segment(2);
$get_session_token = $this->session->userdata('token');
if ((isset($get_session_token) && !isset($get_url_token)) || ((isset($get_url_token) && (isset($get_session_token) && ($get_url_token != $get_session_token))))) {
echo "Session Token Invalid";
}
$this->form_validation->set_rules('username', 'Username');
$this->form_validation->set_rules('password', 'Password');
if ($this->form_validation->run() == FALSE) {
$this->load->view('welcome_message');
} else {
$data = array(
'token' => $key
);
$this->session->set_userdata($data);
redirect('dashboard' .'/'. $key);
}
}
}
Question: Without using codeigniter session flashdata how can I echo my message in my login controller when it is redirect to login because session expire. When I am redirect the echo message does not get activated.
Updated Login Controller
I have got message working but when I go to reload page it does not clear message. Any Suggestions.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
private $error = array();
public function index() {
$this->load->library('form_validation');
$this->load->library('encryption');
$key = bin2hex($this->encryption->create_key(16));
$this->form_validation->set_rules('username', 'Username');
$this->form_validation->set_rules('password', 'Password');
if ($this->form_validation->run() == TRUE) {
$this->session->set_userdata(array('token' => $key));
redirect('dashboard' .'/'. $key);
}
$get_url_token = $this->uri->segment(2);
$get_session_token = $this->session->userdata('token');
if ((isset($get_session_token) && !isset($get_url_token)) || ((isset($get_url_token) && (isset($get_session_token) && ($get_url_token != $get_session_token))))) {
$this->error['warning'] = 'Session Token';
}
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$this->load->view('welcome_message', $data);
}
}

Related

Codeigniter with google oauth2 adds hashtag php to redirect('usercp')

I want to be able to redirect to another controller but when user logins in with google and is success full it gets redirected to there usercp but for some reason it gets the # from the end of here
http://www.example.com/test/google?code=4/sorrynocodeshown#
And when redirects using codeigniter redirect() it adds # to it.
http://www.example.com/usercp#
Question When redirecting to new page once successful login how to stop # from being added.
I use https://github.com/moemoe89/google-login-ci3
I also use vhost with xammp
Controller function
public function google() {
if ($this->input->get('code')) {
$googleplus_auth = $this->googleplus->getAuthenticate();
$googleplus_info = $this->googleplus->getUserInfo();
$google_data = array(
'google_id' => $googleplus_info['id'],
'google_name' => $googleplus_info['name'],
'google_link' => $googleplus_info['link'],
'image' => $googleplus_info['picture'],
'email' => $googleplus_info['email'],
'firstname' => $googleplus_info['given_name'],
'lastname' => $googleplus_info['family_name']
);
$login_google_userid = $this->login_model->login_with_google($googleplus_info['id'], $google_data);
$_SESSION['user_id'] = $login_google_userid;
redirect('usercp');
}
}
config/googleplus.php settings
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['googleplus']['application_name'] 'Somename';
$config['googleplus']['client_id'] = '*****';
$config['googleplus']['client_secret'] = '*****';
$config['googleplus']['redirect_uri'] = 'http://www.mysetname.com/account/login/google';
$config['googleplus']['api_key'] = '*****';
$config['googleplus']['scopes'] = array();
I am using HMVC with codeigniter
application/modules/account/controllers/Login.php
Full Controller
<?php
class Login extends MX_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('googleplus');
}
public function index() {
if ($this->login_model->is_logged_in()) {
$this->session->set_flashdata('success', 'Welcome back! If you wish to logout ' . anchor('account/logout', 'Click Here'));
redirect(base_url('usercp'));
}
if (($this->input->server("REQUEST_METHOD") == 'POST') && $this->validateForm()) {
$this->load->model('account/login_model');
$user_info = $this->login_model->get_user($this->input->post('username'));
if ($user_info) {
$_SESSION['user_id'] = $user_info['user_id'];
redirect(base_url('usercp'));
}
}
$data['login_url'] = $this->googleplus->loginURL();
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
if (isset($this->error['username'])) {
$data['error_username'] = $this->error['username'];
} else {
$data['error_username'] = '';
}
if (isset($this->error['password'])) {
$data['error_password'] = $this->error['password'];
} else {
$data['error_password'] = '';
}
// Common
$data['header'] = Modules::run('common/header/index');
$data['navbar'] = Modules::run('common/navbar/index');
$data['footer'] = Modules::run('common/footer/index');
$this->load->view('login', $data);
}
public function validateForm() {
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
if ($this->form_validation->run() == FALSE) {
$this->error['username'] = form_error('username', '<div class="text-danger">', '</div>');
$this->error['password'] = form_error('password', '<div class="text-danger">', '</div>');
}
if ($this->input->post('username') && $this->input->post('password')) {
$this->load->model('account/login_model');
if (!$this->login_model->verify_password($this->input->post('username'), $this->input->post('password'))) {
$this->error['warning'] = 'Incorrect login credentials';
}
}
return !$this->error;
}
public function google() {
if ($this->input->get('code')) {
$googleplus_auth = $this->googleplus->getAuthenticate();
$googleplus_info = $this->googleplus->getUserInfo();
$google_data = array(
'google_id' => $googleplus_info['id'],
'google_name' => $googleplus_info['name'],
'google_link' => $googleplus_info['link'],
'image' => $googleplus_info['picture'],
'email' => $googleplus_info['email'],
'firstname' => $googleplus_info['given_name'],
'lastname' => $googleplus_info['family_name']
);
$login_google_userid = $this->login_model->login_with_google($googleplus_info['id'], $google_data);
$_SESSION['user_id'] = $login_google_userid;
redirect('usercp');
}
}
}
Codeigniter's redirect() function uses the php header() function in 2 ways:
switch ($method)
{
case 'refresh':
header('Refresh:0;url='.$uri);
break;
default:
header('Location: '.$uri, TRUE, $code);
break;
}
using the refresh parameter will not add the hashtag.
You find more about this in system/helpers/url_helper.php
you can use this to your advantage in google_login.php changing
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
accordingly to
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Refresh:0;url=' . filter_var($redirect, FILTER_SANITIZE_URL));
When calling the redirect, you should be able to drop the hash by using the refresh param:
redirect('usercp', 'refresh');
You can modifying the url by doing something like
$url = strstr($url, '#', true);
But otherwise since it's a client-side stuff there's not a lot of options. You could also remove it from javascript when the client load the page with
history.pushState('', document.title, window.location.pathname + window.location.search)
since this is too long in the comment section, here goes:
try to use your browser's debug mode/developer tools, and see the network part of it. in there, you could see the sequence of requests when your page are loading.
if you are using chrome, thick the preserve log option before doing the oauth.
do the oauth and then try to find the request to google that redirects to your page.
click on the request, you will get the details of the request.
see for the response header, it should be 302 status and the destination should be your http://www.example.com/usercp url.
if you did not see the #, then you have problems in your part, try to check your .htaccess file.
if it's there in the destination, then the problem lies in google part, and not much you can do about it

Cannot set session user_data in codeigniter when the apps was uploaded in hosting

I have a problem in my web app, I use codeigniter 2.2.6, the app work app work fine when i run in localhost but when i was upload to web hosting, cannot set session user_data. Any one can help and discuss my problem? Thanks
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->library('session');
}
public function index(){
if ($this->session->userdata('site_lang')=="") {
$this->session->set_userdata('site_lang','english');
}
$this->form_validation->set_rules('username_login', 'Username', 'required');
$this->form_validation->set_rules('password_login', 'Password', 'required');
if ($this->form_validation->run()){
//my code !
$m_url = URL_API;
$function = "login_user";
$username_login = $this->input->post('username_login');
$password_login = $this->input->post('password_login');
$url = $m_url . "/" . $function . "?" ."u=". $username_login . "&" ."p=". md5($password_login);
$json_data = file_get_contents($url);
$data = json_decode($json_data);
$status = $data->status;
if ($data->status == "000"){
$login= array (
'session_username_login' => $data->username,
'session_customer_id' => $data->customer_id,
'session_customer_no' => $data->customer_no,
'session_customer_name' => $data->customer_name,
'session_customer_email' => $data->customer_email,
'session_customer_gender' => $data->customer_gender,
'session_customer_status' => $data->customer_status,
'session_customer_handphone' => $data->customer_handphone,
'session_customer_birthday' => $data->customer_birthday,
'session_customer_address' => $data->customer_address,
'session_password_login' => md5($password_login) );
$this->session->set_userdata($login);
$_SESSION['session_username_login'] = $data->username;
}
elseif ($status == "007") {
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">'.lang('username_password_wrong').'</div>');
redirect(MENU_LOGIN);
}
elseif ($status == "005") {
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">'.lang('password_wrong').'</div>');
redirect(MENU_LOGIN);
}
elseif ($status == "004") {
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">'.lang('username_wrong').'</div>');
redirect(MENU_LOGIN);
}
}
if($this->session->userdata('session_password_login') != null){
redirect(MENU_MARKETPLACE);
exit;
}
}
$this->load->view(MENU_LOGIN);
}
}

Custom Error Message Does Not Display When Redirected If Session Expire

I am working on my login controller with Codeigniter Version 3.0.3 and HMVC
When the user logs on to the admin dashboard it sets a session token and then redirects it to url
http://localhost/projectname/admin/common/dashboard/?token=bf9691a625fbd0c3513ad822b0f76c6efb45e9b535c7b732d1ff006ce17f8734
When the session expires it redirects back to the admin page And should display message on login page. I am
trying to set a $data variable message instead of using flash data
For some reason when session expires and gets redirected back to admin the warning message does not activate.
Question: Why does the custom data message not show up when session expires once redirected back to admin login?
I also use codeigniter hook function to run the login check function
Controller
Filename: Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends MX_Controller {
private $error = array();
public function index() {
$data['title'] = 'Administration';
$data['heading_title'] = 'Administration';
if (($this->input->server('REQUEST_METHOD') == 'POST') && $this->validate()) {
$this->load->library('encryption');
$token = bin2hex($this->encryption->create_key(32));
$this->session->set_userdata(array('token' => $token));
redirect('admin/common/dashboard/?token=' . $token);
}
// Message Below Not Display On Login If Session Expire And Has Been Redirected Back To Admin
if ((isset($_SESSION['token']) && !isset($_GET['token'])) || ((isset($_GET['token']) && (isset($_SESSION['token']) && ($_GET['token'] != $_SESSION['token']))))) {
$this->error['warning'] = 'Your Session Token Is Invalid!';
}
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['header'] = Modules::run('admin/common/header/index', $data);
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('common/login', $data);
}
protected function validate() {
if (!isset($_POST['username']) || !isset($_POST['password']) || !$this->user->login($_POST['username'], html_entity_decode($_POST['password'], ENT_QUOTES, 'UTF-8'))) {
$this->error['warning'] = 'Incorrect Username Or Password!';
}
return !$this->error;
}
public function check() {
$uri_route = $this->uri->segment(2) .'/'. $this->uri->segment(3);
$route = isset($uri_route) ? $uri_route : '';
$ignore = array(
'common/login',
'common/forgotten',
'common/reset'
);
if (!$this->user->is_logged() && !in_array($route, $ignore)) {
redirect('admin/common/login');
}
if (isset($route)) {
$ignore = array(
'common/login',
'common/logout',
'common/forgotten',
'common/reset',
'error/not_found',
'error/permission'
);
if (!in_array($route, $ignore) && (!isset($_GET['token']) || !isset($_SESSION['token']) || ($_GET['token'] != $_SESSION['token']))) {
redirect('admin/common/login');
}
} else {
if (!isset($_GET['token']) || !isset($_SESSION['token']) || ($_GET['token'] != $_SESSION['token'])) {
redirect('admin/common/login');
}
}
}
}
Login View $error_warning
<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
Hook
<?php
$hook['pre_controller'] = array(
'class' => 'Login',
'function' => 'check',
'filename' => 'Login.php',
'filepath' => 'modules/admin/controllers/common'
);
Because you never set that messsage. Your session has expired, and your if has two parts.
First part: (isset($_SESSION['token']) && !isset($_GET['token'])): session has expired, the token is not set in session, so the first condition is false.
And the second, beefy condition: ((isset($_GET['token']) && (isset($_SESSION['token']) && ($_GET['token'] != $_SESSION['token']))), even if the token is set in the $_GET array that second condition will never be true, because your session has expired, and the token is not set in the session, and/or is not the same to the token in the $_GET array.

Parse error NuSOAP webservice with Codeigniter

I'm using CodeIgniter with NuSOAP library for webservices and this is the error I get when accessing the Client controller:
wsdl error: XML error parsing WSDL from http://localhost/turismoadmin/index.php/Webservice/index/wsdl on line 77: Attribute without value
This is the server controller:
class Webservice extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->library('soap_lib');
$server = new nusoap_server;
$server->configureWSDL('Agencia Turistica', 'urn:server');
$server->wsdl->schemaTargetNamespace = 'urn:server';
$server->register('addcontact',
array('nombre' => 'xsd:string', 'apellido' => 'xsd:string' , 'ciudad' => 'xsd:string'),
array('return' => 'xsd:string'));
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA: '';
$server->service($HTTP_RAW_POST_DATA);
}
function index()
{
if($this->uri->rsegment(3)=="wsdl"){
$_SERVER['QUERY_STRING']="wsdl";
}else{
$_SERVER['QUERY_STRING']="";
}
function addcontact($nombre, $apellido, $ciudad){
$this->modelo_turismo->addcontact($nombre, $apellido, $ciudad);
$resultado = $this->modelo_turismo->selectmax_contacto();
return (json_encode($resultado->fetch_all()));
}
}
}
and this is the Client controller:
class Client extends CI_controller {
function __construct() {
parent::__construct();
}
function index() {
$this->load->library('soap_lib');
$this->nusoap_client = new nusoap_client(site_url('Webservice/index/wsdl'), true);
$err = $this->nusoap_client->getError();
if ($err){
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
}
$result1 = $this->nusoap_client->call('addcontact', array("marcos","de lafuente","hermosillo"));
echo($result1);
// Check for a fault
if ($this->nusoap_client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result1);
echo '</pre>';
} else {
// Check for errors
$err = $this->nusoap_client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result1);
echo '</pre>';
}
}
}
}
I'm trying to do it based
ON THIS TOPIC (Thanks nana.chorage)
I also added this entry to my config/routes.php
$route['Webservice/wsdl']="Webservice/index/wsdl";
And for not to pass unnoticed, I can see my service when I enter this URL:
http://localhost/turismoadmin/index.php/Webservice/wsdl
I really dont know what I'm doing wrong, I have searched a lot around and I can't get rid of it!
Then nusoap client URL should be like this
$this->nusoap_client = new nusoap_client(site_url('Webservice/index?wsdl'), 'wsdl');

Joomla logout with message

I'm trying to modify the
'Token Interceptor' system plugin
by joomunited.com
The original plugin redirects on encountering an invalid token error using register_shutdown_function.
I'm trying to get it to:
Log the user out if they are logged in
Redirect to the login page with the invalid token message
Code:
$app = JFactory::getApplication();
if (!JFactory::getUser()->guest)
{
$app->logout();
}
$app->redirect('/index.php', JText::_('JINVALID_TOKEN'), 'warning');
I can successfully log the user out and redirect to the login page but the error message is not being displayed.
How can I retain the message after logging the user out?
i've also tried:
$app->enqueueMessage(JText::_('JINVALID_TOKEN'), 'warning');
but that didn't work either...
The solution I came up with was a variation of Alonzo Turner's 2nd post here.
The plugin redirects to the login page with a parameter passed in the url. The onAfterInitialise event then looks for this parameter and displays a message if it's found.
class PlgSystemTokeninterceptor extends JPlugin
{
public function __construct(&$subject, $config = array())
{
parent::__construct($subject, $config);
$app = JFactory::getApplication();
if (($app->isSite() && $this->params->get('use_frontend')) || ($app->isAdmin() && $this->params->get('use_backend')))
{
register_shutdown_function(array($this,'redirectToLogin'));
}
}
public function redirectToLogin()
{
$content = ob_get_contents();
if($content == JText::_('JINVALID_TOKEN') || $content == 'Invalid Token')
{
$app = JFactory::getApplication();
if (!JFactory::getUser()->guest)
{
$app->logout();
}
$app->redirect(JURI::base().'index.php?invalid_token=true');
return false;
}
}
function onAfterInitialise()
{
$app = JFactory::getApplication();
$invalid_token = $app->input->get('invalid_token', 'false');
if ($invalid_token == 'true')
{
$app->enqueueMessage(JText::_('JINVALID_TOKEN'), 'warning');
}
return true;
}
}
When you logout you destroy the session so you are not going to have the message any more.
This will get you a message on redirect.
$this->redirect = JUri::base() . 'index.php?option=com_users&view=login';
if (!JFactory::getUser()->guest && $app->input->getCmd('option') != 'com_users')
{
$app->enqueueMessage('message', 'warning');
//$app->logout();
$app->redirect($this->redirect);
}
This will not because the session is destroyed
$this->redirect = JUri::base() . 'index.php?option=com_users&view=login';
if (!JFactory::getUser()->guest && $app->input->getCmd('option') != 'com_users')
{
$app->enqueueMessage('message', 'warning');
$app->logout();
$app->redirect($this->redirect);
}
Not tested but
$app->logout()
echo '<div class="">'. JText::_('whatever you want') . '</div>';
$module = JModuleHelper::getModule('login');
$output = JModuleHelper::renderModule($module);
Something like that

Resources