Website/helpers.php

44 lines
956 B
PHP
Raw Normal View History

2023-03-21 17:23:14 +00:00
<?php
/**
* Helper for evaluating/including views
*/
function view(string $_view, array $_data = [])
{
$_path = __DIR__ . '/view/' . $_view . '.php';
extract($_data);
require $_path;
}
/**
* Helper for converting and outputting JSON
*/
function json_response(mixed $data, int $status_code = 200)
{
http_response_code($status_code);
header('Content-type: application/json');
echo json_encode($data);
}
/**
* Helper for reading and decoding JSON from request body
*/
function json_decode_input(): array|bool|null
{
return json_decode(file_get_contents('php://input'), true);
}
/**
* Helper for generating URLs
*/
function url(string $url, bool $full = false): string
{
$dir = dirname($_SERVER['SCRIPT_NAME']);
if ($dir === '/') {
$dir = '';
}
if (!$full) {
return $dir . $url;
}
return isset($_SERVER['HTTPS']) ? 'https' : 'http' . '://' . $_SERVER['HTTP_HOST'] . $dir . $url;
}