Display/render/show view from controller - php

How can I show a view from a controller? Here is my code:
This is my controller.php file in /var/www/html/application/controllers/controller.php
public function __construct($controller) {
if(!this->controller) {
//show page from: /var/www/html/application/views/404.php
}
}

As far as i can understand from controller path, this is Codeigniter PHP Framework.
If so, you can load 404.php with code below:
$this->load->view('404');
Also there is a function named show_404() that trigers 404 error and loads corresponding view.
I strongly recommend you to read Codeigniter Documentation from beginning.

Related

codeigniter 3.0 custom 404 not found error page

My problem is about custom error pages after upgrading to Codeigniter 3.0.
I used to have a Errors controller which handled 404 error page of the website - on this controller I have customized some parts of page, such as if user is logged in, it was showing username on the navigation bar and etc. (yes, on 404 error page).
After upgrading to CI 3.0, I have noticed that error pages are handled in different folder, I started to migrate to this way; but the problem is I can't load any variables to this page, such as session variables or can't even use any CI's functions on these pages.
I think this pages are supposed to be only HTML pages, but is there any way to load variables to these error pages?
You need to set in application/config/routes.php the following route
$route['404_override'] = 'my404';
Then you need to create a new controller in your controllers directory (application/controllers/)
<?php
class My404 extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->output->set_status_header('404');
$this->load->view('err404');//loading in custom error view
}
}
And create an err404 view. Thats all!
Refer :Reserved Routes
It's not working in codeigniter 3, I overwrite the default view (application/views/errors/html/error_404.php) and added my custom view, now show_404() is working fine.
that is working good, but if redirect to an error, for example 404 with function show_404, your controller wont load your view, for a real 404 in the show_404 method, you have to go to the core of codeigniter and touch it.
\system\core\Common.php
this is an example of code:
function show_404(){
$ci = get_instance();
$ci->output->set_status_header(404);
$ci->load->view('errors/error404_view');
echo $ci->output->get_output();
exit(4);
}
In Codeigniter 3, instead of calling show_404(), I just redirected to the custom error controller function.
e.g. for the above scenario
if (404 condition...) {
redirect("my404");
}
To work with the show_404 () function, you don't need to access the CI core and change how they are talking.
Just make the standard 404 view load your 404 view with $CI->load->view(...)
this will keep the original 404 code of the request and will not make an unnecessary redirect or core changes.
$CI =& get_instance();
$CI->load->view('error-404');

Cannot get FuelPHP action to run

I'm new to FuelPHP and I did a little coding with it! What I did was create a simple controller and created two methods. One for action_index() and the other is action_add().
the code is given below. Views are already in the app\views\ folder.
class Controller_Student extends Controller
{
public function action_index()
{
return Response::forge(View::forge('index'));
}
public function action_add()
{
return Response::forge(View::forge('select'));
}
}
I've set the root to this controller class. When I run the application the index works fine and loads the directed view. But when I give the following URL
http://localhost/project/public/add/
the method doesn't get called! A 404 error is give saying
You can see this page because the URL you are accessing cannot be found.
What Am I doing wrong here. I've gone through every documentation, tutorial I find but I shouldn't get this type of an error. Please help me.
Below is the routing file code :
return array(
'_root_' => 'student', // The default route
'_404_' => 'welcome/404', // The main 404 route
);
You've set the root to student controller, but that doesn't mean all traffic goes through that controller. Try visiting:
http://localhost/project/public/student/add/

Unable to display a form - Codeigniter

I was trying out the tutorial on this link to create a form :
http://codeigniter.com/user_guide/libraries/form_validation.html
But when I type in the url(after creating the files of form.php, formsuccess.php and myform.php) localhost/codeigniter/index.php/form, I get the error of 404 Page Not Found.
I am new to Codeigniter. Can someone help me figure out the error ? Thanks and Regards.
Codeigniter is an MVC framework so url hierarchy is processed a little different.
Can you access localhost/codeigniter/index.php?
No: Do you have the correct .htaccess files in place?
Yes: In your controller folder, do you have a file named Form.php with the following code:
class Form extends CI_Controller {
function index() {
}
}

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>

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