Custom Urls in Codeigniter domain.com/articlename.html - php

I need to make custom URL in Codeiginter to display links from
domain.com/news/id/1
to
domain.com/article-name.html
i want it dynamic to all news id not just one link
can i do it in codeiginter or not ?

Yes you can, This is called URL rewrite. I can explain here but the official documentation is far better.
here it is: http://ellislab.com/codeigniter/user-guide/general/urls.html

In your config.php file do this:
$config['url_suffix'] = '.html'; // this line might actually not be necessary, i forget
In routes.php set this:
$route['article-name.html'] = "news/id/1";
Let me know if you get any errors.
UPDATE
Step 1: Set your default controller in routes.php
$route['default_controller'] = 'get_article';
Step 2: Set your config.php to put .html on the end
$config['url_suffix'] = '.html';
Step 3: Create the Controller
// path: /codeigniter/2.1.4/yourAppName/controllers/get_article.php
<?php
class Get_article extends CI_Controller {
public function index($article = '')
{
// $article will be "article-name.html" or "article2-name.html"
if($article != '')
{
$pieces = explode('.', $article);
// $pieces[0] will be "article-name"
// $pieces[1] will be "html"
// Database call to find article name
// you do this
$this->load->view('yourArticleView', $dbDataArray);
}
else
{
// show a default article or something
}
}
}
?>

Related

Codeigniter routes not working, possibly because of internationalization?

Working on codeigniter project.
Got stuck with routes.
I want to access en/company/login through en/login, so how do I define routes then?
Right now routes code looks like this:
// URI like '/en/about' -> use controller 'about'
$route['^(en|lv)/(.+)$'] = "$2";
// '/en', '/lv' URIs -> use default controller
$route['^(en|lv)$'] = $route['default_controller'];
$route['company/login'] = "login";
tried:
$route['^(en|lv)/company/login'] = "login";
Obviously, Im not getting something.
Can you help please?
Your problem is (i had the same) that this:
$route['^(en|lv)/(.+)$'] = "$2";
overrides your rule for:
$route['^(en|lv)/company/login'] = "login";
Try this:
$route['^(en|lv)\/(company)\/(.+)$'] = "login";
Maybe it should help you to override the first pattern
And if not, edit the first pattern to this:
$route['^(en|lv)\/(?!company).+$'] = "$2";
$route["(en|fr|gr)/(:any)/login"] = "login/index/$1";
--
public function index($company)
{
$language = strtolower($this->uri->rsegments[3]);
if(!in_array($language, ['en', 'fr'])){
// set a default language
// if the route does not provide a valid one
$language = 'en';
}
// Load the language file for the selected language
// for example english, language/en/en_lang.php
$this->lang->load($language, $language);
}
Thank you for your answer, but it seems that I didnt explain that
/company/ is controller and /login/ is "company" function. Your
solution wont work for me. :/
// The $route should contain the uri,
// you seem to have them mixed up.
// $route['uri'] = "controller/method"
$route['(en|lv)/login'] = 'company/login';

Rewrite URL if controller is not existing in codeigniter

Rewrite URL if user tried to access any non existing controller.
Ex:- If user tried to access http://example.com/project/anyvalue . In my program there is no controller with name 'anyvalue'. In this situation I want to redirect to
http://example.com/project/profile/anyvalue
How is this possible using routing in codeigniter?
Use default route to redirect requests to some particular page if controller is missing
You can find routes location in
/application/admin/config/routes.php
$route['default_controller'] = "welcome";
Also use following in case of page not found
$route['404_override'] = 'default_page';
Add routes to all existing controllers under "/project/..."
Add a route that will match any paths under "/project"
Example:
/* Currently available controllers under "/project/" */
$route['project/profile'] = "project/profile";
$route['project/add'] = "project/add";
$route['project/edit'] = "project/edit";
/* Catch all others under "/project/" */
$route['project/(:any)'] = "project/profile/$1";
/* if controller class name is Profile and function name is index */
$route['project/(:any)'] = 'project/profile/index/$1';
What you want is Vanity URLs, you can find a guide for performing this in code igniter here:
http://philpalmieri.com/2010/04/personalized-user-vanity-urls-in-codeigniter/
Essentially you're adding this to your routes file:
$handle = opendir(APPPATH."/modules");
while (false !== ($file = readdir($handle))) {
if(is_dir(APPPATH."/modules/".$file)){
$route[$file] = $file;
$route[$file."/(.*)"] = $file."/$1";
}
}
/*Your custom routes here*/
/*Wrap up, anything that isnt accounted for pushes to the alias check*/
$route['([a-z\-_\/]+)'] = "aliases/check/$1";

Yii - Eliminate default controller ID for a module from URL

I created a module and there exists a default controller inside that. Now I can access the index action (default action) in the default controller like /mymodule/. For all other action i need to specify the controller id in the url like /mymodule/default/register/ . I would like to know is it possible to eliminate the controller id from url for the default controller in a module.
I need to set url rule like this:
before beautify : www.example.com/index.php?r=mymodule/default/action/
after beautify : www.example.com/mymodule/action/
Note: I want this to happen only for the default controller.
Thanks
This is a little tricky because the action part might be considered as a controller or you might be pointing to an existing controller. But you can get away with this by using a Custom URL Rule Class. Here's an example (I tested it and it seems to work well):
class CustomURLRule extends CBaseUrlRule
{
const MODULE = 'mymodule';
const DEFAULT_CONTROLLER = 'default';
public function parseUrl($manager, $request, $pathInfo, $rawPathInfo)
{
if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) {
// Make sure the url has 2 or more segments (e.g. mymodule/action)
// and the path is under our target module.
if (count($matches) != 4 || !isset($matches[1]) || !isset($matches[3]) || $matches[1] != self::MODULE)
return false;
// check first if the route already exists
if (($controller = Yii::app()->createController($pathInfo))) {
// Route exists, don't handle it since it is probably pointing to another controller
// besides the default.
return false;
} else {
// Route does not exist, return our new path using the default controller.
$path = $matches[1] . '/' . self::DEFAULT_CONTROLLER . '/' . $matches[3];
return $path;
}
}
return false;
}
public function createUrl($manager, $route, $params, $ampersand)
{
// #todo: implement
return false;
}
}

Codeigniter Dynamic Routing

Hi i wont to make something like that.
http:// example.com/ - Main Controller
http:// example.com/rules/ - Main Controller where content get from database, but if not exist
return 404 page. (It's ok, isn't problem.)
But if i have subfolder in application/controlles/rules/
I want to redirect it to Main Contorller at Rules folder.
This follow code can solve problem, but i don't know how it right realise.
At routes.php:
$route['default_controller'] = "main";
$route['404_override'] = '';
$dirtest = $route['(:any)'];
if (is_dir(APPPATH.'controllers/'.$dirtest)) {
$route['(:any)'] = $dirtest.'/$1';
} else {
$route['(:any)'] = 'main/index/$1';
}
Ok, what I have:
controllers/main.php
class Main extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('main_model');
}
public function index($method = null)
{
if (is_dir(APPPATH.'controllers/'.$method)) {
// Need re-rout to the application/controllers/$method/
} else {
if ($query = $this->main_model->get_content($method)) {
$data['content'] = $query[0]->text;
// it shows at views/main.php
} else {
show_404($method);
}
}
$data['main_content'] = 'main';
$this->load->view('includes/template', $data);
}
}
Updated Again (routes.php):
So, seem's like what i search (work example):
$route['default_controller'] = "main";
$route['404_override'] = '';
$subfolders = glob(APPPATH.'controllers/*', GLOB_ONLYDIR);
foreach ($subfolders as $folder) {
$folder = preg_replace('/application\/controllers\//', '', $folder);
$route[$folder] = $folder.'/main/index/';
$route[$folder.'/(:any)'] = $folder.'/main/$1';
}
$route['(:any)'] = 'main/index/$1';
But, in perfectly need some like this:
http:// example.com/1/2/3/4/5/6/...
Folder "controllers" has subfolder "1"?
YES: Folder "1" has subfolder "2"?
NO: Folder "1" has controller "2.php"?
NO: Controller "controllers/1/main.php" has function "2"?
YES: redirect to http:// example.com/1/2/ - where 3,4,5 - parameters..
It is realy nice, when you have structure like:
http://example.com/blog/ - recent blog's posts
http://example.com/blog/2007/ - recent from 2007 year blog's posts
http://example.com/blog/2007/06/ - same with month number
http://example.com/blog/2007/06/29/ - same with day number
http://example.com/blog/web-design/ - recent blog's post's about web design
http://example.com/blog/web-design/2007/ - blog' posts about web design from 2007 years.
http://example.com/blog/current-post-title/ - current post
Same interesting i find http://codeigniter.com/forums/viewthread/97024/#490613
I didn't thoroughly read your question, but this immediately caught my attention:
if (is_dir($path . '/' . $folder)) {
echo "$route['$folder/(:any)'] = '$folder/index/$1';"; //<---- why echo ???
}
Honestly I'm not sure why this didn't cause serious issues for you in addition to not working.
You don't want to echo the route here, that will just try to print the string to screen, it's not even interpreted as PHP this way. There are also some issues with quotes that need to be remedied so the variables can be read as variables, not strings. Try this instead:
if (is_dir($path . '/' . $folder)) {
$route[$folder.'/(:any)'] = $folder.'/index/$1';
}
Aside: I'd like to offer some additional resources that are not directly related to your problem, but should help you nonetheless with a solution:
Preferred way to remap calls to controllers: http://codeigniter.com/user_guide/general/controllers.html#remapping
Easier way to scan directories: http://php.net/manual/en/function.glob.php
It's hard to say why the registering of your routes fails. From your code I can see that you're not registering the routes (you just echo them), additionally I see that the usage of variables in strings are used inconsistently. Probably you mixed this a bit, the codeigniter documentation about routes is not precise on it either (in some minor points, their code examples are not really syntactically correct, but overall it's good).
I suggest you first move the logic to register your dynamic routes into a function of it's own. This will keep things a bit more modular and you can more easily change things and you don't pollute the global namespace with variables.
Based on this, I've refactored your code a bit. It does not mean that this works (not tested), however it might make things more clear when you read it:
function register_dynamic_routes($path, array &$route)
{
$nodes = scandir($path);
if (false === $nodes)
{
throw new InvalidArgumentException(sprintf('Path parameter invalid. scandir("$path") failed.', $path));
}
foreach ($nodes as $node)
{
if ($node === '.' or $node === '..')
continue
;
if (!is_dir("{$path}/{$node}")
continue
;
$routeDef = "{$folder}/(:any)";
$routeResolve = "{$folder}/index/\$1";
$route[$routeDef] = $routeResolve;
# FIXME debug output
echo "\$route['{$routeDef}'] = '{$routeResolve}';";
}
}
$path = APPPATH.'controllers/';
register_dynamic_routes($path, $route);
$route['(:any)'] = 'main/index/$1';
Next to this you probably might not want to shift everything onto the index action, but a dynamic action instead. Furthermore, you might want to have a base controller that is delegating everything into the sub-controllers instead of adding the routes per controller. But that's up to you. The example above is based on the directory approach you outlined in your question.
Edit: Additional information is available in the Controllers section next to the URI Routing section
All this seems kind of complicated.
Plus, if you have hundreds (or thousands or more?) of possible routes in a database you may not want to load all of them into the "$routes" array every time any page loads in your application.
Instead, why not just do this?
last line of routes.php:
$route['404_override'] = 'vanity';
Controller file: Vanity.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Vanity extends MY_Controller {
/**
* Vanity Page controller.
*
*/
public function __construct() {
parent::__construct();
}
public function index()
{
$url = $_SERVER['PHP_SELF'];
$url = str_replace("/index.php/", "", $url);
// you could check here if $url is valid. If not, then load 404 via:
//
// show_404();
//
// or, if it is valid then load the appropriate view, redirect, or
// whatever else it is you needed to do!
echo "Hello from page " . $url;
exit;
}
}
?>

codeigniter url suffix .html + hashtag

I want to build an url with hashtag on codeigniter. Example:
"http://www.example.com/blog/post/title.html#comments"
The url_config in my config.php is this:
$config['url_suffix'] = ".html";
And I used the following code to build the anchor:
anchor('blog/post/'.url_title($post->title, 'dash', TRUE).'#comments', 'comments', 'title="'.$post->title.'"');
If you know any solution please let me know it. Thanks
How about this?
anchor(site_url('blog/post/'.$post->title)."#comments");
It returns an url like this: http://example.org/blog/post/stackoverflowRocks.html#comments
If you want to use hash tags without having to pass 'site_url()' to the anchor method you can extend the CodeIgniter Config library class fairly easily.
The CodeIgniter Config library class has a method called site_url that runs when you use the anchor method. site_url, by default, adds the url_suffix after any uri you pass to it without any care or knowledge of hash tags. Fortunately, you can simply extend the Config library class to modify site_url to check for hash tags and add them to the end of the URI after the url_suffix is added.
If you feel so compelled, copy the code below and save it under '/system/application/libraries/MY_Config.php'. You may have to open up '/system/application/config/autoload.php' and add 'My_Config.php' to the autoload library array.
<?php
class MY_Config extends CI_Config {
function site_url($uri = '')
{
if (is_array($uri))
{
$uri = implode('/', $uri);
}
if ($uri == '')
{
return $this->slash_item('base_url').$this->item('index_page');
}
else
{
$suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix');
$hash = '';
if(substr_count($uri,'#') == 1)
{
list($uri,$hash) = explode('#',$uri);
$hash = '#'.$hash;
}
return $this->slash_item('base_url').$this->slash_item('index_page').trim($uri, '/').$suffix.$hash;
}
}
}
?>
The new site_url method sets $hash to an empty string. If a hash tag is found in the link you pass in, the link is split into an array and passed into variables. site_url will now return the link with the hash tag appended at the end (if hash code is present) after the url_suffix.

Categories