I have some website http://www.example.com, I have a controller abc in which I have method index() which loads my website's view. I have made my controller abc as default controller so that when user enters example.com , he can directly see the view. I cannot change this default controller in any case. Now I want that if user enters example.com/1234 , where 1234 is profile number, so it should show that profile . if it is example.com/5678 , then it should show 5678's profile. The problem I am facing is , if user enters example.com/1234 then it will throw a 404 error because I don't have any controller 1234, even if I make a check in my default controller's index function if($this->uri->segment(3) == True) it is throwing 404 error. Any help would be appreciated.
In your routes file add this change:
$route['(:any)'] = 'abc/index/$1';
Then in abc controller:
public function index($profile=NULL)
{
$profile = $this->uri->segment(1, 0);
echo($profile);// just for checking, of course, you will remove this later, + the rest of your code, related to user id
Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method.
In the routes.php (config folder) you can change the defoult controller and routing also. Read the Wildcards (secion) in documentation below
More informacion read the documentation
Create a pre_controller hook in config/hooks.php. Remember to enable hooks in config/config.php if you haven't already.
Example:
$hook['pre_controller'][] = array(
'class' => 'Thehook',
'function' => 'check_for_profile',
'filename' => 'thehook.php',
'filepath' => 'hooks'
);
Then create your hook method check_for_profile() in hooks/thehook.php. This method can check for a matching profile and display or redirect accordingly. If no profile match is found you can call the show_404() method.
This way, your existing controller/method paths are unaffected, and all of your routes remain intact.
If you're redirecting within the hook, use this format:
header("Location: controller/method");
..rather than
redirect('controller/method');
...as the latter will result in a continuous loop
Add in routes.php
$route["(.*)"] = 'abc/userid/$1';
Then in main controller abc add
public function userid()
{
$userid=$this->uri->segment(1);
echo ($userid);
}
Now you have userid in this function :)
Related
I have a codeigniter application in my localserver.
I need some URL rewriting rule for the following.
If any one have any solution please answer.
http://localhost/myapp/index.php/users/login
to
http://localhost/myapp/index.php/usuarios/login
How can I do this in Codeigniter.
This record in config/routes.php will do what you want -
$route['users/login'] = 'usuarios/login'; // for login only (static)
$route['users/(:any)'] = 'usuarios/$1'; // for all routes to users (dynamic for functions without parameters)
More details here : URI Routing
Codeigniter works like this to access myFunction from Mycontroller with the value myVarValue
http://my.webPage.com/index.php/MyController/myFunction/myVarValue
U want to alter the URL, yes you can by creating routes on ../application/config/routes.php
$route['my-function-(:any)'] = 'MyController/myFunction/$1';
This is the first step
You created the routes and those are not working?
Set the base_url on the file ../application/config/config.php, in your case will be http://localhost/myapp, line number 26 of the file on CI v3.1.6
Set the default controller, the default controller that will be inmediatelly accessed by anyone who enters ur website, u set this on ../application/config/routes.php, your default controller can be the name of a Controller or A function within a controller.
Let's say u have this controller
public class MyController extends CI_Controller{
public function __construct(){
parent::__construct();
}
public function index(){
echo 'Hello people, im the index of this controller,'.
' im the function u will see everytime u '.
'access the route http://localhost/myApp/MyController';
}
public function notTheIndex(){
echo 'Hello, im the function u will see if u'.
'access http://localhost/MyController/notTheIndex';
}
}
Lets say this controller will be ur default controller so as mentioned in the routes.php file in the line 53 on ci v3.16 set
$route['default_controller'] = 'MyController';
//if u want to just access the index method
$route['default_controller'] = 'MyController/notTheIndex';
//if for some reason u have a method u would like to be executed
//by default as the index page
Now u want the uris to keep have the names u set
$route['some-beautiful-name'] = 'MyController/notTheIndex';
so when u access http://localhost/some-beautiful-name it will show the result of MyController/notTheIndex
Consider that if u are accessing the different pages via a <a href='some_link'>Some link</a> and the href values need to be changed to your defined routes, if not, this will still work if they are pointing to controllers, but the uri names will stay the same, lets take the example of 'some.beautiful-name' to access MyController/notTheIndex
In Your View
This is a link
The link will work but the uri name will be http://localhost/MyController/notTheIndex
This is a link
The link will work because u defined a route like this else it will not and show 404 error, but here the url shown will be http://localhost/some-beautiful-name
Hope my answer helps u.
I'm using ZfcUser with ht-user-registration and scn-social-auth and there are 2 fairly minor enhancements I want to achieve to extend my implementation, but I'm not having much success so far:
ht-user-registration sends new users an email after registering and denies them access until they've activated their account, this is working fine. What I'd like to do to extend this is redirect the user after registration so that they are sent to a page telling them to check their e-mail rather than to the login page, which is the default behaviour of ZfcUser. I have tried adding an event listener to the module bootstrap that looks like this:
$response = $e->getResponse();
// indicate that we intend to redirect after register action
// set the redirection location to the home page
$response->getHeaders()->addHeaderLine('Location', 'home');
$response->setStatusCode(302);
$response->sendHeaders();
$em = \Zend\EventManager\StaticEventManager::getInstance();
$em->attach('ZfcUser\Service\User', 'register', function($event) use ($response) {
// don't allow anything else to process this event
$event->stopPropagation();
// return the redirect response
return $response;
});
This is called correctly but the redirect never happens and the user still ends up at the login page. Is there something else I need to do to execute the redirect? Or maybe there's a better way entirely to achieve this?
I'd like to add layout variables so that I can modify page titles and navigation in my layout template for the ZfcUser pages. In order to do this I made an override of the UserController from ZfcUser like this :
class UserController extends \ZfcUser\Controller\UserController
{
public function loginAction()
{
$this->layout()->setVariables(array(
'view_title' => 'Reports Login',
));
return parent::loginAction();
}
}
And then overrode the invokable for zfcuser in the config like this:
'controllers' => array(
'invokables' => array(
'Application\Controller\Index' => 'Application\Controller\IndexController',
'zfcuser' => 'Application\Controller\UserController',
),
),
The framework tries to instantiate my UserController at the right point but fails with an InvalidArgumentException: 'You must supply a callable redirectCallback' which I can see is required to construct the base controller but doesn't get passed to my overridden version - any clues why not? I can't find a working example of this to help.
Maybe there's a much easier way to inject layout variables into another module's controller actions?
[EDIT] I have found a simple but not very elegant way of doing this. Since my module overrides the views for both login and registration then it's possible to set layout variables within the view, thus I was able to add a one liner to the top of each view to set the layout variable, e.g.:
<?php $this->layout()->setVariable('view_title', 'Register for an account'); ?>
This doesn't feel correct, but works. If there's a better solution I'd like to know.
I am using Yii framework for my application. My application contain 4 controllers in which I want to pass value from one controller to another.
Let us consider site and admin controller. In site controller, I manage the login validation and retrieves admin id from database. But I want to send admin id to admin controller.
I try session variable, its scope only within that controller.
Please suggest the possible solution for me.
Thanks in advance
You want to use a redirect:
In the siteController file
public function actionLogin()
{
//Perform your operation
//The next line will redirect the user to
//the AdminController in the action called loggedAction
$this->redirect(array('admin/logged', array(
'id' => $admin->id,
'param2' => $value2
)));
}
in the adminController file
public function loggedAction($id, $param2)
{
//you are in the other action and params are set
}
Can I get the controller action from given URL?
In my project, I will have different layout used for admin and normal users. i.e.
something.com/content/list - will show layout 1.
something.com/admin/content/list - will show layout 2.
(But these need to be generated by the same controller)
I have added filter to detect the pattern 'admin/*' for this purpose. Now I need to call the action required by the rest of the URL ('content/list' or anything that will appear there). Meaning, there could be anything after admin/ it could be foo/1/edit (in which case foo controller should be called) or it could be bar/1/edit (in which case bar controller should be called). That is why the controller name should be generated dynamically from the url that the filter captures,
So, I want to get the controller action from the URL (content/list) and then call that controller action from inside the filter.
Can this be done?
Thanks to everyone who participated.
I just found the solution to my problem in another thread. HERE
This is what I did.
if(Request::is('admin/*')) {
$my_route = str_replace(URL::to('admin'),"",Request::url());
$request = Request::create($my_route);
return Route::dispatch($request)->getContent();
}
I could not find these methods in the documentation. So I hope, this will help others too.
You can use Request::segment(index) to get part/segment of the url
// http://www.somedomain.com/somecontroller/someaction/param1/param2
$controller = Request::segment(1); // somecontroller
$action = Request::segment(2); // someaction
$param1 = Request::segment(3); // param1
$param2 = Request::segment(3); // param2
Use this in your controller function -
if (Request::is('admin/*'))
{
//layout for admin (layout 2)
}else{
//normal layout (layout 1)
}
You can use RESTful Controller
Route:controller('/', 'Namespace\yourController');
But the method have to be prefixed by HTTP verb and I am not sure whether it can contain more url segment, in your case, I suggest just use:
Route::group(array('prefix' => 'admin'), function()
{
//map certain path to certain controller, and just throw 404 if no matching route
//it's good practice
Route::('content/list', 'yourController#yourMethod');
});
I want to force all users to log in before accessing pages of my site. I have followed Larry Ullman's tutorial Forcing Login for All Pages in Yii.
According to the tutorial you can make an exception for some pages to avoid redirecting to the log in page. In order to check the current controller it has checked $_GET value. My problem is that I have used urlManager to rewrite the URL and $_GET gives me a null value. Is there any method I can use to get the current controller and action in the score of my class?
I tried the following but it is not accessible in the scope of my component class:
Yii::app()->controller->getId
Did you try:
Yii::app()->controller->id
and:
Yii::app()->controller->action->id
?
Yes you can get the current controller/action route, by reversing urlManager rule:
Yii::app()->urlManager->parseUrl(Yii::app()->request)
As now in Yii2
get current controller name
Yii::$app->controller->id
current controller object
Yii::$app->controller
current action name:
Yii::$app->controller->action->id
current route:
Yii::$app->requestedRoute
Using Yii2, obtain the current controller object with:
Yii::$app->controller
From the controller, obtain the current action as a string using:
Yii::$app->controller->action->id
In Yii2:
The problem of calling Yii::$app->controller->id is that when you call it somewhere (example: in one of your top-level abstract controller), Yii::$app->controller might not be instantiated yet, so it will return error.
Just directly call urlManager to map request to route:
var_dump(Yii::$app->urlManager->parseRequest(Yii::$app->request))
Try Yii::app()->controller->getRoute()
If I get you question correctly, you are basically trying to stop access to certain actions in the controller from being accessed without being logged in right?
If this is what you are after, the correct method to do it is this :
Make a actionMethod() in the controller like so :
class SomeController extends CController{
public function actionSomeAction(){
... More code...
}
After that, you can access the site using : path/to/application/controllerName/actionName
Now if you want to force the user to log in before accessing the action, do this :
Make an access control like so :
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions' => array('**yourActionMethodName**'),
'users' => array('#'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
Now only authenticated users would be able to access the URL.
I hope it solved your problem.
If you simply want to check if the user is a guest and if he is, send him to the login page everytime:
In the config/main.php, add the following :
'defaultController' => 'controllerName/actionMethod',
And in that controller just add the above access rule. Now, by default you are opening the site to an access controlled method. So it would automatically redirect you to the login page.
Even another method :
Just add this in the views/layouts/main.php
<?php
if(Yii::app()->user->isGuest)
{
$this->redirect('/site/login');
}
?>
if (Yii::$app->requestedAction->id == "index") {
//do something
}