Takaapo Page
Takaapo Page

Reputation: 49

Error while redirecting in Codeigniter

I want to have my post title in my url, separated with dashes and I do that with this answer and this is my code :

 public function post($post_id, $slug = ''){
    $data['post'] = $this->posts_model->get_post_by_id($post_id);
    if ($slug) {
        $get_title = $data['post']->post_slug;
        redirect('blog/' . $post_id . '/' . $get_title);
    }
    $this->load->view('pages/show-post', $data);
}

and these are my routes :

$route['blog/(:num)'] = 'blog/post/$1';
$route['blog/(:num)/(:any)'] = 'blog/post/$1/$2';

Problem : when I load my example.com/blog/1 everything is ok, but when I load example.com/blog/1/anything my code redirect me to example.com/blog/1/my-slug-from-database successfully but page load failed and firefox show me The page isn't redirecting properly error.

How can I solve this problem ? Is there any problem in my code ?

Thanks for your helps !

Upvotes: 0

Views: 296

Answers (2)

jtheman
jtheman

Reputation: 7491

I guess what you really want is to prevent the url to show without a slug to improve the link quality and for SEO purposes. Why not just change the code to only redirect when NOT a slug is provided, IE:

Change the line:

if ($slug) {

to

if (!$slug) {

Then the code won't get trapped in a redirect-loop (as suggested by Ron Dadon) and the posts will always show with the slug in the URL.

I cannot guess any other reason for linking to a post as you do in your question example.com/blog/1/anything - why would you want to put anything in the URL? This could only be the slug, right?

Upvotes: 1

Ron Dadon
Ron Dadon

Reputation: 2706

You access example.com/blog/1/anything, and redirected to example.com/blog/1/my-slug-from-database. Now in CI, you get to the same function, and then because $slug is true, you are redirected again to example.com/blog/1/my-slug-from-database. You have a redirection loop - that is what causing the The page isn't redirecting properly error.

You need a way to stop the redirection - as far as I can see from your code, check if $slug === $get_title, and if so - don't redirect. But it's really hard to know what to do, because I'm not sure what you attempt to do.

Upvotes: 2

Related Questions