redirect not working with 'REQUEST_METHOD' - codeigniter

On my login controller, I am trying ($this->input->server('REQUEST_METHOD') == 'POST') for submitting form instead of codeigniter form_validation
But when I use redirect() it does not redirect.
Question: Why does the redirects not working when submitting form with ($this->input->server('REQUEST_METHOD') and what is the best solution to get it to work.
Update: Does not seem to submit the form because I use $config['uri_protocol'] = 'QUERY_STRING'; Instead of $config['uri_protocol'] = 'REQUEST_URI';
But need to use $config['uri_protocol'] = 'QUERY_STRING';
Routes.php
$route['route=common/login'] = 'admin/common/login/index';
$route['route=common/dashboard&token=(:any)'] = 'admin/common/dashboard/index';
$route['route=common/logout&token=(:any)'] = 'admin/common/logout/index';
Config.php
$config['base_url'] = 'http://localhost/project-cms/admin/';
$config['index_page'] = '';
$config['uri_protocol'] = 'QUERY_STRING';
Login Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends MX_Controller {
public function index()
{
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$token = md5(mt_rand());
$url_token = '&token=' . $token;
echo "working";
//redirect('index.php?route=common/dashboard' . $url_token);
//$this->response->redirect($this->url->link('common/dashboard', $url_token, 'SSL'));
}
$data['action'] = $this->url->link('common/login', '', 'SSL');
$this->load->view('template/common/login', $data);
}
}
Login View
<form enctype="multipart/form-data" method="post" action="<?php echo $action;?>">
<input type="text" name="username" />
<input type="submit" value="Submit" />
</form>
Version: Codeigniter 3 & XAMPP With Windows 7

REQUEST_METHOD has nothing to do with your redirection issue.
You are using a wrong method to define routes.
$route['common/login'] = 'admin/common/login/index';
$route['common/dashboard/(:any)'] = 'admin/common/dashboard/index/$1';
$route['common/logout/(:any)'] = 'admin/common/logout/index/S1';
And you will get your token (in your controllers) as,
public function index($token)
{
echo $token;
}
And change your login controllers as,
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends MX_Controller {
public function index()
{
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$token = md5(mt_rand());
redirect('common/dashboard/' . $url_token);
}
$data['action'] = $this->url->link('common/login', '', 'SSL');
$this->load->view('template/common/login', $data);
}
}

Related

I can not upload a file in codeigniter

I cannot upload a file in codeigniter. Code I'm using:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->library('upload');
$this->load->library('form_validation');
$this->load->helper(array('form', 'url'));
$this->load->model('User_m');
}
public function form()
{
if($_POST){
//print_r($_POST);exit;
if(!empty($_FILES['userfile']['name']))
{
$config['upload_path'] = "./uploads/";
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['userfile']['name'];
//Load upload library and initialize configuration
//print_r($config);exit;
$this->load->library('upload',$config);
//$this->upload->initialize($config);
if($this->upload->do_upload('userfile')){
$uploadData = $this->upload->data();
$userfile = $uploadData['file_name'];
//echo $userfile;exit;
}
else
{
$userfile = '';
}
}
else
{
$userfile = '';
}
$data['name']=$this->input->post('name');
$data['email']=$this->input->post('email');
$data['phone']=$this->input->post('phone');
$data['userfile']=$userfile;
$this->User_m->form_insert($data);
}
$this->load->view('form');
}
}
This is my controller function code for processing multipart form data in codeigniter. But file is not uploading.
as you have given code i have modified code to trace it.Here below i have attached the view file as well as controller file :
1) Below is a view file code.In this i have submitted form by giving method name in action attribute.If you are submitting the form through ajax then you can pass the method name over there.
<div id="container">
<h1>Please Fill up the Registration Form.!</h1>
<div id="body">
<!-- <?php echo $error;?> -->
<form method="post" action="<?php echo site_url() . '/Main/form' ?>" enctype="multipart/form-data"> Full name:<br> <input type="text" name="name"><br> Email:<br> <input type="text" name="email"><br> Phone:<br> <input type="text" name="phone"><br><br> Image:<br> <input type="file" name="userfile" /> <br /><br /> <input type="submit"><br> </form>
</div>
</div>
2) Below is a controller code.
<?php
class Main extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url','html'));
}
public function index()
{
$this->load->view('form');
}
public function form()
{
if($_POST){
if(!empty($_FILES['userfile']['name']))
{
$config['upload_path'] = "./uploads/";
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['userfile']['name'];
//Load upload library and initialize configuration
//print_r($config);exit;
$this->load->library('upload',$config);
//$this->upload->initialize($config);
if($this->upload->do_upload('userfile')){
$uploadData = $this->upload->data();
$userfile = $uploadData['file_name'];
//echo $userfile;exit;
}
else
{
$userfile = '';
}
}
else
{
$userfile = '';
}
$data['name']=$this->input->post('name');
$data['email']=$this->input->post('email');
$data['phone']=$this->input->post('phone');
$data['userfile']=$userfile;
// Below $data getting all the form data
print_r($data);
}
$this->load->view('form');
}
}
Hope this will help you!
You can try this
public function form()
{
if($_POST){
if(!empty($_FILES['userfile']['name']))
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['userfile']['name'];
$this->upload->initialize($config);
$this->load->library('upload',$config);
if($this->upload->do_upload('userfile')){
$userfile = $_FILES['userfile']['name'];
}
else
{
$userfile = '';
}
}
else
{
$userfile = '';
}
$data['name']=$this->input->post('name');
$data['email']=$this->input->post('email');
$data['phone']=$this->input->post('phone');
$data['userfile']=$userfile;
$this->User_m->form_insert($data);
}

how to use jump to a specific div of current page in codeigniter

How do i convert this to codeigniter?
my php code for calling link is this
<ul>
<li>Register Here
<li>Login
</ul>
When I call this this specific link will be called.
<?php
#$opt = $_GET['option'];
if($opt=="") {
include('register.php');
error_reporting(1);
} else {
switch($opt) {
case 'register':
include('register.php');
break;
case 'login':
include('login.php');
break;
}
}
But I don't know how to do it in code igniter.
please help me
Try using a controller like Welcome.php or something
<?php
class Welcome extends CI_Controller {
public function index() {
// Load other data stuff.
// You should autoload the url helper.
$this->load->helper('url');
$opt = $this->input->get('option');
if($opt == "") {
$data['title'] = 'Register';
$this->load->view('header', $data);
$this->load->view('register');
$this->load->view('footer');
error_reporting(1);
} else {
switch($opt) {
case 'register':
$data['title'] = 'Register';
$this->load->view('header', $data);
$this->load->view('register');
$this->load->view('footer');
break;
case 'login':
$data['title'] = 'Login';
$this->load->view('header', $data);
$this->load->view('login');
$this->load->view('footer');
break;
}
}
}
Config.php
$config['base_url'] = 'http://localhost/yourproject/';
$config['index_page'] = 'index.php';
URI
$config['uri_protocol'] = 'REQUEST_URI';
To this
$config['uri_protocol'] = 'QUERY_STRING';
And then you can enable
$config['enable_query_strings'] = TRUE;
And use the built in codeigniter query strings.
Then you would use a link like
<li><?php echo anchor('c=welcome&option=register', 'Register');?></li>
The letter c mean controller in codeigniter query string but you can change that in config.php

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.

How to display custom error message without using codeigniter session flashdata

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);
}
}

Upload file to database using codeigniter

I need to upload a file in a mysql database using codeigniter.
My view is:
<?php echo form_open_multipart('home/addpagina2'); ?>
<label for="titolo">Titolo:</label>
<input type="text" size="20" id="titolo" name="titolo"/>
<br/>
<label for="testo">Testo</label><br/>
<textarea name="testo" cols="50" rows="10"></textarea>
<br/>
<label for="file">File:</label>
<input type="file" name="file" />
<br />
<input type="submit" value="Aggiungi"/>
</form>
and controller is:
function addpagina2(){
$this->form_validation->set_rules('titolo', 'Titolo', 'trim');
$this->form_validation->set_rules('testo', 'Testo', 'trim');
if($_FILES["file"]["size"] > 0){
$tmpName = $_FILES["file"]['tmp_name'];
$fp = fopen($tmpName, 'r');
$file = fread($fp, filesize($tmpName));
$file = addslashes($file);
fclose($fp);
}
$pagina = array();
$pagina['titolo'] = $this->input->post('titolo');
$pagina['testo'] = $this->input->post('testo');
$pagina['file'] = $file;
$this->db->insert('pagine', $pagina);
redirect('home/pagine');
}
When I want to display the file I call this view:
<?php
header("Content-type: ".$file['type']);
echo $file;
?>
that is called by this controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class File extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index(){
}
function id($id){
$immagine = $this->db->get_where('pagine', array('id' => $id));
$data['file'] = $immagine->row()->file;
$this->load->view('file', $data);
}
}
the problem is that I have an error while i call the view in the browser, as you can see here: http://mattialori.net/amv/index.php/file/id/2
If I upload a file on the database using phpmyadmin it works.
How can I do?
Why don't you just save the file name into the db?
Then you can upload the img in a specific folder and in your view yuo can set the full path from your folder and append the file name at the end.
EDIT:
you can use the File Upload class in this way:
//Check if the file exists in the form
if($_FILES['file']['name']!=""){
//load library
$this->load->library('upload');
//Set the config
$config['upload_path'] = './uploads/'; //Use relative or absolute path
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['overwrite'] = FALSE; //If the file exists it will be saved with a progressive number appended
//Initialize
$this->upload->initialize($config);
//Upload file
if( ! $this->upload->do_upload("file")){
//echo the errors
echo $this->upload->display_errors();
}
//If the upload success
$file_name = $this->upload->file_name;
//Save the file name into the db
}

Resources