一、PHP 简易 Web 服务器
1、基本介绍
- PHP 自带一个简易的 Web 服务器,适合快速测试,启动方式如下
bash
php -S 【监听地址】:【监听端口】
bash
# 例如
php -S 127.0.0.1:8000
2、注意事项
- 通过以下方式启动,就需要通过 localhost 访问,而不能通过
127.0.0.1访问
bash
php -S localhost:8000
- 通过以下方式启动,就可以通过
127.0.0.1访问,也可以通过 localhost 访问
bash
php -S 127.0.0.1:8000
二、基础接口开发
1、GET 请求
test/testGet/index.php
php
<?php
header('Content-Type: text/plain');
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
echo 'Error: Only GET method is allowed';
exit;
}
echo "testGet Hello World";
exit;
2、GET 请求携带参数
test/testGetCarryData/index.php
php
<?php
header('Content-Type: text/plain');
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
echo 'Error: Only GET method is allowed';
exit;
}
$str = $_GET['str'];
echo "testGetCarryData " . $str;
exit;
3、RESTful GET 请求
test/testGetRestful/index.php
php
<?php
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
echo 'Error: Only GET method is allowed';
exit;
}
$path = explode('/', $_SERVER['REQUEST_URI']);
$id = (int) end($path);
class User
{
public $id;
public $name;
public $age;
public function __construct($id, $name, $age)
{
$this->id = $id;
$this->name = $name;
$this->age = $age;
}
}
$userMap = [
1 => new User(1, "jack", 10),
2 => new User(2, "tom", 20),
3 => new User(3, "smith", 30)
];
echo json_encode($userMap[$id], JSON_PRETTY_PRINT);
exit;
4、POST 请求
test/testPost/index.php
php
<?php
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo 'Error: Only POST method is allowed';
exit;
}
$json = file_get_contents('php://input');
$data = json_decode($json);
class User
{
public $id;
public $name;
public $age;
public function __construct($id, $name, $age)
{
$this->id = $id;
$this->name = $name;
$this->age = $age;
}
}
$userMap = [
1 => new User(1, "jack", 10),
2 => new User(2, "tom", 20),
3 => new User(3, "smith", 30)
];
echo json_encode($userMap[$data->id], JSON_PRETTY_PRINT);
exit;