在 php 中使用 REST api 时如何设置响应状态代码和消息?

How to set Response status code and message while using REST api in php?

product.php

<?php
class Product
{
    private $conn;
    private $table_name = "category";
    public $image_name;
    public $file_s;
    public function __construct($db){
        $this->conn = $db;
    }

    function read()
    {
        $query = "SELECT * FROM ".$this->table_name." order by category_name";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        return $stmt;
    }
}

read.php

<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    include_once 'dbase.php';
    include_once 'product.php';
    $database = new Database();
    $db = $database->getConnection();
    $product = new Product($db);
    $stmt = $product->read();
    $num = $stmt->rowCount();
    if($num>0)
    {
        $products_arr=array();
        $products_arr["data"]=array();
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
        {
            extract($row);
            $product_item=array(
                "image_name" => $image_name,
                "image_url" => $file_s
            );

            array_push($products_arr["data"], $product_item);
        }

        echo json_encode($products_arr);
    }

    else{
        echo json_encode(
            array("message" => "No products found.")
        );
    }
?>

我创建了一个简单的 REST api,它工作得很好,但现在的问题是我不知道如何使用 REST api 添加响应代码和响应消息在 php?

谢谢

这是将 HTTP 状态设置为 200 的方式:

header("HTTP/1.1 200 OK");

在你的代码中应用这个:

<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    header("HTTP/1.1 200 OK");
    include_once 'dbase.php';
    include_once 'product.php';
    $database = new Database();
    $db = $database->getConnection();
    $product = new Product($db);
    $stmt = $product->read();
    $num = $stmt->rowCount();
    if($num>0)
    {
        $products_arr=array();
        $products_arr["data"]=array();
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
        {
            extract($row);
            $product_item=array(
                "image_name" => $image_name,
                "image_url" => $file_s
            );

            array_push($products_arr["data"], $product_item);
        }

        echo json_encode($products_arr);
    }

    else{
        echo json_encode(
            array("message" => "No products found.")
        );
    }
?>

我认为它可以解决您的问题

回声json_encode( 数组("status"="404","message" => "No products found.") );

此处 状态 是您的响应代码。 您可以根据您的要求修改此响应代码

header("HTTP/1.1 200 OK"); // 这一行会将服务器响应设置为 200

header("HTTP/1.1 404 ERROR"); // 这将引发 404 错误。您可以将此代码更改为任何相应的代码