我有一个返回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;
我遇到的问题是页面已经加载并运行了一个脚本,它已经返回了一个200Http代码,如果登录脚本失败或者我捕捉到一个异常,我需要它返回一个404Not found http代码。
https://stackoverflow.com/questions/50650762
复制相似问题