Codeigniter .htaccess rewriting for database - php

I am having difficulties with Codeigniter. I am trying to get data from a MySQL data by passing the record ID as part of the URL
The URL is to be
localhost/site_folder/page/page_title/2
In the above URL, page is the name of the controller and 2 is the primary ID of the record in the database (this could be any number from 1 to 9999).
My controller includes this:
public function index()
{
$this->load->helper('url');
$this->load->model('pages_model');
$id = $this->uri->segment(3,1);
if (empty($id))
{
show_404();
}
$data['page'] = $this->pages_model->get_page($id);
$this->load->view('page',$data);
}
My .htaccess contains this
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
When I enter localhost/site_folder/page/page_title/2 into the address bar, it throws a 404.
Yet, when I enter localhost/site_folder/page it shows the default database entry as shown in the second value of segment(3,1) above.
So, how should I change the .htaccess file for a workable rewrite?
I have tried the following, but none worked for me:
RewriteRule .* page/$0 [PT,L]
RewriteRule .* page/(*.)/$0 [PT,L]
RewriteRule .* page/(?*.)/$ [PT,L]

You can try using the _remap function as described in the CI documentation https://ellislab.com/codeigniter/user-guide/general/controllers.html
The _remap function if exists in a controller is the a function that is called before any class method, and in this function you can check params sent to the function and according to this call any method of the controller.
For your example as i assume that page_title is dynamic you can either set a regular expression to check it or as i n the following example check if the method does not exists then treat it as a page title (this means that you must be sure there can not be a page title and a method name in this controller with the same name)
public function _remap($method, $params = array())
{
if (!method_exists($this, $method))
{
// assume this is a page_title and run the index method
$this->index($method, $params);
}
else {
// means that method exists then run that method
$this->$method( $params);
}
}
Also remember that means that you should take into consideration in the index method usage of 404 header when someone just type random string that the controller will treat as a page_title.

Related

Redirect to Controller results 404 Page Not Found

I am creating a web application in Codeignitor using Laragon as my local server. When I try to "redirect" to a Controller - I get "404 Page Not Found". If I redirect to View - it works. I can access Controllers with other methods such as "Form Open".
Here is my .htaccess file:
RewriteEngine on
RewriteCond $1 !^(index\.php|assets|images|js|css|uploads|favicon.png)
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^(.*)$ index.php/$1 [L]
This is my Controller - for a test I used Redirect to a View "page-login" and a Controller "Private-area". I can access the View, but the Controller sends to 404 Page Not Found.
if($this->form_validation->run()){
$result = $this->login_model->can_login($this->input->post('user_email'), $this->input->post('user_password'));
if($result == ''){
redirect('private_area');
}
else {
$this->session->set_flashdata('message', $result);
redirect('page-login');
FYI I can access Controllers (in this example "Register") using other methods such as Form Open like this:
<?php echo form_open('register/validation'); ?>
Why do I get the 404 error?
Your redirect syntax is incorrect:
the CI function redirect() is structured like this:
redirect($uri = '', $method = 'auto', $code = NULL)
keep in mind to use a relative path like '/my_controller/my_function'
as in this example:
redirect('/login/form/');
you need to autoload/load the URL helper with: $this->load->helper('url');
the form_open() syntax is correct, you need to autoload/load the Form Helper with: $this->load->helper('form');
redirect() function
Does a “header redirect” to the URI specified. If you specify the full site URL that link will be built, but for local links simply providing the URI segments to the controller you want to direct to will create the link. The function will build the URL based on your config file values. (- source)
So, the url must be
redirect("/controller/method/parameters");
Or full url
In your code, Codeigniter will look for the index() method of private_area controller.
Thanks All!
So I think #Don'tPanic nailed it. I thought "Redirect" would point to a Controller - but it points to a Route. So I created a Route in my Routes.php file where
$route['private_area'] = 'private_area';
And everything works. Is this the correct way to do this?
Ie to define Routes in the Routes.php file...then call upon them as required using "Redirect"?

API response fetching method not called CI

I have bad english, but i hope I can explain you my situation.
I have payment controller and two methods.
class payment extends MX_Controller{
public function __construct(){
parent::__construct();
$this->load->model(get_class($this) . "_model", "model");
}
public function pay(){
//Gets form data and sends to payment service
}
public function check(){
//Gets response from payment service and acts according payment
//status
}
}
First sends data to payment service and second have to do something according payment response scenario.
So in my payment cpanel I wrote this url "htts://my-domain.do/payment/check" for response.
The first method works successfully, it sends all needed data, but my second "check()" method does not called.
When I simply write https://my-domain/payment/check it still not working, but when I call like this https://my-domain/index.php/payment/check it works.
My .htaccess also configured.
I use CI 3. Is there any one who had the problem like this.
My .htaccess file look like
RewriteEngine On
Options +FollowSymLinks
Options -Indexes
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule . index.php [L,QSA]
And in app/config/config.php
$config['index_page'] = '';

Codeigniter subdomain routing

I'm trying to setup a blog script on a website running on the CodeIgniter framework. I want do this without making any major code changes to my existing website's code. I figured that creating a sub domain pointing to another Controller would be the cleanest method of doing this.
The steps that I took to setup my new Blog controller involved:
Creating an A record pointing to my server's ip address.
Adding new rules to CodeIgniter's routes.php file.
Here is what I came up with:
switch ($_SERVER['HTTP_HOST']) {
case 'blog.notedu.mp':
$route['default_controller'] = "blog";
$route['latest'] = "blog/latest";
break;
default:
$route['default_controller'] = "main";
break;
}
This should point blog.notedu.mp and blog.notedu.mp/latest to my blog controller.
Now here is the problem...
Accessing blog.notedu.mp or blog.notedu.mp/index.php/blog/latest works fine, however accessing blog.notedu.mp/latest takes me to a 404 page for some reason...
My .htaccess file looks like this (the default for removing index.php from the url):
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
And my Blog controller contains the following code:
class Blog extends CI_Controller {
public function _remap($method){
echo "_remap function called.\n";
echo "The method called was: ".$method;
}
public function index()
{
$this->load->helper('url');
$this->load->helper('../../global/helpers/base');
$this->load->view('blog');
}
public function latest(){
echo "latest working";
}
}
What am I missing out on or doing wrong here? I've been searching for a solution to this problem for days :(
After 4 days of trial and error, I've finally fixed this issue!
Turns out it was a .htaccess problem and the following rules fixed it:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
Thanks to everyone that read or answered this question.
Does blog.domain.co/blog/latest also show a 404?
maybe you could also take a look at the _remap() function for your default controller.
http://ellislab.com/codeigniter/user-guide/general/controllers.html#default
Basically, CodeIgniter uses the second segment of the URI to determine which function in the controller gets called. You to override this behavior through the use of the _remap() function.
Straight from the user guide,
If your controller contains a function named _remap(), it will always
get called regardless of what your URI contains. It overrides the
normal behavior in which the URI determines which function is called,
allowing you to define your own function routing rules.
public function _remap($method)
{
if ($method == 'some_method')
{
$this->$method();
}
else
{
$this->default_method();
}
}
Hope this helps.
have a "AllowOverride All" in the configuration file of the subdomain in apache?
without it "blog.notedu.mp/index.php/blog/latest" work perfectly, but "blog.notedu.mp/latest" no
$route['latest'] = "index";
means that the URL http://blog.example.com/latest will look for an index() method in an index controller.
You want
$route['latest'] = "blog/latest";
Codeigniter user guide has a clear explanation about routes here

Trouble with CodeIgniter routes, getting 404 errors

I am trying to create custom routes for my CodeIgniter site. Even the most basic routes do not work. For example I have the welcome controller mapped to "test" and it just 404's on me. I am running on MAMP with mod_rewrite enabled.
I have the index.php line in config.php empty..
$config['index_page'] = '';
Here is my .htacess file..
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php/$1 [L,QSA]
And here is my route..
$route['welcome'] = 'test';
In a route, the array key contains the URI to be matched, while the
array value contains the destination it should be re-routed to.
-- CI Documentation
Your physical controller name is welcome. So if you want a URL containing the word test in the first segment be remapped to the welcome class, you should do this:
$route['test'] = "welcome/METHOD";
Where METHOD is method of welcome class.
Note: If class/method was welcome/index, you do NOT need to append /index.
If I read this correctly, that route will try to redirect the controller 'welcome' to the controller 'test'. If you have a controller named 'test' and a function named 'index', you can route the following:
route['welcome/index'] = 'test/index';
Is that what you are trying to do?
A couple things:
Routes in CI are cascaded, they're evaluated top to bottom, and the router stops at the first match. Make sure, then, to have any custom route placed below the 2 default routes in a vanilla distribution:
$route['default_controller'] = "welcome";
$route['404_override'] = '';
// custom routes here
$route['welcome'] = "welcome/test";
If you have a controller named "welcome" (the default one), and you want to call a method named "test", you need a route like
$route['welcome'] = "welcome/test"
which will be accessible at the url http://wwww.yourdomain.com/welcome
(if no route were specified, you would have accessed it like http://www.yourdomain.com/welcome/test)
Usually, controller have an index method which is called automatically when no other method is provided. The route you've created so far isn't working because it's calling the index() method of a "test" controller, which is likely not present.
A suggestion: if you mainatain the "welcome" controller as the default one, and you want to call an url like http://www.yourdomain.com/test
You need a test() method and your route must be
$route['test'] = "welcome/test";

Codeigniter - can't hit a method in a class

This is my first CI project so forgive me.
I simply can't hit a method with an AJAX call. It keeps coming up as a 404 in Web Inspector.
I have a controller called "home.php". It's working. I can land on my home page.
Then I have this AJAX call firing on a hover event
function showDataWindow(){
// i might switch this to data attr, but for now item IDs are contained in class
var thisClass = $(this).attr('class');
var thisIDpos = thisClass.indexOf("id-")+3;
var thisID = thisClass.substr(thisIDpos, 3);
alert(thisID); // alerting correctly
$.post('getMoreInfo', { ID: thisID},
function(data) {
.. act on data
I simply can find the method I am calling - getMoreInfo. Always 404.
I have a home.php class in my controllers and its set as my default, and it works because I am landing on my home page and getting the index. But in that home controller is also my getMoreInfo function...
public function getMoreInfo()
{
$ID = $_POST['ID'];
$this->load->model('Artist_model');
$assocReturned = $this->Artist_model->get_more_info($ID);
echo json_encode($assocReturned);
}
And I feel like there is a tiny MC Hammer guarding that function. "You can't touch this". He mocks me in his little parachute pants and minuscule fade.
I think it must be how I am doing my URI in the Jquery AJAX post? I have index re-writing in my htaccess (which I am kind of foggy on exactly)
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?$1 [L]
But I have tried just about every URI permutation in that AJAX call
www.mySite.com/index.php/home/getMoreInfo
index.php/home/getMoreInfo
index.php/getMoreInfo
/home/getMoreInfo
home/getMoreInfo
/getMoreInfo
getMoreInfo
!
And none have worked.
What you have to call depends on how your router is configured.
Default call would be /home/getMoreInfo, but could be changed if you have reconfigured your router. Reference: http://codeigniter.com/user_guide/general/routing.html

Categories