首页 > 解决方案 > 在 PHP 中使用 CURL 返回 http 404

问题描述

我有一个返回 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 not found http 代码。

标签: phpcurl

解决方案


在您已经确定是否有错误之后,只需推迟发送响应即可。,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();

推荐阅读