Let my application run on localhost, the path is: localhost/silex/web/index.php
, defined routes as in the code below, I'd expect visiting localhost/silex/web/index.php/redirect
redirects me to localhost/silex/web/index.php/foo
and displays 'foo'. Instead it redirects me to localhost/foo
.
I am new to Silex and maybe I got it all wrong. Could someone explain where is the problem? Is it correct behavior and it should redirect for absolute paths? Thanks.
<?php
require_once __DIR__.'/../vendor/autoload.php';
use Symfony\Component\HttpFoundation\Response;
$app = new Silex\Application();
$app['debug'] = true;
$app->get('/foo', function() {
return new Response('foo');
});
$app->get('/redirect', function() use ($app) {
return $app->redirect('/foo');
});
$app->run();
The redirect
url expects an url to redirect to, not an in-app route. Try it this way:
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
$app->get('/foo', function() {
return new Response('foo');
})->bind("foo"); // this is the route name
$app->get('/redirect', function() use ($app) {
return $app->redirect($app["url_generator"]->generate("foo"));
});
For internal redirects, which does not change the requested URL, you can also use a sub-request:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
$app->get('/redirect', function() use ($app) {
$subRequest = Request::create('/foo');
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
});
See also Making sub-Requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With