PHP - PHP 简易 Web 服务器、基础接口开发

一、PHP 简易 Web 服务器

1、基本介绍
  • PHP 自带一个简易的 Web 服务器,适合快速测试,启动方式如下
bash 复制代码
php -S 【监听地址】:【监听端口】
bash 复制代码
# 例如

php -S 127.0.0.1:8000
2、注意事项
  1. 通过以下方式启动,就需要通过 localhost 访问,而不能通过 127.0.0.1 访问
bash 复制代码
php -S localhost:8000
  1. 通过以下方式启动,就可以通过 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;
相关推荐
aramae3 小时前
模拟实现strcmp()(C语言)
c语言·开发语言·后端
Madison-No73 小时前
搭建项目测试环境
linux·运维·服务器·python
+VX:Fegn08953 小时前
计算机毕业设计|基于springboot + vue蛋糕店管理系统(源码+数据库+文档)
前端·数据库·vue.js·spring boot·课程设计
泡海椒4 小时前
PDF 表格样式优化:jquick-pdf 边框、圆角、背景色
java·开发语言·pdf
悠悠121384 小时前
微服务通信别只看性能:REST 与 gRPC 的 6 个选型判断和一次 502 故障复盘
运维·服务器
Beyond_System|系统之外5 小时前
【学编程】Python基础编程题100道(21-60)
开发语言·python·算法
Nicander5 小时前
我给 Excalidraw 做了一个本地工作区:DrawSpace
前端·开源
景熙55235 小时前
15.Java 8 Stream 流入门到实战
java·开发语言·数据结构
云老大-阿里云国际站代理商6 小时前
华为云国际站服务代理商:NAT网关怎么配?多台ECS共用公网IP要注意什么
服务器·华为云·云计算
linux_cfan6 小时前
17 · 引擎适配器全景:HLS/DASH/Vimeo/Mux/Cast
前端·javascript·音视频