如何在PHP中使用CURL返回http 404?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (64)

我有一个函数返回一个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代码。

提问于
用户回答回答于

代码:

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();

扫码关注云+社区

领取腾讯云代金券