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;
相关推荐
@不误正业11 小时前
2026-05-16-多Agent协作框架深度实战-从ReAct到Plan-and-Execute全架构演进
前端·react.js·架构
Reload.11 小时前
CZ航司,shopping JS逆向 acw_sc__v2
开发语言·javascript·python·网络爬虫·ecmascript
码界筑梦坊11 小时前
130-基于Python的体育用品销售数据可视化分析系统
开发语言·python·信息可视化·flask·毕业设计
咖喱o11 小时前
IPv6
服务器·前端·网络
海上彼尚11 小时前
Nodejs也能写Agent - 6.基础篇 - Agent
前端·人工智能·后端·node.js
IpdataCloud11 小时前
IP查询工具怎么选?在线API vs IP离线库:精度、速度、成本、隐私全对比
服务器·网络·数据库
码界筑梦坊11 小时前
131-基于Flask的美国新泽西州自动售货机销售数据可视化分析系统
开发语言·python·信息可视化·数据分析·flask·毕业设计
努力努力再努力wz11 小时前
【QT入门系列】QWidget 六大常用属性详解:windowOpacity、cursor、font、focus、toolTip 与 styleSheet
android·开发语言·数据结构·c++·qt·mysql·算法
Harm灬小海11 小时前
【云计算学习之路】学习Centos7系统:Linux磁盘管理
linux·运维·服务器·学习·云计算