Can Symfony simply reload a page request? - php

I have an app that receives a request from another app. It detects a value on the query string, checks that value against a cached value and, if they don't match, it needs to clear its cache and reload the page (establishing a new cache). Unfortunately, I can't find a way to tell Symfony to redirect to the current page in exactly the same format (protocol, URI path, query string, etc.). What am I missing? This is all happening in a filter on isFirstCall().
Thanks.

We have done this in a filter.
It is a bit hacky but here is an example of doing the redirect in a filter...you'll have to do the testing of the cache yourself...
class invalidateCacheFilter extends sfFilter {
public function execute($filterChain) {
$redirect=true;
if($redirect===true)
{
$request = $this->getContext()->getRequest();
/**
This is the hacky bit. I am pretty sure we can do this in the request object,
but we needed to get it done quickly and this is exactly what needed to happen.
*/
header("location: ".$request->getUri());
exit();
}
$filterChain->execute();
}
}

If you want to redirect, you can do like this:
if (true===$redirect)
{
return $this->getContext()->getController()->redirect($request->getUri());
}

Related

Laravel testing redirect from function

If I have a function that checks to see if a string is numeric and redirects back if it is not but does nothing if it is ie
function check_numeric(string $param) {
if(!is_numeric($param)) {
return Redirect::back()->with('Failed', 'Number!');
}
}
How would I test this in PHPUnit? I have tried to use assertRedirect but I am not sure of how to implement it (if it is even possible)
To be clear. The check_numeric() function is a standalone function that is imported into controllers to be used by the different controller classes. The fucntion itself does not have a class nor a route.
What I would like to do is test the function directly without its use in a controller or route.
I can test the pass cases by doing:
$this->assertNull(check_numeric('1')); // does what I want!!
However I would also like to directly check the fail cases with something like
$previousUrl = '/';
$this->from($previousUrl)->(check_numeric('five'))->assertRedirect($previousUrl);
I think there is not automatic way to check if it's redirecting back, but you can build it.
To approaches comes to mind.
All samples assumed under phpunit, test extending Tests\TestCase;
1 - Check the URL before you make the request
$currentUrl = "/";
$response = $this->post('check-number', "five" );
$response->assertRedirect($currentUrl);
2 - Validate the message you're sending back when the validation fails.
$response = $this->post('/check-number', "five" );
$this->followRedirects($response)->assertSee('Failed');
YourController.php
function check_numeric(string $param) {
if(!is_numeric($param)) {
return Redirect::back()->with('Failed', 'Number!');
}
}
web.php
Route::post('/check-number', 'App\Http\Controllers\YourControllerController#check_numeric');
In the other hand, responding to your previous question, if you want to test the function directly, you have to go with what you're expecting, in this case you're not returning anything if everything is OK, so the way to go on that case would be:
$this->assertNull(app('App\Http\Controllers\YourControllerController')->check_numeric("five"));
This would fail, if you pass a number it would pass.
Doesthat help?

How to pass a data with redirect in codeigniter

In my controller i used this way. i want to pass a variable data to my index function of the controller through redirect
$in=1;
redirect(base_url()."home/index/".$in);
and my index function is
function index($in)
{
if($in==1)
{
}
}
But I'm getting some errors like undefined variables.
How can i solve this?
Use session to pass data while redirecting. There are a special method in CodeIgniter to do it called "set_flashdata"
$this->session->set_flashdata('in',1);
redirect("home/index");
Now you may get in at index controller like
function index()
{
$in = $this->session->flashdata('in');
if($in==1)
{
}
}
Remember this data will available only for redirect and lost on next page request. If you need stable data then you can use URL with parameter & GET $this->input->get('param1')
So in the controller you can have in one function :
$in=1;
redirect(base_url()."home/index/".$in);
And in the target function you can access the $in value like this :
$in = $this->uri->segment(3);
if(!is_numeric($in))
{
redirect();
}else{
if($in == 1){
}
}
I put segment(3) because on your example $in is after 2 dashes. But if you have for example this link structure : www.mydomain.com/subdomain/home/index/$in you'll have to use segment(4).
Hope that helps.
Use session to pass data while redirecting.There are two steps
Step 1 (Post Function):
$id = $_POST['id'];
$this->session->set_flashdata('data_name', $id);
redirect('login/form', 'refresh');
Step2 (Redirect Function):
$id_value = $this->session->flashdata('data_name');
If you want to complicate things, here's how:
On your routes.php file under application/config/routes.php, insert the code:
$route['home/index/(:any)'] = 'My_Controller/index/$1';
Then on your controller [My_Controller], do:
function index($in){
if($in==1)
{
...
}
}
Finally, pass any value with redirect:
$in=1;
redirect(base_url()."home/index/".$in);
Keep up the good work!
I appreciate that this is Codeigniter 3 question, but now in 2021 we have Codeigniter 4 and so I hope this will help anyone wondering the same.
CI4 has a new redirect function (which works differently to CI3 and so is not a like for like re-use) but actually comes with the withInput() function which does exactly what is needed.
So to redirect to any URL (non named-routed) you would use:
return redirect()->to($to)->withInput();
In your controller - I emphasise because it cannot be called from libraries or other places.
In the function where you are expecting old data you can helpfully use the new old() function. So if you had a key in your original post of FooBar then you could call old('FooBar'). old() is useful because it also escapes data by default.
If however, like me, you want to see the whole post then old() isn't helpful as the key is required. In that instance (and a bit of a cheat) you can do this instead:
print'<pre>';print_r($_SESSION['_ci_old_input']['post']);print'</pre>';
CI4 uses the same flash data methods behind the scenes that were given in the above answers and so we can just pull out the relevant session data.
To then escape the data simply wrap it in the new esc() function.
More info would be very helpful, as this should be working.
Things you can check:
Is your controller named home.php? Going to redirect(base_url()."home"); shows your home page?
Make your index function public.
public function index($in) {
....
}

Yii language control using behaviours how to prevent form resubmition dialog

I used this tutorial http://www.yiiframework.com/wiki/208/how-to-use-an-application-behavior-to-maintain-runtime-configuration/ to change language. But I ran into problem that $_Post['lang'] variable is not being reset and every time I try to refresh the page, It gives me form resubmition dialog, which I don't want to have. But I don't know where and how to use redirect, since it doesnt work in behaiours class. How can I prevent this form resubmition?
Edit: I found an ugly solution, to put this code in every view file that I have
<?php
$this->renderPartial('//lang/_refresh', array())
?>
But It involed repeating same code alot and I am sure there is a better solution out there (probably to place a refresh function in the right place)
Found a solution, all you need is to add a beforeAction to components/Controller since all added controllers extend it. The problem was I didn't know that. Here is the function that works so that I dont have to rewrite the code.
protected function beforeAction()
{
if (isset($_POST['lang'])) {
$this->refresh();
}
return true;
}

Redirect specific routes to page if they don't exist with laravel 4

I have a route that needs to be redirected to another page if the data they're pulling doesn't exist. The route is:
Route::get('{link}/{data}', 'LinkController#getLink');
Where {link} and {data} are model bound with:
Route::model('link', 'Link');
Route::model('data', 'Data');
As is, when the data for this link doesn't exist it 404's, and if it does exist, it's taken to the page as it should. What I would like to do is redirect to another page if the link would otherwise 404. I've found suggestions on how to do this globally, but I only want it to happen on this one route.
Any ideas?
// Link Controller
public function getLink($linkId, $dataId)
{
if ( is_null($link) or is_null($data) ) {
return Redirect::to('some/path');
}
}
If either of the passed models are null when it hits your controller method, just redirect them. As for your /{link} route that you refer to but don't show code for, do something similar in whatever closure/controller you handle that in.
Get rid of the model binding - you've left the cookie cutter realm.
Route::get('{link}/{data?}', 'LinkController#getLink');
// note I made the data ^ parameter optional
// not sure if you want to use it like this but it's worth pointing out
Do all of the model checking in the controller, something like this:
public function getLink($linkId, $dataId)
{
$link = Link::find($linkId);
$data = Data::find($dataId);
if(is_null($link)){
throw new NotFoundHttpException;// 404
}
elseif(is_null($data)){
return Redirect::to('some/view');// redirect
}
// You could also check for both not found and handle that case differently as well.
}
It's hard to tell from your comments exactly how you'd like to treat missing link and/or data records, but I'm sure you can figure that out logically. The point of this answer is that you don't need to use Laravel's model binding since you can do it yourself: find the record(s) else redirect or 404.

cakephp - callback function for every controller action to set available navigation links

I'm trying to achieve something so basic in my cakephp-app, that I'm quite surprised I didn't easily find a solution to it...
What I just want to do is to set available links for my app's main navigation depending on the user being logged in or not and if he is, depending on his role (which is stored in the users-table).
So basically a function like this:
if(!$this->request->is('ajax')) {
if(_user_is_not_logged_in_) {
$availableNavItems = array('login','help');
}
else {
if($this->Auth->User('role') == 'user') {
$availableNavItems = array('something','something else','whatever','help','logout');
}
elseif($this->Auth->User('role') == 'admin') {
$availableNavItems = array('something','something else','whatever','admin-tool','user management','help','logout');
}
}
// set available pages for layout
$this->set('availableNavItems',$availableNavItems);
}
In my layout of course I would create a navbar with links to those available pages.
The only question I have - where would I put code like the above? Is there any callback-function I could put in AppController which cakephp calls on every request?
And, what would be a good way to check what I wrote as pseudo-code "_user_is_not_logged_in_" above?
Thanks in advance for any help!
if(_user_is_not_logged_in_) {
could be written as
if(!$this->Auth->user('id')){
And you could put the function in your beforeRender method of your AppController, which executes on every request, right before the view is rendered.
Also of note is the beforeFilter method, which gets called early, before the controller logic executes. You shouldn't need it in this case, but it's worth knowing about.

Categories