You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP API如何实现URL路径传studentId获取学生欠费数据

PHP实现路径段形式传参方案

要实现http://localhost/api/getOutstandingBill/GC2022A0021格式的路径传参,只需完成两步配置:

1. 配置Web服务器重写规则

直接访问无.php后缀的路径时,服务器默认无法定位到实际处理文件,需要添加重写规则把路径请求转发到对应的PHP脚本:

  • 若使用Apache服务:
    在项目的api目录下新建.htaccess文件,写入以下规则:
    RewriteEngine On
    # 跳过真实存在的文件、目录请求,避免静态资源被误转发
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    # 把getOutstandingBill/后的路径内容转发给getOutstandingBill.php处理
    RewriteRule ^getOutstandingBill/(.+)$ getOutstandingBill.php?path_param=$1 [L,QSA]
    
  • 若使用Nginx服务:
    找到站点对应的Nginx配置文件,在server配置块中添加以下规则,保存后重载Nginx配置即可生效:
    location /api/ {
        rewrite ^/api/getOutstandingBill/(.+)$ /api/getOutstandingBill.php?path_param=$1 last;
    }
    

2. 修改PHP代码解析路径参数

原代码通过$_GET['studentId']读取查询参数,现在调整为优先读取重写传递的路径参数,同时保留对原有查询参数格式的兼容,避免旧调用方受影响。另外原代码存在SQL注入风险,同步做了安全修复,修改后的完整代码如下:

<?php
require_once '../db_config/config.php';
require_once './class/bills.php';
require_once 'jwt_utils.php';

header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json; charset=UTF-8');
header("Access-Control-Allow-Methods: GET");

$database = new Database();
$db = $database->getConnection();
$item = new OutstandingBill($db);

$item->studentid = '';
// 优先读取路径段传参
if (isset($_GET['path_param']) && !empty(trim($_GET['path_param']))) {
    $item->studentid = trim($_GET['path_param']);
} 
// 兼容原有查询参数传参格式
elseif (isset($_GET['studentId']) && !empty(trim($_GET['studentId']))) {
    $item->studentid = trim($_GET['studentId']);
}
// 未传必填参数直接返回400错误
if (empty($item->studentid)) {
    echo json_encode([
        'success' => false,
        'message' => "Missing required studentId parameter",
        'error_code' => 400
    ]);
    die();
}

$bearer_token = get_bearer_token();
$is_jwt_valid = is_jwt_valid($bearer_token);

if ($is_jwt_valid) {
    // 对传入参数做转义,避免SQL注入,若使用PDO建议改用预处理参数绑定
    $safe_student_id = mysqli_real_escape_string($db, $item->studentid);
    $query = "SELECT * FROM tblbills WHERE student_id = '$safe_student_id'";
    $studentExist = dbQuery($query);

    if (dbNumRows($studentExist) > 0) {
        $outstandingBill = [];
        $sql = "SELECT * FROM tblbills WHERE student_id='$safe_student_id'";
        $result = dbQuery($sql);

        while ($row = dbFetchAssoc($result)) {
            $outstandingBill = [
                'student_id' => $row['student_id'],
                'full_name' => $row['full_name'],
                // 'department' => $row['departmentid']
                'payment_type' => $row['payment_type'],
                'amount' => $row['amount'],
                'discount_percent' => $row['discount_percent'],
                'status' => $row['status'],
                'invoice_number' => $row['invoiceid'],
                'due_year_month' => $row['billdate'],
            ];
        }

        echo json_encode([
            'success' => true,
            'message' => "The outstanding payment for student $item->studentid",
            'data' => [$outstandingBill]
        ]);
    }
    else {
        echo json_encode([
            'success' => false,
            'message' => "There is NO student with id number $item->studentid",
            'error_code' => 404
        ]);
    }
}
else {
    echo json_encode([
        'success' => false,
        'message' => "Please provide a valid token",
        'error_code' => 401
    ]);
}
?>

配置完成后直接访问目标路径格式的接口即可正常返回响应,原有的查询参数格式接口也可正常使用。

注意:如果后续需要扩展更多路径段形式的接口,可以把重写规则调整为通用规则,统一把请求转发到入口文件做路由分发,不需要为每个接口单独写重写规则。

内容的提问来源于stack exchange,提问作者Emmon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 16:39:19