Daniel Robinson
Daniel Robinson

Reputation: 653

Returning http 404 with CURL in PHP

I have a function that returns a json_encoded string. All works great however if the function returns an error I would like to throw the error through a http 404 error response back to the page. Is this possible?

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
 }

Then from another page I'm using curl to fire a json string to the page

$url = "mydomain.com";
$content = '{"App": "67759d99-772b-4d53-af65-3ef714285594", "Email": "[email protected]", "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;

The problem I'm having is as the page has already loaded and ran a script its already returned a 200 http code when if the login script fails or I catch an exception I need it to return a 404 not found http code.

Upvotes: 1

Views: 363

Answers (1)

hanshenrik
hanshenrik

Reputation: 21493

just defer transmitting the response to after you're already sure about whether or not you got an error. the Output Control Functions, in particular ob_start()/ob_get_clean()/ob_end_flush() are often helpful with that, eg

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

Upvotes: 1

Related Questions