SEO url gives 404-error in CodeIgniter - php

I am pretty new to codeigniter. I do know php.
How can I accomplish to load the right view?
My url: /blog/this-is-my-title
I’ve told the controller something like
if end($this->uri->segment_array()) does exist in DB then load this data into some view.
I am getting an 404-error everytime I access /blog/whatever
What am i seeing wrong?

unless you're using routing, the url /blog/this-is-my-title will always 404 because CI is looking for a method called this-is-my-title, which of course doesn't exist.
A quick fix is to put your post display code in to another function and edit the URLs to access posts from say: /blog/view/the-post-title
A route like:
$route['blog/(:any)'] = "blog/view/$1";
may also achieve what you want, if you want the URI to stay as just `/blog/this-is-my-title'

The may be more possibilities:
The most common - mod_rewrite is not active
.htaccess is not configured correctly (if u didn't edited it try /blog/index.php/whatever)
The controller does not exist or is placed in the wrong folder
Suggestion: if you only need to change data use another view in the same controller
if (something)
{
$this->load->view('whatever');
}
else
{
$this->load->view('somethingelse');
}
If none of those works post a sample of code and configuration of .htaccess and I'll take a look.

The best way to solve this problem is to remap the controller. That way, you can still use the same controller to do other things too.
No routing required!
enter code here
<?php
class Blog extends Controller {
function __construct()
{
parent::__construct();
}
public function _remap($method, $params = array())
{
if (method_exists($this, $method))
{
$this->$method();
}
else
{
$this->show_post();
}
}
function index()
{
// show blog front page
echo 'blog';
}
function edit()
{
// edit blog entry
}
function category()
{
// list entries for this category
}
function show_post()
{
$url_title = $this->uri->segment(2);
// get the post by the url_title
if(NO RESULTS)
{
show_404();
}
else
{
// show post
}
}
}
?>

Related

Error 404 despite that page exists Codeigniter

I have something like website.com/profile/nameofuser that is working.
But if I have website.com/profile/_nameofuser I get 404 error also website.com/profile/nameofuser_ or website.com/profile/nameof_user is working. It's not something related to accepted characters, but what's the problem?
class Profile extends CI_Controller {
public function __construct()
{
parent:: __construct();
$this->load->model('Profile_model');
$this->load->helper(array('url', 'form', 'htmlpurifier'));
}
public function index() {
$this->load->library('form_validation');
if(getUserData($this->uri->segment(2), "ID") < 0) {
$this->session->set_flashdata('error', 'Profil inexistent.');
redirect(base_url());
}
if (!is_cache_valid(md5('profile' . $this->uri->segment(2) . ''), 300)){
$this->db->cache_delete('profile', $this->uri->segment(2));
}
if(getUserData($this->uri->segment(2), "ID") > 0) {
/* some mysql queries.. */
}
$data["main_content"] = 'profile/profile_view';
$this->load->view('includes/template.php', $data);
} else {
$this->session->set_flashdata('error', 'Profil inexistent.');
redirect(base_url());
}
}
function _remap($method,$args)
{
if (method_exists($this, $method))
{
$this->$method($args);
}
else
{
$this->index($method,$args);
}
}
}
Here is my profile controller. I really don't know what's the problem. If I enter an invalid profile redirects with error flashdata so ti's ok. Maybe it's a remap problem?
1) Check the fie format in your view file.. if it is html file that mean you cannot call it without its format
for example
if your file is php format have name home-view.php
you can call it as
$this->load->view('home-view');
but if it is html file then the name in home-view.html
so you have to call it with its exstention as
$this->load->view('home-view.html');
your call to /profile/nameofuser is missing a fundamental from the MVC architecture.
You need to call a controller/method combination (in CI, your basic url is domain.com/controller/method)...
since you don't have a specific method for each user within the profile controller, which is actually a good thing, you need a method within the controller that handles your users. You already have it, it's called index
If you point your URL to /profile/index/nameofuser and change $this->uri->segment(2) to $this->uri->segment(3) you should get it to work
give it a try and let me know

Passing value through url

I am trying to send a url from view page to controller but it does not seem to work the way i am thinking.
View Page
Product
User
I want to get "tbl_product"
Controller admin
<?php
class Admin extends CI_Controller {
public function test() {
echo $this->uri->segment(4);
}
}
?>
but if the segment(4) is changed to segment(3), it shows up with displaying "product" in the screen
your controller function should have arguments for your url segments
for example:
public function test($product = 'product', $tbl = 'tbl_product') {
echo $tbl // contains the string tbl_product
}
Since you said your routes look like this:
$route['default_controller'] = "admin";
$route['404_override'] = ''
and your URL is like this:
<?= base_url() ?>admin/test/product/tbl_product
Then if your base_url() is localhost/my_app, your URL will be read as this:
http://localhost/my_app/admin/test/product/tbl_product
http://localhost/my_app/CONTROLLER/METHOD/PARAMETER/PARAMETER
So in your controller, you can do this:
class Admin extends CI_Controller {
public function test($product = NULL, $tbl_product = NULL) {
echo $product;
echo $tbl_product;
}
}
It's strange to use codeigniter for this purpose, because codeigniter uses as default the url format bellow.
"[base_url]/[controller]/[method]"
I think it will be better and more easy to just pass the values you want as get parameters and make some httaccess rules to make your url more readable for the user and robots. That said you can do that:
Product
<?php
class Admin extends CI_Controller {
public function test() {
echo $this->input->get('product');
//should output 'tbl_product'
}
}
?>
If you prefer to use uri instead u should route your uri's so it will be like.
In your routes file you probably I'll need something like this.
$route['product/(:any)'] = "Admin/test";
This way you will probably access the uri segments correctly.
Thank you so much for going through.
$this->uri->segment(4); // is now working :S
its not working properly after all I made changes to routes.php and came back to default again. I seriously have no idea what the reason behind not displaying the result before.

CI routing issue

i am currently learning CI and i have come to an issue that i cant seem to solve.
i set up my wamp server in a drive and inside the www(root) folder i have extracted the codeigniter files.
![example][1][1]: http://i.stack.imgur.com/7RKqG.png
then I created my php files for view/model and controller and set the default route in the config/routes.php
so now when I go to my browser and type localhost I get the post.php displayed without anyissue.
but I am unable to access any of the views from here. for example i have a new_post.php view and when i type in the address bar localhost/new_post.php i get a "Not Found
The requested URL /new_post.php was not found on this server." error.
what am i doing wrong? below i have posted the code which i have written in the post.php controller along with a image of the file structure/names i have.
posts.php - controller
<?php
class Posts extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('post'); //loads the post model u created in the models folder
}
function index() //goes to this function 1st when u access the controller
{
$data['posts']=$this->post->get_posts(); // load all the data from the get_posts function in post model to the data array posts
$this->load->view('post_index', $data); //loads the view
}
function post($postID)
{
$data['post']=$this->post->get_post($postID);
$this->load->view('post', $data);
}
function new_post()
{
if($_POST)
{
$data=array(
'title'=> $_POST['title'],
'post'=> $_POST['post'],
'active' =>1
);
$this->post->insert_post($data);
redirect(base_url(). 'posts/');
}
else
{
$this->load->view('new_post');
}
}
function editpost($postID)
{
$data['success']=0;
if($_POST)
{
$data_post=array(
'title'=> $_POST['title'],
'post'=> $_POST['post'],
'active' => 1
);
$this->post->update_post($postID,$data);
$data['success'] =1;
}
$data['post']=$this->post->get_post($postID);
$this->load->view('edit_post',$data);
}
function deletepost($postID)
{
$this->post->delete_post($postID);
redirect(base_url(). 'posts/');
}
}
![structure][1] [1]: http://i.stack.imgur.com/SnsbW.png
In CodeIgniter you have to use controller to get access to his function
you are saying "when i type in the address bar localhost/new_post.php i get a Not Found" because you try to direct access its function name you have to use example.com/controllername/functionname like this
http://localhost/posts/new_post
for more information check codeignier url
https://ellislab.com/codeigniter/user-guide/general/urls.html
if you not removed index.php using .htaccess then you have to use your url like this
http://localhost/index.php/posts/new_post
In CodeIgniter, everything runs through the main "index.php" file, in your root directory.
So, you would access your new post page, like this;
http://localhost/index.php/posts/new_post
Have a read through the CodeIgniter user guide, it will answer any problem you have.
https://ellislab.com/codeigniter/user-guide/

How pass a variable during ajax rendering in cakephp 2.x

I want to pass a variable to my ajax rendering function.Something like this
$this->render('tempcomment/'.$id, 'ajax');
and my tempcomment action is
public function tempcomment($id) {
$commentdata = $this->Post->Comment->findByPostid($pid);
$this->set('commentdata', $commentdata);
}
but rendering is not working.
See below to start with:
public function tempcomment($id) {
// ^ ------ ...
$commentdata = $this->Post->Comment->findByPostid($pid);
// ^--- this is different!
$this->set('commentdata', $commentdata);
}
render is used just to decide what view to use in your controller action to render the action. It does not call the action itself
so if you have a code like this
public function test() {
$this->set('foo', 12345);
$this->render('tempcomment', 'ajax');
}
you are just saying that you want to use the tempcomment view to render the test action but you are not telling cake to actually execute the tempcomment action.
so if you want to call the action you have to do by yourself
$this->tempcomment($id);
$this->render('tempcomment/'.$id, 'ajax');
let me tell you that I don't see any reason to do this and I think that probably there are other ways to do what you are trying to achieve. But I assume you know what you are doing
Try this, its another work around of what you want to achieve:
public functionc ajax_tempcomment($id){ //just access this action
$this->redirect('tempcomment/'.$id);
$this->layout = "ajax";
}
public function tempcomment($id) {
$commentdata = $this->Post->Comment->findByPostid($pid);
$this->set('commentdata', $commentdata);
}

Is a POST controller suitable in a php mvc?

I am creating a custom MVC style framework from scratch and am at the point where I need to implement the code to control what happens on POST.
At the moment I have a main index.php which acts as a controller and passes data to other controllers such as:
profilecontroller.class.php
forumcontroller.class.php
At the moment I see two options as to where the POST controllers can go ..
First Approach
Firstly for site wide posts such as login that can occur on any page I would use something like this in the very first index.php to redirect all POST to a specific POST controller that then sends the data to a model to be processed:
if($_POST)
//post controller, works on specific form id's
Alternate Approach
The other option I see would be to build the POST identifier into the model construction sections but I don't think this would be very manageable/wise as they'd always be checked and resulting in more loaded code?
Are there any good/simple examples out there?
I'm creating my mvc to be as light as possible so that's my reason for going from scratch.
In a RESTful setup, you would normally have a controller for an object, say news, and then actions such as add, edit, delete etc.
Within your actions, you should then assert what HTTP method should be used to access the method, if one should be. For example:
<?php
class NewsController extends AbstractController {
public function save() {
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
header('HTTP/1.1 405 Method Not Allowed');
die('Please use POST.');
}
// carry on knowing we're working with a POST request
}
}
Creating a separate controller for POST requests would, as you say, quickly becoming unruly and unmanageable.
If you're looking for a way of handling requests for different HTTP methods within different controller actions, then maybe check out ToroPHP. It's a lightweight (single file) router, where you map a request to a class that's referred to as a handler, and then that handler has methods for different HTTP methods. A quick example:
<?php
require 'lib/torophp/toro.php';
require 'classes/handlers/HomeHandler.php';
$toro = new ToroApplication(array(
array('/', 'HomeHandler')
));
$toro->serve();
And then your HomeHandler would look as follows:
<?php
class HomeHandler {
public function get() {
echo 'Hello, world!';
}
public function post() {
echo 'Try performing a GET request for the home page, buddy.';
}
// and so on...
}
Hope that helps.
This is my default Controller :
<?php
Class Controller_Home{
public $Registery = null;
final public function __construct($Registery){ $this->Registery = $Registery; }
final public function Init($Method=null){
# Quelle action on fait ?
if($Method){
$Split = explode('_', $Method);
$MethodName = 'Action';
foreach($Split as $Splitted){
$MethodName.= '_'.ucfirst($Splitted);
}
if(method_exists($this, $MethodName)){
$this->$MethodName();
} else {
echo '404';
die;
}
} else {
$this->Action_Default();
}
}
final public function Action_Default(){
$this->Registery->Import('Library.Account');
var_dump($this->Registery->Account);
echo 'Default Home';
}
}
As you can see, once you are in Action_Default, you can do whatever you want based on $_GET, $_POST, whatever you want ...
So with this code :
website.com/home/bob/ will use function Action_Bob inside the controller Home (Home::Action_Bob) ... if you see $_POST just put inside Action_Bob this
public function Action_Bob(){
if($_POST){
$this->Action_Bob_Post();
}
// continue
}

Categories