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;
相关推荐
「QT(C++)开发工程师」4 分钟前
C++ auto 用法详解
开发语言·c++
OPEN-F11 分钟前
C++STL教程:容器适配器与实用工具
开发语言·c++
yaoxin52112322 分钟前
507. Java 反射 - 在 BeanFactory 中实现依赖注入
java·开发语言
OPEN-F29 分钟前
C++模板教程:变参模板、折叠表达式与SFINAE
java·开发语言·c++
有点。31 分钟前
C++二叉搜索树进阶
开发语言·c++
HugoStudio_SWAN35 分钟前
【擦除重绘】C++ 控制台动画:弹跳 Logo DVD 屏保效果
开发语言·c++·学习·程序人生
2601_962074681 小时前
自己编译RustDesk,并将自建ID服务器和key信息写入客户端
运维·服务器
kyriewen1 小时前
我装了30多个Skill,给AI安排了8个岗位
前端·javascript·ai编程
风骏时光牛马2 小时前
大模型落地实践中的技术选型思路与方案对比
前端
大模型丫丫2 小时前
Hermes Agent:轻量级智能体框架实战指南
大数据·运维·服务器