Difficulty with two segment uri - codeigniter

They are trying to create the url, where the first segment is the User and the second is his file, ex: www.exemplo.com/joao/ball
Controller
public function user() {
$user_url = $this->uri->segment(1);
}
^^ This would return the profile with every file: www.exemplo.com/joao
public function arquivo() {
$arquivo_url = $this->uri->segment(2);
}
^^ This specific file: www.exemplo.com/joao/bola
Routes
$route['(:any)'] = 'home/user/$1';
$route['??'] = 'home/arquivo/$1';

To solve your problem, you should use route like this..
$route['(:any)/(:any)'] = 'home/arquivo';
$route['(:any)'] = 'home/user';
but as far you with your project this type of routing will give your some hard time. i suggest you to use explicit route name because (:any) refer any thing can be pass through this url.

You can use routes to map the URI and its parameters to the relevant function. CodeIgniter routes behave differently depending on the version of CI.
In CodeIgniter 2.2.0 (:any) is equivalent to the regex, .+ - matches one or more of any character (excluding line breaks); in 3.0 and the current development version it is equivalent to [^/]+ - one or more of any character, excluding line breaks.
The latter is more useful in this case, as you want to identify the two parameters (separated by a forward slash).
In 2.2.0:
$route['([^/]+)/([^/]+)'] = 'home/arquivo/$1/$2';
$route['(:any)'] = 'home/user/$1';
In 3.0:
$route['(:any)/(:any)'] = 'home/arquivo/$1/$2';
$route['(:any)'] = 'home/user/$1';
Controller functions will usually pass the URI parameters as function parameters like this:
public function user($user)
{
// Show the user's profile
}
public function arquivo($user, $file)
{
// Show the file for the user
}

Able to resolve with the following code.
$route['([^/]+)'] = 'home/user/$1';
$route['(:any)/(:any)'] = 'home/arquivo/$1';

Related

can we give create function name like my-account in codeigniter

I am working on codeigniter and I want to give function name like edit-profile and controller name like my-account.
I have tried to create like this but it is giving error.
In config/routes.php
$route['translate_uri_dashes'] = FALSE;
Just change to TRUE and you can use either _ or -.
and name functions separated by underscores then when request url use
separate words with dash
I hope my answer would be useful
Yes. You can
In Controller
public function my_account($value='')
{
# code...
}
In Routes
$route['my-account'] = "controller_name/my_account";
Tested. Works fine
In config
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
i hope you are asking about name conventions just through this url if about method name convention class and method naming

Codeigniter - url segment replace or redirect

I have a base controller (base) which all other controllers extend from.
Anything placed here will override other controllers, the redirects will be here.
URLs example:
http://domain.com/controllerone/function
http://domain.com/controllertwo/function
http://domain.com/controllerthree/function
Using the code below. will give me the controller name
$this->uri->segment(1);
Each of the above controllers need to be redirected to separate URLs, but the funcation part should not change:
http://domain.com/newcontrollerone/function
http://domain.com/newcontrollertwo/function
http://domain.com/newcontrollerthree/function
In my base controller i want the following logic:
$controller_name = $this->uri->segment(1);
if($controller_name === 'controllerone'){
// replace the controller name with new one and redirect, how ?
}else if($controller_name === 'controllertwo'){
// replace the controller name with new one and redirect, how ?
}else{
// continue as normal
}
i was thinking i should use redirect() function and str_replace(), but dont know how efficient these would be. Ideally i do not want to use the Routing class.
thanks.
try
header("Location:".base_url("newcontroller/".$this->uri->segment(2)));
Simple Solution using segment_array:
$segs = $this->uri->segment_array();
if($segs[1] === 'controllerone'){
$segs[1] = "newcontroller";
redirect($segs);
}else if($segs[1] === 'controllertwo'){
$segs[1] = "newcontroller2";
redirect($segs);
}else{
// continue as normal
}
CodeIgniter's URI Routing, should be able to help in this case. However, if you have a good reason not to use it, then this solution may help.
The potential redirects are in an array, where the key is the controller name being looked for in the URL and the value is the name of the controller to redirect to. This may not be the most efficient but I think it should be easier to manage and read than a potentially very long if-then-else statement.
//Get the controller name from the URL
$controller_name = $this->uri->segment(1);
//Alternative: $controller_name = $this->router->fetch_class();
//List of redirects
$redirects = array(
"controllerone" => "newcontrollerone",
"controllertwo" => "newcontrollertwo",
//...add more redirects here
);
//If a redirect exists for the controller
if (array_key_exists($controller_name, $redirects))
{
//Controller to redirect to
$redirect_controller = $redirects[$controller_name];
//Create string to pass to redirect
$redirect_segments = '/'
. $redirect_controller
. substr($this->uri->uri_string(), strlen($controller_name)); //Function, parameters etc. to append (removes the original controller name)
redirect($redirect_segments, 'refresh');
}
else
{
//Do what you want...
}

CodeIgniter - When using $route['(:any)'] = 'pages/view/$1' how to use other controllers?

When using
$route['(:any)'] = 'pages/view/$1';
and I want to use other controllers in my routing for example:
$route['del/(:any)'] = 'crud/del';
it won't work. I guess it will use
pages/view/del/$1
and not my crud-controller when deleting an item. How can I solve this?
As indicated, $route['(:any)'] will match any URL, so place your other custom routes before the "catch-all" route:
$route['del/(:any)'] = 'crud/del';
// Other routes as needed...
$route['(:any)'] = 'pages/view/$1';
Its hundred percent working
$route['(:any)'] url is placed last in your routes file
$route['(:any)/company_product_deal_detail'] = "mypage_product_picture/deal_detail/$1";
$route['(:any)/company_service_deals/(:any)'] = "mypage_service_deal_list/index/$1";
$route['(:any)/company_service_deals'] = "mypage_service_deal_list/index/$1";
$route['(:any)'] = "company/index/$1";
I know that it's an old question, but I have found myself a nice solution.
By default, CodeIgniter gives priority to URL's from routes config (even if straight controller, method etc. specified), so I have reversed this priority this way:
In system/core/Router.php find _parse_routes method.
Add this code under literal route match:
$cont_segments = $this->_validate_request($this->uri->segments);
if ($cont_segments == $this->uri->segments) {
return $this->_set_request($cont_segments);
}
I agree, that this approach is kinda wrong, because we edit file from system/core, but I needed a fast soluttion to work with a lot of URL's.

CodeIgniter: urlencoded URL in URI segment does not work

I'm trying to put a URL as the value of one of my URI segments in CI. My controller method is defined to accept such an argument. However, when I go to the URL, I get a 404 error. For example:
www.domain.com/foo/urlencoded-url/
Any ideas what's wrong? Should I do this via GET instead?
UPDATE:
// URL that generates 404
http://localhost/myapp/profile_manager/confirm_profile_parent_delete/ugpp_533333338/http%3A%2F%2Flocalhost%2Fmyapp%2Fdashboard%2F
// This is in my profile_manager controller
public function confirm_profile_parent_delete($encrypted_user_group_profile_parent_id = '', $url_current = '')
If I remove the second URI segement, I don't get a 404: http://localhost/myapp/profile_manager/confirm_profile_parent_delete/ugpp_533333338/
It seems that the %2F breaks things for apache.
Possible solutions:
preg_replace the /'s to -'s (or something else) before sending the url then switch it back on the other end.
Set apache to AllowEncodedSlashes On
bit of a hack, but you could even save the url to a session variable or something instead of sending through the url *shrug *
double url encode it before sending
Pass urlendode()'d URL in segment and then decode it with own (MY_*) class:
application/core/MY_URI.php:
class MY_URI extends CI_URI {
function _filter_uri($str)
{
return rawurldecode(parent::_filter_uri($str));
}
}
// EOF
You may need to change the rule in config/route.php to accept the encoded characters in URL. Also you can take a look at some of the solution from below articles:
http://codeigniter.com/forums/viewthread/81365/
http://sholsinger.com/archive/2009/04/passing-email-addresses-in-urls-with-codeigniter/
Passing URL in Codeigniter URL segment
I actually had to do urlencode(urlencode(urlencode(
and urldecode(urldecode(urldecode(
3 times!! and it finally worked, twice didn't cut it.
try
function __autoload($class){
if(!empty($_SERVER['REQUEST_URI'])){
$_SERVER['REQUEST_URI'] = $_SERVER['REDIRECT_QUERY_STRING'] = $_SERVER['QUERY_STRING'] = $_SERVER['REDIRECT_URL'] = $_SERVER['argv'][0] = urldecode($_SERVER['REQUEST_URI']);
}
}
in config.php
this method work for me
This is very old, but I thought I'd share my solution.
Instead of accepting the parameter as a url path, accept it as a get variable:
http://localhost/myapp/profile_manager/confirm_profile_parent_delete/ugpp_533333338?url_current=http%3A%2F%2Flocalhost%2Fmyapp%2Fdashboard%2F
and in code:
function confirm_profile_parent_delete($encrypted_user_group_profile_parent_id = '') {
$url_current = $this->input->get('url_current');
...
This seems to work.

How to build an anchor in CodeIgniter where you want to change a variable that is already present in the URI?

Normally I would just use URL GET parameters but CodeIgniter doesn't seem to like them and none of the URL helper functions are designed for them, so I'm trying to do this the 'CodeIgniter way'.
I would like to build a page where the model can accept a number of different URI paramters, none necessarily present, and none having to be in any particular order, much like a regular URL query string with get parameters.
Let's say I have the following url:
http://example.com/site/data/name/joe/
Here not including the controller or the method there would be one parameter:
$params = $this->uri->uri_to_assoc(1);
print_r($params);
// output
array( [name] => [joe] )
If I wanted 'joe' to change to 'ray' I could do this:
echo anchor('name/ray');
Simple enough but what if there are more parameters and the position of the parameters are changing? Like:
http://example.com/site/data/town/losangeles/name/joe/
http://example.com/site/data/age/21/name/joe/town/seattle
Is there a way to just grab the URL and output it with just the 'name' parameter changed?
Edit: As per landons advice I took his script and set it up as a url helper function by creating the file:
application/helpers/MY_url_helper.php
Basically I rewrote the function current_url() to optionally accept an array of parameters that will be substituted into the current URI. If you don't pass the array the function acts as originally designed:
function current_url($vars = NULL)
{
$CI =& get_instance();
if ( ! is_array($vars))
{
return $CI->config->site_url($CI->uri->uri_string());
}
else
{
$start_index = 1;
$params = $CI->uri->uri_to_assoc($start_index);
foreach ($vars as $key => $value)
{
$params[$key] = $value;
}
$new_uri = $CI->uri->assoc_to_uri($params);
return $CI->config->site_url($new_uri);
}
}
It works OK. I think the bottom line is I do not like the 'CodeIgniter Way' and I will be looking at mixing segment based URL's with querystrings or another framework altogether.
You can use the assoc_to_uri() method to get it back to URI format:
<?php
// The segment offset to use for associative data (change me!)
$start_index = 1;
// Parse URI path into associative array
$params = $this->uri->uri_to_assoc($start_index);
// Change the value you want (change me!)
$params['name'] = 'ray';
// Convert back to path format
$new_uri = $this->uri->assoc_to_uri($params);
// Prepend the leading segments back to the URI
for ($i=1; $i<$start_index; $i++)
{
$new_uri = $this->uri->segment($i).'/'.$new_uri;
}
// Output anchor
echo anchor($new_uri);
I'd recommend wrapping this in a helper function of some sort. Happy coding!
Why not use CodeIgniter's built in URI Class? It allows you to select the relevant segments from the URL which you could use to create the anchor. However, unless you created custom routes, it would mean that your methods would need to accept more parameters.
To use the URI Class, you would have the following in your method:
echo anchor($this->uri->segment(3).'/ray');
Assuming /site/data/name are all CodeIgniter specific (/controller/method/parameter)
Now, I think this could be made a lot easier if you were using routes. Your route would look like this:
$route['site/data/name/(:any)'] = 'site/data/$1';
Effictively, your URL can be as detailed and specific as you want it to be, but in your code the function is a lot cleaner and the parameters are quite descriptive. You method would defined like this:
function data($name) { }
To extend your route to accept more parameters, your route for the the example URL "http://example.com/site/data/age/21/name/joe/town/seattle" you supplied would look like this:
$route['site/data/age/(:num)/name/(:any)/town/(:any)'] = 'controller/data/$1/$2/$3';
And your function would look like this:
function data($age, $name, $town) { }

Resources