Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Silex应用程序->;重定向与路由不匹配_Php_Redirect_Silex - Fatal编程技术网

Php Silex应用程序->;重定向与路由不匹配

Php Silex应用程序->;重定向与路由不匹配,php,redirect,silex,Php,Redirect,Silex,让我的应用程序在localhost上运行,路径是:localhost/silex/web/index.php,定义的路由如下面的代码所示,我希望访问localhost/silex/web/index.php/redirect将我重定向到localhost/silex/web/index.php/foo,并显示“foo”。相反,它将我重定向到localhost/foo 我是新来的Silex,也许我完全搞错了。有人能解释一下问题出在哪里吗?它的行为是否正确,是否应该重定向到绝对路径?谢谢 <?

让我的应用程序在localhost上运行,路径是:
localhost/silex/web/index.php
,定义的路由如下面的代码所示,我希望访问
localhost/silex/web/index.php/redirect
将我重定向到
localhost/silex/web/index.php/foo
,并显示“foo”。相反,它将我重定向到
localhost/foo

我是新来的Silex,也许我完全搞错了。有人能解释一下问题出在哪里吗?它的行为是否正确,是否应该重定向到绝对路径?谢谢

<?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();

重定向
url需要一个url重定向到,而不是应用程序内路由。试着这样做:

$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"));
});

对于不会更改请求的URL的内部重定向,您还可以使用子请求:

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);
});
另请参见。

“silex/silex”:“>=2.0”
,本机特性允许您基于路由名称生成URL

您可以替换:

$app['url_generator']->generate('my-route-name');
作者:

然后使用它重定向:

$app->redirect($app->path('my-route-name'));
另一种可能是创建一个自定义特征,用路由名称直接重定向:

namespace Acme;

trait RedirectToRouteTrait
{
    public function redirectToRoute($routeName, $parameters = [], $status = 302, $headers = [])
    {
        return $this->redirect($this->path($routeName, $parameters), $status, $headers);
    }
}
将特征添加到应用程序定义中:

use Silex\Application as BaseApplication;

class Application extends BaseApplication
{
    use Acme\RedirectToRouteTrait;
}
然后在需要的地方使用它:

$app->redirectToRoute('my-route-name');

我知道子请求,我只是想我可以这样做。谢谢你的回答。请你解释一下,我会用这个!:)是否可以从POST请求重定向到GET请求?是的,事实上,如果重定向,下一个请求将是GET,http规范定义了这一点。标量类型提示仅在PHP7中可用。您最好从代码片段中删除它们。
$app->redirectToRoute('my-route-name');