[PHP]Slim3でリダイレクトを行う

カテゴリ: SlimFramework

PHPのSlim3 Frameworkで302リダイレクトを行いたい場合があります。

Slim3でリダイレクトを行うときは、下記のように$response->withRedirect()メソッドを利用すればよいです。

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app = new \Slim\App($settings);
$app->get('/linkto', function (Request $request, Response $response) {
    return $response->withRedirect('http://www.yahoo.co.jp/');
});

$app->run();

Slim3におけるwithRedirect()メソッドの実装

withRedirect()メソッドの実態は、vendor\slim\slim\Slim\Http\Response.phpにて、以下のように定義されています。

namespace Slim\Http;

class Response extends Message implements ResponseInterface
    ...

    public function withRedirect($url, $status = null)
    {
        $responseWithRedirect = $this->withHeader('Location', (string)$url);

        if (is_null($status) && $this->getStatusCode() === 200) {
            $status = 302;
        }

        if (!is_null($status)) {
            return $responseWithRedirect->withStatus($status);
        }

        return $responseWithRedirect;
    }

一目で見て分かるように、渡されたURLでLocationのHTTPヘッダを指定したうえで、302のステータスコードを設定しているだけです。
ステータスコードを変更したい場合は、第二引数で指定することが可能です。


Amazonでおトクに買い物する方法
AmazonチャージでポイントGET


Amazonは買いもの前にAmazonギフト券をチャージしてポイントをゲットしないと損!

こちらもおススメ

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です