How to pass data via withHeader('Location', ...)?

My scenario is like this:

  1. One goes to /test/create.
  2. If GET, redirect to /test and pass an array with information: Array('foo' => 'bar').
  3. /test should now be able to read this array somehow.

I’ve tried using this:

$app->get('/test', function($request, $response, $args) {
  $body = $request->getParsedBody();
  $foo = $body['foo'];

  echo $foo;
$app->get('/test/create', function($request, $response, $args) {
  return $response->withStatus(302)->withJson(array('foo' => 'bar'))->withHeader('Location', '/test');

But nothing seems to get passed to the $body. I am new to Slim, so I believe I am doing this completely wrong.

Thanks in advance,

I think it should be this…

return $response->withJson(array('foo' => 'bar'))->withRedirect('/test');

Although a much cleaner line, it made no noticeable difference. How do I retrieve the array?

It could be a PHP “feature”… To confirm you can var_dump the response… but I do not see why the body wouldn’t be dumped.

It does print $response if I only do print_r($response):

Slim\Http\Response Object
    [status:protected] => 200
    [reasonPhrase:protected] => 
    [protocolVersion:protected] => 1.1
    [headers:protected] => Slim\Http\Headers Object
            [data:protected] => Array
                    [content-type] => Array
                            [value] => Array
                                    [0] => text/html; charset=UTF-8
                            [originalKey] => Content-Type
    [body:protected] => Slim\Http\Body Object
            [stream:protected] => Resource id #63
            [meta:protected] => 
            [readable:protected] => 
            [writable:protected] => 
            [seekable:protected] => 
            [size:protected] => 

As you can see, no passed array. I am redirecting from /test/create using this:

return $response->withJson(array('foo' => 'bar'))->withRedirect('/test', 302);

Shouldn’t the $response status be 302 then? (still says 200 in the print above)

dump the body of the message. it will be in there

Dump what message? Can you give me an example code? Sorry, I am new to Slim.

$response = $response->withJson(array('foo' => 'bar'))->withRedirect('/test');

That won’t redirect me to /test. It will only print the array from /test/create.


Ok. This is why it is not going to work.

  1. You return a 302 with a Body.
  2. The browser goes, oh … ok. Then makes a new GET request to the place defined by your Location header.

If you want to transfer data, you will need to use a session or a cookie.

Thanks for the explanation. I solved it now with Flash messages instead.