Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a97df5b

Browse files
committed
Clean up php server code (don't use switch in routing)
1 parent b81c6e7 commit a97df5b

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

server.php

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,25 +17,23 @@
1717
function routeRequest()
1818
{
1919
$comments = file_get_contents('comments.json');
20-
switch($_SERVER["REQUEST_URI"]) {
21-
case '/':
22-
echo file_get_contents('./public/index.html');
23-
break;
24-
case (preg_match('/comments.json*/', $_SERVER["REQUEST_URI"]) ? true : false):
25-
if($_SERVER['REQUEST_METHOD'] === 'POST') {
26-
$commentsDecoded = json_decode($comments, true);
27-
$commentsDecoded[] = ['author' => $_POST['author'],
28-
'text' => $_POST['text']];
20+
$uri = $_SERVER['REQUEST_URI'];
21+
if ($uri == '/') {
22+
echo file_get_contents('./public/index.html');
23+
} elseif (preg_match('/\/comments.json(\?.*)?/', $uri)) {
24+
if($_SERVER['REQUEST_METHOD'] === 'POST') {
25+
$commentsDecoded = json_decode($comments, true);
26+
$commentsDecoded[] = ['author' => $_POST['author'],
27+
'text' => $_POST['text']];
2928

30-
$comments = json_encode($commentsDecoded, JSON_PRETTY_PRINT);
31-
file_put_contents('comments.json', $comments);
32-
}
33-
header('Content-Type: application/json');
34-
header('Cache-Control: no-cache');
35-
echo $comments;
36-
break;
37-
default:
38-
return false;
29+
$comments = json_encode($commentsDecoded, JSON_PRETTY_PRINT);
30+
file_put_contents('comments.json', $comments);
31+
}
32+
header('Content-Type: application/json');
33+
header('Cache-Control: no-cache');
34+
echo $comments;
35+
} else {
36+
return false;
3937
}
4038
}
4139

0 commit comments

Comments
 (0)