REST API - 我在这里做错了什么?

时间:2016-02-04 05:46:28

标签: php json api rest http

我可以显示成功代码但由于某种原因我无法显示错误代码。每当我将响应代码从0更改为1,2,3等等时,它就会给我“HTTP 500错误”。

我在这里做错了什么?

enter image description here

我无法解决这个问题,请帮我解决这个问题。

这是我的PHP API代码

<?php
    function deliver_response($format, $api_response){
        header('HTTP/1.1 '.$api_response['status'].' '.$api_response['code'] );
        if( strcasecmp($format,'json') == 0 ){
            header('Content-Type: application/json; charset=utf-8');
            $json_response = json_encode($api_response);
            echo $json_response;
        }
        exit;
    }

    // Settings
    $authentication_required = TRUE;

    // Success and errors codes. Always there status with success or error. If error then there is code and reason. 
    $api_response_code = array(
        0 => array('status' => 200),
        1 => array('status' => 'error', 'code' => 'UNSUPPORTED_METHOD'),
        2 => array('status' => 'error', 'code' => 'URL_PARSE_FAIL'),
        3 => array('status' => 'error', 'code' => 'EMPTY_QUERY'),
        4 => array('status' => 'error', 'code' => 'AUTH_REQUIRED'),
        5 => array('status' => 'error', 'code' => 'AUTH_FAILED'),
        6 => array('status' => 'error', 'code' => 'EMPTY_COMMAND'),
        7 => array('status' => 'error', 'code' => 'UNKNOWN_COMMAND')
    );

    // Default HTTP response of 'success'.
    $response['code'] = 0;
    $response['status'] = $api_response_code[ $response['code'] ]['status'];

    // User authentication
    if( $authentication_required ){
        if( empty($_GET['password']) ){
            $response['code'] = 4;
            $response['status'] = $api_response_code[ $response['code'] ]['status'];
            $response['data'] = $api_response_code[ $response['code'] ]['code'];
            deliver_response($_GET['format'], $response);
        }

        // Return an error response if user fails authentication
        elseif( $_GET['password'] != '123' ){
            $response['code'] = 5;
            $response['status'] = $api_response_code[ $response['code'] ]['status'];
            $response['data'] = $api_response_code[ $response['code'] ]['code'];
            deliver_response($_GET['format'], $response);
        }
    }

    // Hello World
    if( strcasecmp($_GET['method'],'hello') == 0){
        $response['code'] = 0;
        $response['status'] = $api_response_code[ $response['code'] ]['status'];
        $response['data'] = 'Hello World';
    }

    if($_GET['cmd']) {
        $response['code'] = 7;
        $response['status'] = $api_response_code[ $response['code'] ]['status'];
        $response['data'] = $api_response_code[ $response['code'] ]['code'];
    }
    // Return response to browser
    deliver_response($_GET['format'], $response);

?>

感谢。

0 个答案:

没有答案