Skip to content

Commit 8dc95f2

Browse files
committed
Merge pull request reactjs#26 from AndyMathys/php-server
2 parents 558e0c7 + 2945ece commit 8dc95f2

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,9 @@ python server.py
2424
ruby server.rb
2525
```
2626

27+
### PHP
28+
```sh
29+
php server.php
30+
```
31+
2732
And visit <http://localhost:3000/>. Try opening multiple tabs!

server.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
$scriptInvokedFromCli =
3+
isset($_SERVER['argv'][0]) && $_SERVER['argv'][0] === 'server.php';
4+
5+
if($scriptInvokedFromCli) {
6+
echo 'starting server on port 3000' . PHP_EOL;
7+
exec('php -S localhost:3000 -t public server.php');
8+
} else {
9+
return routeRequest();
10+
}
11+
12+
function routeRequest()
13+
{
14+
$comments = file_get_contents('_comments.json');
15+
switch($_SERVER["REQUEST_URI"]) {
16+
case '/':
17+
echo file_get_contents('./public/index.html');
18+
break;
19+
case '/comments.json':
20+
if($_SERVER['REQUEST_METHOD'] === 'POST') {
21+
$commentsDecoded = json_decode($comments, true);
22+
$commentsDecoded[] = ['author' => $_POST['author'],
23+
'text' => $_POST['text']];
24+
25+
$comments = json_encode($commentsDecoded);
26+
file_put_contents('_comments.json', $comments);
27+
}
28+
header('Content-Type: application/json');
29+
echo $comments;
30+
break;
31+
default:
32+
return false;
33+
}
34+
}
35+

0 commit comments

Comments
 (0)