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;
相关推荐
Nebula_g12 小时前
JavaSE项目实践:红包雨-线程池/线程
java·开发语言
外收内放12 小时前
Python基础语法练习题(56优化版补充)
开发语言·python
小羊没烦恼!12 小时前
jQuery1.5的改进细节
java·服务器·开发语言·前端·c#
独孤九剑打醒他12 小时前
【原创开源·修订版】源-栅-漏-栅-源横向双栅MOS:从“被误解的短路”到“电流路径多值逻辑与顶层供电架构”
前端·嵌入式硬件·架构·开源·硬件工程
阿狗童鞋12 小时前
React实战指南
前端·react.js·前端框架
程序员老陆12 小时前
C++ 未定义行为全景:对象模型、优化边界与工程防御
开发语言·c++·程序设计
v:ychya201813 小时前
独立站外贸建站公司怎么选?建站就要建营销型网站
前端·php
嵌入式er13 小时前
影石系统组 一二面OC面经
java·开发语言
徐小黑ACG13 小时前
Golang 基础06 接口interface
开发语言·后端·golang
春涧草茶13 小时前
慢就是快12-12手动抛出异常
java·linux·前端