I am new to codeIgnitor and keep getting the error 404, please advise where am I going wrong, below is my structure and pages.
database name: stoma_store_suppliers ,
Database fields: supplierid, supplier_name, supplier_phone
Models Page:_____________suppliers.php
<?php
Class Suppliers extends CI_Model
{
public function get_suppliers($supplierid) {
if($supplierid != FALSE) {
$query = $this->db->get_where('store_suppliers', array('supplierid' =>$supplierid));
return $query->row_array();
}
else {
return FALSE;
}
}
}
?>
Controllers Page__________
suppliers.php
<?php if (!defined('BASEPATH'))exit('No direct script access allowed');
class Suppliers extends CI_Controller {
public function show($supplierid) {
$this->load->model('suppliers');
$store_suppliers = $this->suppliers->get_suppliers($supplierid);
$data['supplier_name'] = $suppliers['supplier_name'];
$data['supplier_phone'] = $suppliers['supplier_phone'];
$this->load->view('index', $data);
}
}
?>
Views Page:
index.php
<?php print $supplier_name; ?>
<?php print $supplier_phone; ?>
Required things to access any page of codeigniter are:
First letter of controller file must be capital like Suppliers.php.
The first letter of the class definition must match the filename, e.g. for Suppliers.php it would be class Suppliers extends CI_Controller.
If a database is to be used, then the correct connection details must be set in the file config/database.php.
Below are the steps to access the any page created in the codeigniter.
Write your site domain followed by index.php, e.g. http://mysitedomain.com/index.php/suppliers
To remove the need for index.php in the URL add an .htaccess file at the root folder. Details here. In that case the URL will be
http://mysitedomain.com/. Now, domain name will get followed by controller name and the function to be accessed, e.g.
http://mysitedomain.com/suppliers/show
To pass arguments to a controller using the URL add them after the controller/function segments, e.g. http://mysitedomain.com/user/show/dede
If a controller has an index function - public function index(){ - it can be accessed two ways:
A) http://mysitedomain.com/suppliers/index
B) http://mysitedomain.com/suppliers
If /function/argument URI segments are not provided after controller name, codeigniter will call index() by default.
Related
I am new to CodeIgniter MVC. My home view is loaded correctly. When i replace home in index() with aboutus it is working, but when i call aboutus function then it is showing 404 file not found error. Login is also working correctly. I am not getting what is wrong. My view folder contains aboutus, home and login files.
public function index()
{
$this->load->view("home");
}
function login()
{
$this->load->view("login");
}
function aboutus()
{
$this->load->view("aboutus");
}
//Here the html code
<li>Login</li>
<li><a href="<?php echo base_url();?>index.php/aboutus" >About Us</a></li>
How to load default controller
In config/routes.php
$route['default_controller'] = "controller_name; //this load index() in provided controller
$route['default_controller'] = "controller_name/method_name"; //this load method which you created inside provided controller(ex: main/about_us)
How to create controller
Path - application/controllers/
File name - main.php
inside main.php
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Main extends CI_Controller {
public function index()
{
$this->load->view("home");
}
function login()
{
$this->load->view("login");
}
function aboutus()
{
$this->load->view("aboutus");
}
}
How to create view
Path - `application/view/`
File name - `home.php`
File name - `login.php`
File name - `aboutus.php`
How to use Link
Home
Login
aboutus
How to use base_url()
in config/autoload.php
$autoload['helper'] = array('url');
in config/config.php
$config['base_url'] = '';
Change your html like this
home
about us
You need to add route to your new function aboutus() in routes.php
You can find routes.php in "application/config/".
suppose your controller name is 'Client_home'
Then,
eg : $route['default_controller'] = 'Client_home';
This is the reason why aboutus is working when you replace home in index() with aboutus . The index() method will be called by default, if you are not specifying which function you want to initiate.
For the aboutus() method / function, the route will be like this :
eg : $route['aboutus'] = "Client_home/aboutus";
Synatx:
$route['url'] = "controllername/method or function name"
Example for this question. Hope this help you:
http://localhost/ciexample/index.php/your_controller/your_function
i would like to know the controller name and also would like to know where u have change its configuration , if yes than which config .
use this in address bar
"localhost/folder_name_of_the_project/index/controller_name"
I have 2 controllers in application/controllers
Welcome.php
pages.php
I am accessing welcome.php through this url
http://opunletter.com/index.php/welcome/
But while accessing http://opunletter.com/index.php/pages/
I am getting following error
404 Page Not Found
The page you requested was not found.
I am Not able to figure the error. Plz help !
class Pages extends Controller {
function search($search_terms = '')
{
// If the form has been submitted, rewrite the URL so that the search
// terms can be passed as a parameter to the action. Note that there
// are some issues with certain characters here.
if ($this->input->post('q'))
{
redirect('/pages/search/' . $this->input->post('q'));
}
if ($search_terms)
{
// Load the model and perform the search
$this->load->model('page_model');
$results = $this->page_model->search($search_terms);
}
// Render the view, passing it the necessary data
$this->load->view('search_results', array(
'search_terms' => $search_terms,
'results' => #$results
));
}
}
Try with extends CI_Controller and construct() like following:
class Pages extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function search($search_terms = '')
{
...
}
}
And you should use controller name Pages.php (capital first letter) instead of pages.php in CI3.
So I have this setup:
ARTISTAS
But when I click on that link, it takes me to http://localhost/Universal%20Music/Universal/artistas/index which says 404, like if there's nothing there but I've already created the controller with that name loading some views in it. Am I missing something here?
EDIT
My config.php has:
$config['base_url'] = 'http://localhost/Universal/Universal';
I stop using spaces in the names of the folders and now the path is:
C:\Users\Horacio\Documents\Projects\Universal\Universal
The controller file has the same name of the class I need and the code inside is:
<?php
class Artistas extends CI_Controller {
function __construct() {
parent::__construct();
}
public function index()
{
$this->load->view('header');
$this->load->view('main-index');
}
}
I just started working with CodeIgniter and I am having some trouble with the segment-based urls. I understand how to call them doing $variable = $this->uri->segment(2); but whenever I go to the url, I am getting a 404. Is there something I need to do for URI routing?
For example, I am trying to go to localhost/ci/index.php/games/1000 (where 1000 would be a game ID), but I am getting a 404. localhost/ci/index.php/games/ works fine.
In order for that to work you would need to have a controller called games.php with this content
class Games extends CI_Controller
{
public function index($id)
{
echo $id;
}
}
Unless you do something like this
class Games extends CI_Controller
{
public function index()
{
echo 'this is index';
}
public function game($id)
{
echo $id;
}
}
and add this to your routes.php
$route['game/(:any)'] = "games/game/$1";
By default the 2nd segment of the URI is a method (function) within the controller which CI automatically calls.
So in your case you are actually attempting to call a function named 1000() within the games controller, which doesn't exist and therefore results in a 404.
Instead what I think you want to do is call the index() function, and pass the variable 1000 to it.
So if you were to go to localhost/ci/index.php/games/index/1000 you shouldn't get a 404 anymore, however your URI segment will now be wrong to get the variable 1000.
Here is a working example of the controller with the corrected URI segment:
class Games extends CI_Controller
{
// good habit to call __construct in order to load
// any models, libraries, or helpers used throughout this controller
public function __construct()
{
parent::__construct();
}
// default controller
public function index()
{
// this should display 1000
echo $this->uri->segment(3);
}
}
In codeigniter, as you know, a page of the form: /class/function/ID, where class is the controller name, function is the method within the controller, and ID is the parameter to pass to that method.
The typical usage would be (for a book site for example) to pass the book id to the function which would then query the database for appropriate book. My problem is this: I was messing around and randomly (in the url string) typed in an ID that is not present in the database (with normal point and click browsing this would never happen) and I get database errors due to the residual queries I attempt to perform using a non-existent ID.
I have written code to check if there are any rows returned before attempting to use the ID, but if the ID is non-existent I would like the user to get a 404 error page rather than a blank page or something (since this seems like proper functionality). This would need to be a true 404 page (not simply loading a view that looks like a 404 page) so as not to screw with search engines. Okay - so my question is this: within normal program logic flow (as described above) how can I force a 404 error using codeigniter? Thanks.
Update: code igniter has a show_404('page') function but I don't think this will generate a true HTTP 404 error...
show_404() actually sends the proper headers for a search engine to register it as a 404 page (it sends 404 status).
Use a Firefox addon to check the headers received when calling show_404(). You will see it sends the proper HTTP Status Code.
Check the default application/errors/error_404.php. The first line is:
<?php header("HTTP/1.1 404 Not Found"); ?>
That line sets the HTTP Status as 404. It's all you need for the search engine to read your page as a 404 page.
$this->output->set_status_header('404');
to generate 404 headers.
If you want a custom error page you can do the following thing.In your Libraries create a file name MY_Exceptions and extend it with CI_Exceptions.And then override the show_404() function.In this function you can now create an instance of your Controller class using &get_instance() function.And using this instance you can load your custom 404 Error page.
class MY_Exceptions extends CI_Exceptions {
public function __construct(){
parent::__construct();
}
function show_404($page = ''){ // error page logic
header("HTTP/1.1 404 Not Found");
$heading = "404 Page Not Found";
$message = "The page you requested was not found ";
$CI =& get_instance();
$CI->load->view('/*Name of you custom 404 error page.*/');
}
Only follows these steps:
Step 1
Update your application/config/routes.php file
$route['404_override'] = 'error/error_404';
Step 2
Create your own controller in controllers folder
ex. error.php
<?php
class Error extends CI_Controller
{
function error_404()
{
$data["heading"] = "404 Page Not Found";
$data["message"] = "The page you requested was not found ";
$this->load->view('error',$data);
}
}
?>
Step 3
Create your view in views folder
ex. error.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title><?php echo $heading;?></title>
</head>
<body>
<?php echo $message;?>
</body>
</html>
I had the same problem with you and I found a complete solution for this in CodeIgniter 3. Here I would like to share step by step how to solve it. Of course, we need to support a custom 404 page to satisfy SEO requirement.
Show 404 page for URLs which do not match the schema in routes
Add a new Error controller in application/controllers to support a custom 404 page.
class ErrorController extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->output->set_status_header('404');
return $this->load->view('errors/error_404');
}
}
Add a new custom view error_404.php for 404 page in application/views/errors
<div>
<p>We are so sorry. The page you requested could not be found.</p>
</div>
Declare 404_overide in config/routes.php
$route['404_override'] = 'ErrorController';
Show 404 page for URLs which match the schema in routes but point to non-existing resource.
Set subclass_prefix in config/config.
$config['subclass_prefix'] = 'MY_';
Define your custom Exceptions class in application/core
class MY_Exceptions extends CI_Exceptions {
public function __construct() {
parent::__construct();
}
function show_404($page = '', $log_error = TRUE) {
$CI = &get_instance();
$CI->output->set_status_header('404');
$CI->load->view('errors/error_404');
echo $CI->output->get_output();
exit;
}
}
Call show_404() wherever you want. Here I created my custom supper model class in application/models and check query results there. Other models will extends the supper model and show 404 page if they could not found a resource.
abstract class MY_Model extends CI_Model
{
protected $table = 'table_name';
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function find($id)
{
$result = $this->db->get_where($this->table, ['id' => $id]);
$data = $result->row_object();
if (!$data) {
show_404();
}
return $data;
}
}
Yes show_404() WILL send out a 404 but it looks like hell. There have been a few hacks suggested here, but why hack when you can use built in features?
Upgrade to CI 2.0 and you'll be able to use the amazing:
$route['404_override'] = 'errors/error_404';
Then you can have a general errors controller without having to worry about trying to load views, libraries and helpers WY too early in the CI instance to function properly.
try using this
set_status_header(404);
Create controller in your application/controllers folder.
class Error extends Controller
{
function error_404()
{
$this->load->view('error');
}
}
Then in your application/library extend the Router class by creating application/libraries/MY_Router.php
class MY_Router extends CI_Router
{
private $error_controller = 'error';
private $error_method_404 = 'error_404';
function MY_Router()
{
parent::CI_Router();
}
// this is just the same method as in Router.php, with show_404() replaced by $this->error_404();
function _validate_request($segments)
{
// Does the requested controller exist in the root folder?
if(file_exists(APPPATH.'controllers/'.$segments[0].EXT))
{
return $segments;
}
// Is the controller in a sub-folder?
if(is_dir(APPPATH.'controllers/'.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
if(count($segments) > 0)
{
// Does the requested controller exist in the sub-folder?
if(!file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
{
return $this->error_404();
}
}
else
{
$this->set_class($this->default_controller);
$this->set_method('index');
// Does the default controller exist in the sub-folder?
if(!file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = '';
return array();
}
}
return $segments;
}
// Can't find the requested controller...
return $this->error_404();
}
function error_404()
{
$segments = array();
$segments[] = $this->error_controller;
$segments[] = $this->error_method_404;
return $segments;
}
function fetch_class()
{
// if method doesn't exist in class, change
// class to error and method to error_404
$this->check_method();
return $this->class;
}
function check_method()
{
$class = $this->class;
if (class_exists($class))
{
if ($class == 'doc')
{
return;
}
if (! in_array('_remap', array_map('strtolower', get_class_methods($class)))
&& ! in_array(strtolower($this->method), array_map('strtolower', get_class_methods($class))))
{
$this->class = $this->error_controller;
$this->method = $this->error_method_404;
include(APPPATH.'controllers/'.$this->fetch_directory().$this->error_controller.EXT);
}
}
}
}
If the page does not exist, it will be routed to error controller