-
Notifications
You must be signed in to change notification settings - Fork 144
/
router.php
111 lines (108 loc) · 2.67 KB
/
router.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
function get($route, $path_to_include)
{
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
route($route, $path_to_include);
}
}
function post($route, $path_to_include)
{
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
route($route, $path_to_include);
}
}
function put($route, $path_to_include)
{
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
route($route, $path_to_include);
}
}
function patch($route, $path_to_include)
{
if ($_SERVER['REQUEST_METHOD'] == 'PATCH') {
route($route, $path_to_include);
}
}
function delete($route, $path_to_include)
{
if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
route($route, $path_to_include);
}
}
function any($route, $path_to_include)
{
route($route, $path_to_include);
}
function route($route, $path_to_include)
{
$callback = $path_to_include;
if (!is_callable($callback)) {
if (!strpos($path_to_include, '.php')) {
$path_to_include .= '.php';
}
}
if ($route == "/404") {
include_once __DIR__ . "/$path_to_include";
exit();
}
$request_url = filter_var($_SERVER['REQUEST_URI'], FILTER_SANITIZE_URL);
$request_url = rtrim($request_url, '/');
$request_url = strtok($request_url, '?');
$route_parts = explode('/', $route);
$request_url_parts = explode('/', $request_url);
array_shift($route_parts);
array_shift($request_url_parts);
if ($route_parts[0] == '' && count($request_url_parts) == 0) {
// Callback function
if (is_callable($callback)) {
call_user_func_array($callback, []);
exit();
}
include_once __DIR__ . "/$path_to_include";
exit();
}
if (count($route_parts) != count($request_url_parts)) {
return;
}
$parameters = [];
for ($__i__ = 0; $__i__ < count($route_parts); $__i__++) {
$route_part = $route_parts[$__i__];
if (preg_match("/^[$]/", $route_part)) {
$route_part = ltrim($route_part, '$');
array_push($parameters, $request_url_parts[$__i__]);
$$route_part = $request_url_parts[$__i__];
} else if ($route_parts[$__i__] != $request_url_parts[$__i__]) {
return;
}
}
// Callback function
if (is_callable($callback)) {
call_user_func_array($callback, $parameters);
exit();
}
include_once __DIR__ . "/$path_to_include";
exit();
}
function out($text)
{
echo htmlspecialchars($text);
}
function set_csrf()
{
session_start();
if (!isset($_SESSION["csrf"])) {
$_SESSION["csrf"] = bin2hex(random_bytes(50));
}
echo '<input type="hidden" name="csrf" value="' . $_SESSION["csrf"] . '">';
}
function is_csrf_valid()
{
session_start();
if (!isset($_SESSION['csrf']) || !isset($_POST['csrf'])) {
return false;
}
if ($_SESSION['csrf'] != $_POST['csrf']) {
return false;
}
return true;
}