如何使用rest api和php发送代码200和403

问题描述 投票:1回答:1

我使用php和restful api开发了一个小型Crud应用程序。如果要创建记录,我想发送代码200,而错误消息则发送代码403。下面是我的代码:

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];

$query = $restObj->create_record($firstname,$lastname,$age);
echo json_encode([
      "message" => $query ? "User Created" : "Error creating user"
]);

这是我创建记录的功能:

public function create_record($firstname,$lastname,$age)
{   
$sql = "INSERT INTO table1 (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";
$query = mysqli_query($this->conn,$sql);    
return $query;  
}

该代码工作正常,我可以创建记录,但是我不知道如何显示代码200和代码403消息。请帮助

php json rest restful-url
1个回答
0
投票

您可以使用http_response_code(200)获取并设置HTTP响应代码。

参考PHP Manual: http-response-code

© www.soinside.com 2019 - 2024. All rights reserved.