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;
相关推荐
kyriewen17 小时前
Anthropic 估值逼近万亿美元,Claude Sonnet 5 + Claude Science 一天两连发
前端·ai编程·claude
小徐_233318 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
天蓝色的鱼鱼21 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
泯泷21 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花21 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷21 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
团团崽_七分甜21 小时前
Spring Boot 核心知识点总结
前端
lichenyang4531 天前
从一个按钮开始,理解 ASCF 框架到底在做什么
前端
古夕1 天前
第三方 SSO 接入实践:redirect_uri 编码、回调一致性与跨项目联调
前端·vue.js