Skip to content

Commit

Permalink
Clean up php server code (don't use switch in routing)
Browse files Browse the repository at this point in the history
  • Loading branch information
zpao committed May 12, 2015
1 parent b81c6e7 commit a97df5b
Showing 1 changed file with 16 additions and 18 deletions.
34 changes: 16 additions & 18 deletions server.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,23 @@
function routeRequest()
{
$comments = file_get_contents('comments.json');
switch($_SERVER["REQUEST_URI"]) {
case '/':
echo file_get_contents('./public/index.html');
break;
case (preg_match('/comments.json*/', $_SERVER["REQUEST_URI"]) ? true : false):
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$commentsDecoded = json_decode($comments, true);
$commentsDecoded[] = ['author' => $_POST['author'],
'text' => $_POST['text']];
$uri = $_SERVER['REQUEST_URI'];
if ($uri == '/') {
echo file_get_contents('./public/index.html');
} elseif (preg_match('/\/comments.json(\?.*)?/', $uri)) {
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$commentsDecoded = json_decode($comments, true);
$commentsDecoded[] = ['author' => $_POST['author'],
'text' => $_POST['text']];

$comments = json_encode($commentsDecoded, JSON_PRETTY_PRINT);
file_put_contents('comments.json', $comments);
}
header('Content-Type: application/json');
header('Cache-Control: no-cache');
echo $comments;
break;
default:
return false;
$comments = json_encode($commentsDecoded, JSON_PRETTY_PRINT);
file_put_contents('comments.json', $comments);
}
header('Content-Type: application/json');
header('Cache-Control: no-cache');
echo $comments;
} else {
return false;
}
}

0 comments on commit a97df5b

Please sign in to comment.