codeigniter 403 override status - php

i know this question has been asked before. But completely there is no any good answer for this problem.
i was using CSRF security and completely know how to use it. if the token is not valid, the csrf will return me like
An Error Was Encountered
The action you have requested is not allowed.
and in Security.php there is a function how the status was set
public function csrf_show_error()
{
show_error('The action you have requested is not allowed.', 403);
}
kindly, i need to custom the the error page.
like in config if we set $route['404_override'] = 'Page_error';
it would show the Page_error what we have set before.
is there any case how to override the 403 ?
thank you

All built-in error pages use templates, which are located under application/views/errors/ - you can edit those to change the appearance.
The CSRF error page in particular uses the 'error_general' template.
Can't use a controller for anything but the 404 page though.

Here is how I handled this. I created a MY_Security.php file in application/core with this PHP code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Security extends CI_Security{
public function __construct(){
parent::__construct();
}
public function csrf_show_error(){
if((!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'))
exit(json_encode(array(//put your array elements here)));
else
show_error('The action you have requested is not allowed.', 403);
}
}
?>

Related

In one CodeIgniter controller session is empty, in other all works

I developed this functionality locally on my laptop and all worked well, but when I uploaded changes on the server, I received an issue.
The check_admin_auth() function checks session variable and it is NULL when it calls from my controller (all other controllers in the project with the same code works well).
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Ctransaction extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->auth->check_admin_auth(); // this function
/* checks one session item to check is user logged and admin or not,
if not - redirects to login page. But in my case redirecting doesn't apply,
I see just white screen, page status 200. */
$this->db->query('SET SESSION sql_mode = ""');
}
public function index()
{
// some code here
$content = $this->parser->parse('gltransaction/list', $data, true);
$this->template->full_admin_html_view($content);
}
public function ajaxLoadGLTransactions()
{
// some code here
echo json_encode($result);
}
}
Please, can you help me to find where the problem is?
I think that's settings in php.ini or in the same place, but I didn't find a reason.
I tried to modify /system/libraries/Session/Session.php as it was recommended in web, but it didn't help.
Files with sessions are created in folder /application/ci_sessions and they stored all necessary data, but for some reason, my controller doesn't load it and returns on its page session with only one field - __ci_last_regenerate.
The library session is loaded in autoloader in configuration file.
Cookies are the same on working pages and on page of my controller.
CI Version 3.1.4
PHP Version 7.2.32
The problem was that before <?php I've added one more line. The file of controller was like:
// empty line without anything
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
// and all other code
Didn't think that it can make sense!

CodeIgniter error pages show in popup mode

How can we display all types of error messages without redirecting to the error pages application\errors\*error_pages*
Here, We'll stay in same page and if any error occurs on action, it'll show on popup mode. Can anyone help me with code example ?
Though the question is not clear. You can check the availability of a 404- not found page like this:-
First open routes.php in the application/config folder and set a custom controller name.
$route['404_override'] = 'my404/404_page'; //my404 is class name.
Create a new controller and write the following code in it.
<?php
class my404 extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function 404_page()
{
// instead of loading any view just handle this response via ajax call from your client side
$error= array();
$error['error_code']='404';
$error['error_message']='This url is not found';
echo json_encode($error);
}
}
?>

CodeIgniter 404 page

When I enter a non existent url on my site it takes me to the 404 page that is specified by this in routes.php:
$route['404_override'] = 'page/not_found';
So the design of the page is as I have made it in the view not_found.php in the "page" directory.
However if I use this function to manually enforce a 404:
show_404();
It takes me to the default CodeIgniter 404 page with no style:
404 Page Not Found
The page you requested was not found.
How can I make it go to the same 404 page that I specified in the routes file?
All the answers here seem very outdated (as of version 2, at least) or very overkill. Here's a much simpler and manageable way, which only involves two steps:
In application/config/routes.php modify the field 404_override to point to some controller:
// Specify some controller of your choosing
$route['404_override'] = 'MyCustom404Ctrl';
Inside the controller specified in your routes.php, implement the index() method so it loads your custom error 404 view. You might also want to set some headers so the browser knows you're returning a 404 error:
// Inside application/controllers/MyCustom404Ctrl.php
class MyCustom404Ctrl extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index(){
$this->output->set_status_header('404');
// Make sure you actually have some view file named 404.php
$this->load->view('404');
}
}
Like the in-code comment mentioned, be sure there's a view file in application/views/404.php where you actually have your custom 404 page.
As a side note, some of the answers in this page suggest you modify stuff inside /system, which is a bad idea because when you update your version of CodeIgniter, you'll override your changes. The solution I'm suggesting doesn't mess with core files, which makes your application much more portable and maintainable, and update resistant.
Use the _remap() function. This allows you to do some very powerful stuff with 404 errors beyond what is normally built in - such as
Different 404 messages depending if the user is logged in or not!
Extra logging of 404 errors - you can now see what the referring person was to the 404, thus helping track down errors. This includes seeing if it was a bot (such as Google bot) - or if it was a logged in user, which user caused the 404 (so you can contact them for more information - or ban them if they are trying to guess admin routes or something)
Ignore certain 404 errors (such as a precomposed.png error for iPhone users).
Allow certain controllers to handle their own 404 errors different if you have a specific need (i.e. allow a blog controller to reroute to the latest blog for example)
Have all your controllers extend MY_Controller:
class MY_Controller extends CI_Controller
{
// Remap the 404 error functions
public function _remap($method, $params = array())
{
// Check if the requested route exists
if (method_exists($this, $method))
{
// Method exists - so just continue as normal
return call_user_func_array(array($this, $method), $params);
}
//*** If you reach here you have a 404 error - do whatever you want! ***//
// Set status header to a 404 for SEO
$this->output->set_status_header('404');
// ignore 404 errors for -precomposed.png errors to save my logs and
// stop baby jesus crying
if ( ! (strpos($_SERVER['REQUEST_URI'], '-precomposed.png')))
{
// This custom 404 log error records as much information as possible
// about the 404. This gives us alot of information to help fix it in
// the future. You can change this as required for your needs
log_message('error', '404: ***METHOD: '.var_export($method, TRUE).' ***PARAMS: '.var_export($params, TRUE).' ***SERVER: '.var_export($_SERVER, TRUE).' ***SESSION: '.var_export($this->session->all_userdata(), TRUE));
}
// Check if user is logged in or not
if ($this->ion_auth->logged_in())
{
// Show 404 page for logged in users
$this->load->view('404_logged_in');
}
else
{
// Show 404 page for people not logged in
$this->load->view('404_normal');
}
}
Then in routes.php set your 404's to your main controller, to a function that DOES NOT EXIST - i.e.
$route['404'] = "welcome/my_404";
$route['404_override'] = 'welcome/my_404';
but there is NO my_404() function in welcome - this means ALL your 404's will go through the _remap function - so you achieve DRY and have all your 404 logic in one spot.
Its up to you if you use show_404() or just redirect('my_404') in your logic. If you use show_404() - then just modify the Exceptions class to redirect
class MY_Exceptions extends CI_Exceptions
{
function show_404($page = '', $log_error = TRUE)
{
redirect('my_404');
}
}
To change behavior of show_404 you need to modify a file from CI core (system/Core/Common.php), which is not very practical for feature updates.
Instead of that, you could:
Redirect users to the same place controller/method as specified in $route['404_override'].
You could create a custom library to handle custom 404's and use it like $libInstance->show_404();
public function show_404() {
set_status_header(404);
return "404 - not found";
}
Or use views:
public function show_404($template) {
set_status_header(404);
if (ob_get_level() > $this->ob_level + 1)
{
ob_end_flush();
}
ob_start();
include(APPPATH.'views/'.$template.'.php');
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
If you tried the user_guide you would see that is shows the following:
show_404('page' [, 'log_error']) The function expects the string
passed to it to be the file path to the page that isn't found. Note
that CodeIgniter automatically shows 404 messages if controllers are
not found.
So you need to pass the controller name as a first parameter. The second is for logging being enabled or disabled.
CodeIgniter comes with a default 404 error page But by using routing option of codeigniter you can easily show your custom 404 error page to your user.
To do this just go to route file of your codeigniter project and type below line
$route['404_override'] = 'error_404';
Here error_404 is a controller file to display the custom 404 error page or any other type of error page in your codeigniter project.
Create the error_404 file and copy this code into this file
class Error_404 extends CI_controller
{
public function index()
{
$this->output->set_status_header('404');
// Make sure you actually have some view file named 404.php
$this->load->view('Error_page');
}
}
Make Error_page view file in your CodeIgniter view folder and that's it, Type any wrong url and now you can see your custom 404 error page.
If you have any doubts then you can follow this tutorial which has step by step tutorial to create custom 404 error page in codeigniter
Change application/errors/error_404.php file to the page you want shown. That's the file that show_404() is showing...
*show_404('page' [, 'log_error'])
This function will display the 404 error message supplied to it using the following error template:
application/errors/error_404.php
The function expects the string passed to it to be the file path to the page that isn't found. Note that CodeIgniter automatically shows 404 messages if controllers are not found.
CodeIgniter automatically logs any show_404() calls. Setting the optional second parameter to FALSE will skip logging.*
You need to set below code in application/config/routes.php
$route['404_override'] = 'page/not_found';
After you create one controller in application/controller named "page.php"
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class page extends CI_Controller {
public function __construct(){
parent::__construct();
}
public function not_found() {
$this->load->view('not_found');
}
}
Then you can create your own design for 404 error page in application/view named "not_found.php"
<html>
<body>
<section>
<div>
<div align="center" style="margin-top:50px; margin-bottom:50px;">
<img src="<?php echo base_url();?>images/404.jpg" /> // will be your image path.
</div>
</div>
</section>
</body>
</html>
Or
<html>
<body>
<section>
<div>
<div align="center" style="margin:0px auto;">
<h1>OOPS!</h1>
<h3>Sorry, an error has occured, Requested page not found!</h3>
<h5 align="center">Back to Home</h5>
</div>
</div>
</section>
</body>
</html>

CakePHP-2.0: How can i redirect to home page when someone hits url http://site/controller/unknownaction in CakePHP-2.0?

http://site/users/abcd
Here is the error=>
Error: The action abcd is not defined in controller UsersController
Error: Create UsersController::abcd() in file: app/Controller/UsersController.php.
I want to catch this error, and redirect to home/index.
How can i do this ?
EDIT: Sorry I read over the Cake 2.0
Take a look at this http://book.cakephp.org/2.0/en/development/exceptions.html#using-appcontroller-apperror
Try the manual manual
class AppError extends ErrorHandler {
function missingAction($parameters) {
$this->controller->redirect('/');
}
}
Error.php contains functions that handle cakePHP errors, you just override them
You could take the 404 page template and add a HTML redirect there.
The file to modify would be:
app/views/errors/missing_controller.ctp
UPDATE:
My bad, if it's missing an action then update:
app/views/errors/missing_action.ctp

How can I redirect a 404 Error in a custom 404 page using Codeigniter?

Kind sirs,
I'm using Codeigniter to build a blog. I might need a way to redirect a 404 error into a custom 404 page. Just like what Abduzeedo.com's 404 page. Is it possible to control this by using routes? Or should i use controllers to direct it to another view? Thanks very much!
there is another way which I use: by overriding Exception core class of Codeigniter. Firstly make sure your config file(system/application/config/config.php) subclass prefix is as following
$config['subclass_prefix'] = 'MY_';
Then make a file named MY_Exceptions.php in system/application/libraries. Then override the function show_404() function here as follows.
class MY_Exceptions extends CI_Exceptions{
function MY_Exceptions(){
parent::CI_Exceptions();
}
function show_404($page=''){
$this->config =& get_config();
$base_url = $this->config['base_url'];
$_SESSION['error_message'] = 'Error message';
header("location: ".$base_url.'error.html');
exit;
}
}
Now Error controller will be your error page, where the page will be redirected for 404 error.
Custom 404 page is create by using the following 3 steps,
Step 1: First open routes.php in application/config and set a custom controller name,
$route['404_override'] = 'my404'; //my404 is class name.
Step 2: Create a new controller and write the following code in it. The code is very easy to understand. So I am not going to explain it here,
<?php
class my404 extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->output->set_status_header('404');
$data['content'] = 'error_404'; // View name
$this->load->view('index',$data);//loading in my template
}
}
?>
Step 3: Create a view file with name 'error_404.php' with your custom message.
You don't need to create any controller or modify the code, rather than modify one view file. Just placed your 404 page HTML into the application/views/errors/html/error_404.php file.
If you want to use base_url() or any other CodeIgniter functions, initialize CI_Controller class like the below code.
<?php
$ci = new CI_Controller();
$ci =& get_instance();
$ci->load->helper('url');
?>
For a simple solution, go to your "error_404.php" file in "application/errors/" directory and put this code at the beginning of the file:
header("Location:".base_url());
It'll redirect your 404 page to home page.
Simple Solution.
Create your custom error or Page not found page within view.
Create a controller for error page. Within index function load the view of error page that you already created in previous step.
Now, Go to your application/config/routes.php
you should find $route['404_override'] = '';
Its the '' mean its calling the default error page.
Now place your controller name for error page .
It will work.
Suppose my Controller for error page is 'error'. and view page is 'notfound' .
So, code for Error.php controller will be:
<?php
class Error extends CI_Controller
{
function index()
{
$this->load->view('notfound');
}
}
Now, I replaced $route['404_override'] = ''; to $route['404_override'] = 'error'; in
application/config/routes.php.
Well you want to show your custom 404page when page not found in your website you just replace your custom file on core file which is located in application/error/error_404.php just replace your file here and you are good to go else where you can follow other method by using routes and custom controller for you custom 404 page. But the shortest and easiest way is replacing the core file with custom 404error page file
First open routes.php in the application/config folder and set a custom controller name.
$route['404_override'] = 'custom404'; //custom404 is class name.
Create a new controller and write the following code in it. The code is very easy to understand. So I am not going to explain it here.
<?php
class custom404 extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->output->set_status_header('404');
$data['content'] = 'error_404'; // View name
$this->load->view('index',$data);//loading in my template
}
}
?>
Create a view file with name 'error_404.php' with your custom message.
That is all you need to do and will be having your custom 404 page now.
No need to define any complexity.
The process is very simple.
First, go to your application->config->routes.php file and change this with your controller's function, where you simply load the header, footer, and 404.php page.
$route['404_override'] = 'welcome/_404';
Then come to your controller's page
function _404(){
$this->load->view("header");
$this->load->view("404");
$this->load->view("footer");
}
The same question is also available here
Display a view for 404 error in CodeIgniter
A more simple solution:
Just edit /application/views/error_404.php with your custom 404 page :)

Categories