我有一个返回json_encoded字符串的函数。一切都很好但是如果函数返回错误我想通过http 404错误响应将错误抛回页面。这可能吗?
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-
Allow-Headers, Authorization, X-Requested-With");
include_once '../../config/database.php';
include_once '../../objects/functions.php';
include_once '../../objects/user.php';
try
{
$user = new user($db, $fn);
$response = file_get_contents("php://input");
$var = json_decode($response);
echo json_encode($user->userLogin($var->App, $var->Email,
$var->Pass));
}
catch(Exception $e)
{
//need to somehow throw a http 404 error here and cant use header ( "HTTP/1.0 401 Unauthorized" ); as the page is already loaded
}
然后从另一个页面我使用curl将json字符串激发到页面
$url = "mydomain.com";
$content = '{"App": "67759d99-772b-4d53-af65-3ef714285594", "Email": "me@example.com", "Pass":"example"}';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type:
application/json; charset=utf-8;"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$response = json_decode($json_response, true);
echo $json_response;
我遇到的问题是因为页面已经加载并运行了一个脚本,它已经返回了200个http代码,如果登录脚本失败或我捕获异常我需要它返回404找不到的http代码。
答案 0 :(得分:1)
在您确定是否收到错误后,只需将响应发送给您。 Output Control Functions
,特别是ob_start()/ ob_get_clean()/ ob_end_flush()通常对此有帮助,例如
ob_start();
include_once '../../config/database.php';
include_once '../../objects/functions.php';
include_once '../../objects/user.php';
try
{
$user = new user($db, $fn);
$response = file_get_contents("php://input");
$var = json_decode($response);
echo json_encode($user->userLogin($var->App, $var->Email,
$var->Pass));
}
catch(Exception $e)
{
http_response_code(404);
}
ob_end_flush();