This repository has been archived on 2025-02-26. You can view files and clone it, but cannot push or open issues or pull requests.
szurubooru/src/Helpers/HttpHelper.php

92 lines
2.1 KiB
PHP
Raw Normal View History

<?php
namespace Szurubooru\Helpers;
class HttpHelper
{
2015-06-28 10:07:11 +02:00
private $redirected = false;
2015-06-28 10:07:11 +02:00
public function setResponseCode($code)
{
http_response_code($code);
}
2015-06-28 10:07:11 +02:00
public function setHeader($key, $value)
{
header($key . ': ' . $value);
}
2015-06-28 10:07:11 +02:00
public function outputJSON($data)
{
$encodedJson = json_encode((array) $data);
$lastError = json_last_error();
if ($lastError !== JSON_ERROR_NONE)
$this->output('Fatal error while encoding JSON: ' . $lastError . PHP_EOL . PHP_EOL . print_r($data, true));
else
$this->output($encodedJson);
}
2015-06-28 10:07:11 +02:00
public function output($data)
{
echo $data;
}
2014-10-08 19:47:21 +02:00
2015-06-28 10:07:11 +02:00
public function getRequestHeaders()
{
if (function_exists('getallheaders'))
{
return getallheaders();
}
$result = [];
foreach ($_SERVER as $key => $value)
{
2015-11-25 09:48:03 +01:00
if (substr($key, 0, 5) === "HTTP_")
2015-06-28 10:07:11 +02:00
{
$key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
$result[$key] = $value;
}
else
{
$result[$key] = $value;
}
}
return $result;
}
2014-09-04 19:21:18 +02:00
2015-06-28 10:07:11 +02:00
public function getRequestHeader($key)
{
$headers = $this->getRequestHeaders();
return isset($headers[$key]) ? $headers[$key] : null;
}
2014-09-04 19:21:18 +02:00
2015-06-28 10:07:11 +02:00
public function getRequestMethod()
{
return $_SERVER['REQUEST_METHOD'];
}
2015-06-28 10:07:11 +02:00
public function getRequestUri()
{
$requestUri = $_SERVER['REQUEST_URI'];
$requestUri = preg_replace('/\?.*$/', '', $requestUri);
return $requestUri;
}
2015-06-28 10:07:11 +02:00
public function redirect($destination)
{
$this->setResponseCode(307);
$this->setHeader('Location', $destination);
$this->redirected = true;
}
2015-06-28 10:07:11 +02:00
public function nonCachedRedirect($destination)
{
$this->setResponseCode(303);
$this->setHeader('Location', $destination);
$this->redirected = true;
}
2015-06-28 10:07:11 +02:00
public function isRedirecting()
{
return $this->redirected;
}
}