Redirect in PHP Codeigniter - php

I have some problems using Code Igniter and I feel there is something I don't understand because I can't get my redirects and my headers to work. Here is the situation :
When site is entered, the default "home" controller is called.
public function initialize()
{
printf("CONSTRUCTION OF HOME CONTROLLER - \n");
// print_r($_SESSION);
//TODO : CONSIDER CREATING A LIBRARY TO AVOID WRITING THIS OFTEN. NOT
// SESSION TROLLING DETECTION
if( isset($_SESSION['banana']))
{
echo "SPLITTING THE TRUTH";
}
// GETTING AS SERIOUS AS GREG
if( !isset($_SESSION['username']))
{
printf("USERNAME IS NOT SET. SETTING UP THE LOGIN PAGE. \n");
redirect('home_invite');
}
else
{
$this->load->view('welcome_message');
}
}
public function index()
{
//INITIALIZING THE PATH USED FOR THIS NAVIGATION
printf("TROLLING THE BEGINNING OF THIS CONTROLLER HOME - ");
$this->initialize();
printf("TROLLING THE END OF THIS CONTROLLER HOME - ");
//TODO : CONSIDER CREATING A LIBRARY TO AVOID WRITING THIS OFTEN
}
Index calls initialize who verify if the user has already a session variable with username in it. If that's the case, we would proceed to check his level of privileges, etc, and load corresponding view. Thats not the problem.
If the session is not started, I want to load the "login" view, called here "home_invite". And I want to redirect him to that page. But if I use this code, the page will show a 404 error.
If I use $this->load->view('home_invite'), it works, but I don't understand and I feel it isn't what I want it to do.
Why is redirect not working in this context?

Using the redirect() method redirects to a URL. You therefore need to pass it a full URL (as it uses the header() function which according to the RFC for HTTP1.1 requires a full URL.
This means that you can use
redirect(site_url('home_invite'));
Which will redirect your user to http://www.yoursite.com/home_invite
This means that you must have a controller called home_invite available as you can't load a view from the URL. Equally you could create a method in your existing controller and use the routes.php file to masquerade /your_controller/home_invite as /home_invite
The site_url() function is also part of the URL helper you've already included to use redirect().
If you don't want to use site_url(), you could just as well hard code the URL in like
redirect('http://www.yoursite.com/home_invite');

Related

Laravel Auth return to index

Can I redirect to the previous page someone if not logged in? Also, is it possible to create a hierarchy system for users?
I tried this:
if(!(Auth::check())) {
header("Location: {{ route('cooperado.index') }});
}
But i not even got an error message, just doesn't work. I'm starting at laravel so it's kind of hard to fully understand how it works.
Using Constructor in controller
You also can use middleware in order to redirect unauthenticated user back or somewhere else.
public method __construct(){
$this->middleware('auth');
}
Add this code in your controller so all methods within particular controller
-direct from route defination
Route::get('/path/',controller#method)->name('cooperado.index')->middleware('auth');
Redirection
using this method unauthenticated user will redirect to login page.
in order to edit redirection page you can change '#redirectTo' method
in
app/Http/Middleware/Authenticate.php
file.
if(!(Auth::check())) {
return redirect()->route('cooperado.index');
}
You mention in your question also wants to return previous page then use following but i'm not recommended this because if your first login effort fails then login failed' page becomes your previous page and second login effort succeeds then you are redirected to login page again because it's your previous page.
return Redirect::to(URL::previous());
You can use this. Is the easiest way to do this.
And you can also pass message, will displayed on when user redirect back from main page.
if(!Auth::check) {
return Redirect::back()->with('error','Please Login');
}

CodeIgniter - Select controller based on database

I'm building a simple CMS using Code Igniter version 3.0.0
The site's URLs are all customizable by the user and so do not follow the standard MVC structure of /controller/method/parameter-1/parameter-2/. Instead, all frontend traffic gets directed to PublicController's index method. This method searches the database for the current URL to return the correct page, and also the page type. Each page type corresponds to a controller.
How do I call that controller from the PublicController without doing a redirect?
I can't use the redirect() method because that would change the URL in the browser window and cause an un-need additional page request.
if you look at the url /about/who-we-are/
about is the controller and who-we-are is a function in the controller that loads one or more views.
The same for /locations/stores/
the functions stores in the controller locations.
read the documentation and it will be easy to understand.
http://www.codeigniter.com/user_guide/overview/mvc.html
I am pretty sure that configuring a route is your answer:
// routes.php
$route['(:any)'] = "PublicController/index/$1";
// PublicController.php
public function index()
{
var_dump(func_get_args());
}

Incorrect routing via /config/routes.php

I have the following (basic) route set up in a CI-based web app:
$route['sms/resend/(:num)/(:any)'] = 'sms/resend/$1/$2';
The controller + 'resend' method:
class Sms extends CI_Controller {
public function resend($to, $message) {
// my code
}
}
Logically speaking, anything that doesn't fit the route should be directed to a 404 page instead of the resend() method within the sms controller. This isn't the case, however. The following URL, for example, isn't redirected correctly, it goes to the same controller+method:
http://myapp/sms/resend/uuuu/WhateverMessage
What could be the problem?
After a bit of digging, I've come to understand that CI's default routing does not get deactivated when a default route related to a specific controller/method pair is added. That being said, if a URL does not fit the route $route['sms/resend/(:num)/(:any)'] = 'sms/resend/$1/$2', then the same URL is run through CI's default routing mechanism as a fallback, so it still takes me to the resend method of the sms controller. To prevent this from happening, I needed to add another custom route that follows all others related to the sms resending, that redirects any other url to a different controller+method. If this controller doesn't exist, you get the default 404 page.
So the final /config/routes.php file:
$route['sms/resend/(:num)/(:any)'] = 'sms/resend/$1/$2';
$route['sms/checkoperator/(:num)'] = 'sms/checkoperator/$1';
$route['sms/(:any)'] = 'somewhereovertherainbow';
I think the rout file is just for rerouting. Your URL don't fits the routing Conditions so it don't gets rerouted! So it goes the normal way wich is the same (in this case!)
Something like this could work!
(! :num) /(:any) '] = error page (or not existing page)
So every request wich doesn't start with a number gets redirected to the error page!
The syntax might be wrong!
This would work great :
$route['sms/resend/[^0-9]/(:any)'] = 'errorpage';
You have to replace the error page by something ;)

Codeigniter shorten urls

Is it possible to create such urls in codeigniter?
http://site.com/shorturl/
Where shorturl isn't a physical controller file, but a variable.
I expect the algorythm for parsing url query to be like this:
1) Search for physical controller file. If exists, do standard codeigniter routine. If not
2) Try to load special controller file, where "shorturl" is a variable. Do further stuff inside that controller.
Thanks in advance
The previous answer seems quite good, but thought I'd share what I'd though of.
If you set your 404_override to point to a controller you have set up as follows:
$route['404_override'] = 'welcome/short';
Any URL that doesn't exist (any short URL for example) would get sent there, where you could do the following to check the value:
public function short() {
$shortCode = $this->uri->segment(1);
}
That would give you the value you need to check. If all is well, do the redirect, if the code doesn't exist, you can then use the show_404 method to actually show the 404 page.

what the diffence beetween forward and redirect or setRenderView in Zend framework? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between redirect and forward in Zend framework
I'm new to zend framework, when i try to use foward, redirect, setViewRender in controller, what are their diffences?
As the official docs say:
_forward($action, $controller = null, $module = null, array $params = null): perform another action. If called in preDispatch(), the
currently requested action will be skipped in favor of the new one.
Otherwise, after the current action is processed, the action
requested in _forward() will be executed.
_redirect($url, array $options = array()): redirect to another location. This method takes a URL and an optional set of options. By
default, it performs an HTTP 302 redirect.
Read more to understand it better.
i'm pretty sure that a redirect redirects you to a particular page/ controller therefore going through all of the pre view processes including if you can view the page, setViewRender will just output the view you have selected and disregard all of the stuff the controller etc handles. (i haven't used zend for a while however)
_redirect creates a completely new http request, where as _forward simply forwards the request. I realized this when setting a variable in zend_registry, well this might sound a little off the track but when you use _request all the request variables and headers and registry variables are completely reset where as in case of _forward it simply forwards all those things. This is like you can have previously provided information along with some more information in case of _forward.
Well for setViewRenderer I really like this idea, I mean this is something like dependency injection. You dont really need to have a default view, you could provide a new view for the given action. I think you would get the best answer if you look into this.
_forward is an internal redirect. Where as _redirect sends a header that tells the client's browser to go to some other URL, _forward tells the Dispatcher to internally redirect the request somewhere else.
If you consider the normal dispatch order of:
preDispatch()
someAction()
anotherAction()
postDispatch()
Calling _forward at any point in that progression will cause the following steps to not be executed. So if you call _forward in preDispatch(), someAction() will not be called and so on. If you _forward() in someAction() and you are using the viewRenderer action helper to render your views (you are letting the framework choose what view script to render), then no view script will be rendered in someAction().
When the request is forwarded to the new Controller / Module the entire dispatch process will be repeated there.
Note:
If you forward inside someAction() to anotherAction() you must do it like this
return $this->_forward('another');
You should add a return to $this->_forward() or your current Action will continue to execute before forwarding to the other Action.
Also note that the view that will be rendered will be another.phtml
While when doing a redirect, ZF would instruct the browser to load http://example.com/controller-name/action-name as _redirect() sends a header, meaning you create a new HTTP Request and go through the entire dispatch process with it.
Last to render a certain view inside an action use the viewRenderer Action helper:
// Bar controller class, foo module:
class Foo_BarController extends Zend_Controller_Action
{
public function addAction()
{
// Render 'bar/form.phtml' instead of 'bar/add.phtml'
$this->_helper->viewRenderer('form');
}
public function editAction()
{
// Render 'bar/form.phtml' instead of 'bar/edit.phtml'
$this->_helper->viewRenderer->setScriptAction('form');
}
public function processAction()
{
// do some validation...
if (!$valid) {
// Render 'bar/form.phtml' instead of 'bar/process.phtml'
$this->_helper->viewRenderer->setRender('form');
return;
}
// otherwise continue processing...
}
}

Categories