Reputation: 91
Ok, I creating blog, just for learn php. And when I try redirect page after Sign in or sign up, I use header("Location: /") for example, for redirect to home page of blog. And it's work only when I use var_dump()... This my code, help pls
This method from Mediator, which send response for user and here headers added.
/**
* @param ResponseInterface $response
*/
public function sendResponse(ResponseInterface $response)
{
$response->addHeaders();
var_dump($response->getHeaders());
http_response_code($response->getStatusCode());
if ($response->getStatusCode() !== 200) {
die($response->getContent());
}
echo $response->getContent();
}
This method from controller with sign up
/**
* @return ResponseInterface
* @throws \ReflectionException
* @throws \core\FileNotFoundException
*/
public function signInAction()
{
$authForm = $this->createAuthForm();
if ($authForm->load()) {
if ($authForm->isValid() && $authForm->login()) {
return new SuccessResponse('Welcome!',[ '0' => 'Location: /',]);
}
ErrorsCheckHelper::setError('Wrong login or password');
return $this->renderLogin();
}
return $this->renderLogin();
}
And this is my class for response which I used in this case
namespace response;
class SuccessResponse implements ResponseInterface{
/** @var int */
protected $statusCode = 200;
/** @var string */
protected $content;
/** @var array */
protected $headers;
/**
* SuccessResponse constructor.
* @param $headers
* @param $content
*/
public function __construct(string $content, array $headers = array())
{
$this->headers = $headers;
$this->content = $content;
}
/**
* @return array
*/
public function getHeaders(): array
{
return $this->headers;
}
/**
* @return string
*/
public function getContent(): string
{
return $this->content;
}
/**
* @param string $content
*/
public function setContent(string $content): void
{
$this->content = $content;
}
/**
* @return int
*/
public function getStatusCode(): int
{
return $this->statusCode;
}
/**
* @param array $headers
*/
public function setHeaders(array $headers)
{
array_merge($this->headers, [$headers]);
}
public function addHeaders()
{
if (!empty($this->headers)) {
foreach ($this->headers as $header) {
header($header);
}
}
return;
}
}
Upvotes: 0
Views: 49
Reputation: 3526
The values of the headers that you want to set should be indexed by their name, not by a numeric value or other string, so where you had this:
return new SuccessResponse('Welcome!',[ '0' => 'Location: /',]);
try using:
return new SuccessResponse('Welcome!',[ 'Location: /']);
Upvotes: 1
Reputation: 91
Oh, just whaaaaat..... I fix code like this and it's start work
/**
* @param ResponseInterface $response
*/
public function sendResponse(ResponseInterface $response)
{
http_response_code($response->getStatusCode());
if ($response->getStatusCode() !== 200) {
$response->addHeaders();
die($response->getContent());
}
$response->addHeaders();
echo $response->getContent();
}
Upvotes: 0