How to create dynamic URL in Codeigniter?.
I've following table which stores basic article details:
1. ID
2. Article Title
3. Content
4. Tags
5. Status
6. Create Time
7. Update Time
8. Author ID
9. Status
Now I want to know how to create dynamic URL, which holds Page ID & Article Title.
For example http://www.domain.com/1/hello-codeigniter
Now above sample URL, I am generating URL with ID & Article Title.
- ID for retrieve article content (When user clicks to article, get content from ID).
- Article Title for Safe URL.
but I don't want to show ID from URL and still get content when user redirect to detail page.
HERE IS MY CODE:
View: home_page.php
<div id="body">
<?php for($i=0; $i<count($blogPosts); $i++): ?>
<div class="post-preview">
<?php
$postID = $blogPosts[$i]->id; // Get post ID
$postTitle = $blogPosts[$i]->title; // Get post Title
$urlTitle = preg_replace('/\s+/', '-', $postTitle); // Replacing space with dash
echo anchor('content/'.$postID.'/'.$urlTitle, $postTitle, array('title' => $postTitle)); // Get post URL
echo "<br />";
?>
</div>
<hr>
<?php endfor; ?>
</div>
Controller: home.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
public function index() {
$this->load->model("HomeModel"); // Load HomeModel
$data['blogPosts'] = $this->HomeModel->blogPosts(); // Get blog posts data from blogPostsData function
$this->load->view("home_page", $data);
}
}
Model: HomeModel.php
class HomeModel extends CI_Model {
public function blogPosts() {
$this->db->select('*');
$this->db->from('blog_posts');
$query = $this->db->get();
return $query->result();
}
}
After coding When I hover to anchor link I am getting this URL:
http://localhost/codeIgniter/index.php/content/1/My-First-Blog-Post!
How to hide index.php, content & 1 from URL.
One more thing is that When I clicked to link I am getting this error message:
An Error Was Encountered
The URI you submitted has disallowed characters.
Any help would be appreciated!!!
You can use
routesfor this purposeTo remove
index.phpuse.htaccesswith following codeand in
config.phpTo remove content from url remove content from anchor in view
I don't think so you should remove
1from url. If you remove it from url then how can you identify your post. So it will be good to keep it in url. Or if you want to remove then append this id at the end of post title likeand explode the last element for id of post
you are getting this error because in your url you added
!. To make your application secure CI prevent special characters from url. So it would be best practice to don't use special characters in url except_and-.On your Controller
now in your routes
application/config/routes.php