<?php
# Author - Fedor Vlasenko, vlasenkofedor@gmail.com
define('METHOD', $_SERVER['REQUEST_METHOD']);
define('URI', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
function router($url, ...$args)
{
(empty($args[1]) || false !== strpos(METHOD, $args[0]))
&& (URI === $url || preg_match('#^' . $url . '$#iu', URI, $match))
&& die(call_user_func_array(end($args), $match ?? []));
}
router('/api/games', 'GET', function () {
echo 'список игрушек';
});
router('/api/game/(\d+)', 'GET', function (...$args) {
echo 'информация о игрушке: ', $args[1];
});
router('/api/games', 'POST', function () {
echo 'добавить новую игрушку';
});
router('/api/games/(\d+)', 'PUT', function (...$args) {
echo 'обновить существующую игрушку: ', $args[1];
});
router('/api/games/(\d+)', 'DELETE', function (...$args) {
echo ' удалить игрушку: ', $args[1];
});
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
echo '404';
<?php
$method = $_SERVER['REQUEST_METHOD'];
$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
switch ($method) {
case 'PUT':
do_something_with_put($request);
break;
case 'POST':
do_something_with_post($request);
break;
case 'GET':
do_something_with_get($request);
break;
default:
handle_error($request);
break;
}
<?php
// Headers
header('Access-Control-Allow-Origin: http://localhost:3000');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: *');
header('Content-Type: application/json');
// Connect to db
$connect = mysqli_connect('localhost', 'root', 'root', 'f-mania');
// If connect error
if (!$connect) {
echo mysqli_connect_error();
die();
}
// Split url into array
$params = explode('/', $_GET['url']);
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
if ($params[0] == 'account') {
// ...
}
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($params[0] == 'account') {
if ($params[1] == 'login') {
// ...
} elseif ($params[1] == 'recover') {
// ...
} elseif ($params[1] == 'reset') {
// ...
} elseif ($params[1] == 'register') {
// ...
}
}
} elseif ($_SERVER['REQUEST_METHOD'] == 'PUT') {
// ...
} elseif ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
// ...
}
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-F
RewriteRule ^(.+)$ index.php?url=$1 [L,QSA]