How would i create a vanity url in codeigniter - codeigniter

How can i create a vanity url in codeigniter. Im having real trouble doing this in the framework. And there doesnt seem to be any good answers out there.

It's possible, I'm using this in one of my projects...
Here is a thread on the CodeIgniter forums showing how to do it...
http://codeigniter.com/forums/viewthread/113962/

According to Personalized User Vanity URL's in CodeIgniter, you can accomplish this by modifying 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";

Related

configuring dynamic url's in router

I'm using Codeigniter. Basically what I want is to remove the Controller name (Home) from the url.
Those urls look like:
http://localhost/mechanicly/Home
http://localhost/mechanicly/Home/about
http://localhost/mechanicly/Home/contactus
now there are two ways I can remove the Home controller:
static definition of every url inside route:
$route['about'] = "Home/about";
$route['contactus'] = "Home/contactus";
I can use call backs in routes in Codeigniter:
$route['(.+)'] = function ( $param ) {
if( strpos( $param, "Admin" ) !== false ) {
echo $param;
return "Admin/".$param;
}
else{
echo $param;
return "Home/".$param;
}
};
this logic is much better as it is generic and I don't have to create new routes every time for new method inside the controller.
It is working fine for the client controller which is Home but I have another controller named as Admin and I want to redirect Admin requests to the Admin controller and Home request to the Home Controller.
Why does above code work fine for the Home controller but returns
not found
when I validate for the Admin controller?
I am using CI version 3.x
If you really want to get crazy, you could parse the methods from the controller file and programatically create the "static" approach.
Pseudo code here
$controller_file_contents = file_get_contents('path/to/controller.php');
$controller_methods = function_that_parses_methods_from_file($controller_file_contents);
foreach ($controller_methods as $controller_method) {
$route[$controller_method] = "Home/" . $controller_method;
}
How function_that_parses_methods_from_file works is probably gonna involve a regex, something like function \w+. If you go with this approach, try to keep the controller as small as possible by offloading as much logic as possible into models, which is often a good idea anyways. That way the performance impact in the router is as small as possible.
Alternatively, you may be able to parse the controller using get_class_methods if you can figure out how to load the controller into memory inside the router without conflicting when you need to load the controller using the router or causing too much performance issues.
Pretty goofy, but every method you create in that controller will automatically create a route.
you can create your menu(url´s) from db like
tbl_menu tbl_level
---------- -------------
id id
fk_level level
name dateUP
dateUP active
active
In your controllers you need to call the correct menu by session or wherever you want
then you can has this in your route.php
$route['(.+)'] = 'int_rout/routing/' . json_encode($1);
in your controller Int_rout.php
public function routing ( $param ) {
$routing = json_decode($param);
$routing = explode('/', $routing);
//$menu -> get menu from model
foreach($menu as $item){
if($routing[0] === $item->name){
//$level -> get level from model
$redirect = $level->level;
}
}
//the final redirect will be like
//admin/user or admin/user/12
//public/us
$params = ( empty($routing[1])) ? '' : '/' . $routing[1];
redirect($redirect . '/' . $routing[0] . $params, 'refresh');
}

codeigniter hmvc routes not working properly

I installed HMVC by wiredesignz but the routes from application/modules/xxx/config/routes.php didn't get recognized at all.
Here is an example:
In application/modules/pages/config/routes.php I have:
$route['pages/admin/(:any)'] = 'admin/$1';
$route['pages/admin'] = 'admin';
If I type the URL, domain.com/admin/pages/create it is not working, the CI 404 Page not found appears.
If I move the routes to application/config/routes.php it works just fine.
How do I make it work without putting all the admin routes in main routes.php?
I searched the web for over 4 hours but found no answers regarding this problem. I already checked if routes.php from modules is loading and is working just fine, but any routes I put inside won't work.
I found a way of making the routes from modules working just fine, I don't know if is the ideal solution but works fine so far:
open your application/config/routes.php and underneath $route['404_override'] = ''; add the following code:
$modules_path = APPPATH.'modules/';
$modules = scandir($modules_path);
foreach($modules as $module)
{
if($module === '.' || $module === '..') continue;
if(is_dir($modules_path) . '/' . $module)
{
$routes_path = $modules_path . $module . '/config/routes.php';
if(file_exists($routes_path))
{
require($routes_path);
}
else
{
continue;
}
}
}
the following solution works fine even if config folder or routes.php is missing from your module folder
Here's the thing: the module's routes.php only gets loaded when that module is "invoked", otherwise CI would have to load all route configurations from all modules in order to process each request (which does not happen).
You'll have to use your main application's routes.php to get this to work. You aren't using the pages segment in your URL, therefore the routing for that module never gets loaded.
I know that's what you wanted to avoid, but unfortunately it's not possible unless you want to get "hacky".
Here's the routing I use to map requests for admin/module to module/admin, maybe you can use it:
// application/config/routes.php
$route['admin'] = "dashboard/admin"; // dashboard is a module
$route['admin/([a-zA-Z_-]+)/(:any)'] = "$1/admin/$2";
$route['admin/([a-zA-Z_-]+)'] = "$1/admin/index";
$route['(:any)/admin'] = "admin/$1";
You just need this https://gist.github.com/Kristories/5227732.
Copy MY_Router.php into application/core/

CodeIgniter - Dynamic URL segments

I was wondering if someone could help me out.
Im building a forum into my codeigniter application and im having a little trouble figuring out how i build the segments.
As per the CI userguide the uri is built as follows
www.application.com/CLASS/METHOD/ARGUMENTS
This is fine except i need to structure that part a bit different.
In my forum i have categories and posts, so to view a category the following url is used
www.application.com/forums
This is fine as its the class name, but i want to have the next segment dynamic, for instance if i have a category called 'mycategory' and a post by the name of 'this-is-my-first-post', then the structure SHOULD be
www.application.com/forums/mycategory/this-is-my-first-post
I cant seem to achieve that because as per the documentation the 'mycategory' needs to be a method, even if i was to do something like /forums/category/mycategory/this-is-my-first-post it still gets confusing.
If anyone has ever done something like this before, could they shed a little light on it for me please, im quite stuck on this.
Cheers,
Nothing is confusing in the document but you are a little bit confused. Let me give you some suggestions.
You create a view where you create hyperlinks to be clicked and in the hyperlink you provide this instruction
First Post
In the controller you can easily get this
$category = $this->uri->segment(3);
$post = $this->uri->segment(4);
And now you can proceed.
If you think your requirements are something else you can use a hack i have created a method for this which dynamically assign segments.
Go to system/core/uri.php and add this method
function assing_segment($n,$num)
{
$this->segments[$n] = $num;
return $this->segments[$n];
}
How to use
$this->uri->assign_segment(3,'mycategory');
$this->uri->assign_segment(4,'this-is-my-first-post');
And if you have error 'The uri you submitted has disallowed characters' then go to application/config/config.php and add - to this
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
You could make a route that forwards to a lookup function.
For example in your routes.php add a line something like;
$route['product/(:any)/(:any)'] = "forums/cat_lookup/$1/$2";
This function would then do a database lookup to find the category.
...
public function cat_lookup($cat, $post) {
$catid = $this->forum_model->get_by_name($cat);
if ($catid == FALSE) {
redirect('/home');
}
$post_id = $this->post_model->get_by_name($post);
/* whatever else you want */
// then call the function you want or load the view
$this->load->view('show_post');
}
...
This method will keep the url looking as you want and handle any problems if the category does not exist.Don't forget you can store the category/posts in your database using underscores and use the uri_title() function to make them pretty,
Set in within config/routes.php
$route['song-album/(:any)/:num'] = 'Home/song_album/$id';
fetch in function with help of uri segment.
$this->uri->segment(1);

Codeigniter global_xss_filtering

In my codeigniter config I have $config['global_xss_filtering'] = TRUE;. In my admin section I have a ckeditor which generates the frontend content.
Everything that is typed and placed inside the editor works fine, images are displayed nice, html is working. All except flash. Whenever I switch to html mode and paste a youtube code piece it is escaped and the code is visible on the frontpage instead of showing a youtube movie.
If I set $config['global_xss_filtering'] = FALSE; the youtube code is passed like it should. This is because 'object', 'embed' etc are flagged as "naughty" by CI and thus escaped.
How can I bypass the xss filtering for this one controller method?
Turn it off by default then enable it for places that really need it.
For example, I have it turned off for all my controllers, then enable it for comments, pages, etc.
One thing you can do is create a MY_Input (or MY_Security in CI 2) like the one in PyroCMS and override the xss_clean method with an exact copy, minus the object|embed| part of the regex.
http://github.com/pyrocms/pyrocms/blob/master/system/pyrocms/libraries/MY_Security.php
It's one hell of a long way around, but it works.
Perhaps we could create a config option could be created listing the bad elements for 2.0?
My case was that I wanted global_xss_filtering to be on by default but sometimes I needed the $_POST (pst you can do this to any global php array e.g. $_GET...) data to be raw as send from the browser, so my solution was to:
open index.php in root folder of the project
added the following line of code $unsanitized_post = $_POST; after $application_folder = 'application'; (line #92)
then whenever I needed the raw $_POST I would do the following:
global $unsanitized_post;
print_r($unsanitized_post);
In CodeIgniter 2.0 the best thing to do is to override the xss_clean on the core CI library, using MY_Security.php put this on application/core folder then using /application/config.php
$config['xss_exclude_uris'] = array('controller/method');
here's the MY_Security.php https://gist.github.com/slick2/39f54a5310e29c5a8387:
<?php
/**
* CodeIgniter version 2
* Note: Put this on your application/core folder
*/
class MY_Security extends CI_Security {
/**
* Method: __construct();
* magic
*/
function __construct()
{
parent::__construct();
}
function xss_clean($str, $is_image = FALSE)
{
$bypass = FALSE;
/**
* By pass controllers set in /application/config/config.php
* config.php
* $config['xss_exclude_uris'] = array('controller/method')
*/
$config = new CI_Config;
$uri = new CI_URI;
$uri->_fetch_uri_string();
$uri->_explode_segments();
$controllers_list = $config->item('xss_exclude_uris');
// we need controller class and method only
if (!empty($controllers_list))
{
$segments = array(0 => NULL, 1 => NULL);
$segments = $uri->segment_array();
if (!empty($segments))
{
if (!empty($segments[1]))
{
$action = $segments[0] . '/' . $segments[1];
}
else
{
$action = $segments[0];
}
if (in_array($action, $controllers_list))
{
$bypass = TRUE;
}
}
// we unset the variable
unset($config);
unset($uri);
}
if ($bypass)
{
return $str;
}
else
{
return parent::xss_clean($str, $is_image);
}
}
}
Simple do the following on the views when displaying embedded object code like from YouTube and etc:
echo str_replace(array('<', '>'), array('<', '>'), $embed_filed);
The global XSS Filtering is only escaping (or converting) certain "dangerous" html tags like <html>
Simple Workaround:
Set $config['global_xss_filtering'] = TRUE;
Run your POST data through HTMLPurifier to remove any nasty <script> tags or javascript.
HTMLPurifier Docs
HTMLPurifier Codeigniter Integration
On the page where you receive the forms POST data use html_entity_decode() to undo what XSS filtering did.
//by decoding first, we remove everything that XSS filter did
//then we encode all characters equally.
$content = html_entity_decode($this->input->post('template_content'))
Then immediately run it through htmlentities()
$content = htmlentities($content);
Store as a Blob in MySQL database
When you want to display the
information to the user for editing run html_entity_decode()
This is how I did it. If anyone knows of a major flaw in what I did, please tell me. It seems to be working fine for me. Haven't had any unexpected errors.

Codeigniter HVMC modular seperation extension URL rewrite / routing

Ive been using HVMC modular extension, and its working great, but Im having trouble figuring out how to use, and if it is possible to use URL routing with HVMC.
Basically, I have a module called “site”, which is my main default site controller. All of the other modules I am not using directly, I am only using them by calling echo modules::run(‘controller/method’);—So basically I just want to remove “site” from the URL so that all the methods within the site module/controller appear without the word “site” in it.
Can anyone tell me if this can be done with HVMC modular extensions?
Any help much appreciated!
For completeness I have been researching my own solution to this issue and the removal of the "site" prefix on the URI string can be achieved by adding the following into the routes.php config file.
$route['(:any)'] = "site/$1";
$route['default_controller'] = "site";
I also worked since 3 years in CI HMVC, and some of my routing examples is there, it may help you.
I define 2 types of module here one is site and another is admin.
1>Routing for admin:
/*ADMIN is a constant, you can define anything like admin or backend etc. */
/*Example: admin/login*/
$route[ADMIN.'/([a-zA-Z]+)'] = function($controller){
return 'admin/'.strtolower($controller);
};
/*Example: admin/user/listing*/
$route[ADMIN.'/([a-zA-Z]+)/(:any)'] = function($controller, $function){
return 'admin/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function));
};
/*Example: admin/user/edit/LU1010201352*/
$route[ADMIN.'/([a-zA-Z]+)/(:any)/(:any)'] = function($controller,$function,$param) {
return 'admin/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function)).'/'.$param;
};
/*Example: admin/user/assign-group/LU1010201352/G2010201311*/
$route[ADMIN.'/([a-zA-Z]+)/(:any)/(:any)/(:any)'] = function($controller,$function,$param,$param1){
return 'admin/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function)).'/'.$param.'/'.$param1;
};
2>Routing for site:
$route['([a-zA-Z]+)'] = function($controller) {
return 'site/'.strtolower($controller);
};
$route['([a-zA-Z]+)/(:any)'] = function($controller,$function){
return 'site/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function));
};
$route['([a-zA-Z]+)/(:any)/(:any)'] = function($controller,$function,$param) {
return 'site/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function)).'/'.$param;
};
$route['([a-zA-Z]+)/(:any)/(:any)/(:any)'] = function($controller,$function,$param,$param1) {
return 'site/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function)).'/'.$param.'/'.$param1;
};
It is totally dynamic. You can create lots of controller inside any module. If you want to add more module then you just make another block of routing like 1 or 2.

Resources