首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在PHP中使用CURL返回http 404

在PHP中使用CURL返回http 404
EN

Stack Overflow用户
提问于 2018-06-02 04:44:02
回答 1查看 205关注 0票数 1

我有一个返回json_encoded字符串的函数。但是,如果函数返回错误,我希望通过http 404错误响应将错误抛回页面。这个是可能的吗?

代码语言:javascript
复制
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字符串发送到该页面

代码语言:javascript
复制
$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代码。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50650762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档