如何获得与cURL一起发送的帖子字段来休息api?

时间:2017-04-27 00:32:56

标签: php rest curl

我正在用php构建一个简单的restful api。我可以读取使用GET发送的数据,但不能读取使用POST发送的数据。

$json_array=array(
    "userId"=>'',
    "refId"=>f(alea()),
    "name"=>f($name),
    "status"=>'0'
    );
$insert = api("MyLists","POST","insertLists",$json_array);

发送请求的Api函数:

 function api() {
global $apiKey;
global $apiURL;
// GET
$tab = func_get_args();
if($tab[1] == 'POST') {
    // POST
    $tab = func_get_args();
    global $apiKey;
    global $apiURL;
    $url = $apiURL.$tab[0]."/".$apiKey."/".$tab[2];
    $data = $tab[3];
    $data_string = json_encode($data);
    $rCURL = curl_init();
    curl_setopt($rCURL, CURLOPT_URL, $url); 
    curl_setopt($rCURL, CURLOPT_POST, 1);                                                                     
    curl_setopt($rCURL, CURLOPT_POSTFIELDS, $data_string);                                                                  
    curl_setopt($rCURL, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($rCURL, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($data_string))                                                                       
    );                                                                                                                                                                                                                   
    $aData = curl_exec($rCURL);
    curl_close($rCURL);
    return json_decode($aData);
}
else {
    $url = $apiURL.$tab[0]."/".$apiKey."/".$tab[1];
    $i=2;
    while(isset($tab[$i]))  {
        $url.="/".$tab[$i];
        $i++;
    }
    // return $url;
    $rCURL = curl_init();
    curl_setopt($rCURL, CURLOPT_URL, $url);
    curl_setopt($rCURL, CURLOPT_HEADER, 0);
    curl_setopt($rCURL, CURLOPT_RETURNTRANSFER, 1);
    $aData = curl_exec($rCURL);
    curl_close($rCURL);
    return json_decode($aData);
}
}

Php函数接收请求: AbstractApi.php

header("Access-Control-Allow-Orgin: *");
header("Access-Control-Allow-Methods: *");
header("Content-Type: application/json");
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$method = $_SERVER['REQUEST_METHOD'];
if($method == "GET" || $method == "POST") {
    $type=$_GET['type']."API";
    if(file_exists("./".$type.".php")) {
        require_once("./".$type.".php");
        if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
                    $_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
        }
        try {
            $API = new $type($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
             echo json_encode($API->processAPI());
        } catch (Exception $e) {
            echo json_encode(Array('error' => $e->getMessage()));
        }
    }
    else { 
        echo json_encode(Array('error' => "Invalid Type"));
    }
}
else {
    echo json_encode(Array('error' => "Only accepts GET/POST requests"));
}

Api.php

    abstract class API
{
    /**     * Property: method     * The HTTP method this request was made in, either GET, POST, PUT or DELETE     */
    protected $method = '';
    /**     * Property: endpoint     * The Model requested in the URI. eg: /files     */
    protected $endpoint = '';
    /**     * key app     */
    protected $key = '';
    /**     * Property: args     * Any additional URI components after the endpoint and verb have been removed, in our     * case, an integer ID for the resource. eg: /<endpoint>/<verb>/<arg0>/<arg1>     * or /<endpoint>/<arg0>     */
    protected $args = Array();
    /**     * Property: file     * Stores the input of the PUT request     */
    protected $file = Null;
    /**     * Constructor: __construct     * Allow for CORS, assemble and pre-process the data     */
    protected $db = Null;
    protected $db2 = Null;

    public function nf($str) {
    $newStr = $str;
            if(!(strpos($newStr,'@eg_@')=== false))
               $newStr=str_replace("@eg_@","\\",$newStr);

            if(!(strpos($newStr,'@xx_@')=== false))
               $newStr=str_replace("@xx_@","/",$newStr);

            if(!(strpos($newStr,'@kx_@')=== false))
               $newStr=str_replace("@kx_@",'"',$newStr);

            if(!(strpos($newStr,'@bw_@')=== false))
               $newStr=str_replace("@bw_@",'',$newStr); 
            if(!(strpos($newStr,'@er_@')=== false))
               $newStr=str_replace("@er_@",'&egrave;',$newStr); 
            if(!(strpos($newStr,'@ec_@')=== false))
               $newStr=str_replace("@ec_@",'&eacute;',$newStr); 

      return  $newStr;
    }


    public function verifiedAPI($entry) {

          $createurs = $this->db->query("SELECT * FROM apikey");
          foreach( $createurs as  $value ) {
                 if($entry == $value['Value_Key']) return true;
          }
            return false;
    }

    // public function verifyGET($entry) {
         // if ($entry != 'GET') 
            // return "Only accepts GET requests";
    // }


    public function __construct($request)
    {

        $this->db = new DB();
        $this->db2 = new DB2();

        $this->args     = explode('/', rtrim($request, '/'));

        $this->key      = array_shift($this->args);
            if(!$this->verifiedAPI($this->key) ) 
             throw new Exception('Invalid API Key');    

        $this->endpoint = array_shift($this->args);
        $this->method   = $_SERVER['REQUEST_METHOD'];
        if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
            if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
                $this->method = 'DELETE';
            } else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
                $this->method = 'PUT';
            } else {
                throw new Exception("Unexpected Header");
            }
        }
        switch ($this->method) {
            case 'DELETE':
            case 'POST':
                $this->request = $this->_cleanInputs($_POST);
                break;
            case 'GET':
                $this->request = $this->_cleanInputs($_GET);
                break;
            case 'PUT':
                $this->request = $this->_cleanInputs($_GET);
                $this->file    = file_get_contents("php://input");
                break;
            default:
                $this->_response('Invalid Method', 405);
                break;
        }
    }
    function __destruct() {
         $this->db->CloseConnection(); 
    }
    public function useDAO() {
        $type = $_GET['type'];
        $nameFunc = array_shift($this->args);
        $daoType =  'get'.$type.'DAO';
        if($nameFunc == "insert") {
          $obj = new $type();
            $arr = json_decode($this->args[0]);

            foreach($arr as $key => $value) {
                 $obj->$key = $this->nf($value);
            }
            $args = array($obj);
        } else {
            if($nameFunc == "update") {
                  $arr1 = json_decode($this->args[0],"1");           
                  $id = $arr1['id'];    
                  $transaction2 = new Transaction();
                  $result = DAOFactory::$daoType()->load($id);
                  $transaction2->commit();          

                  foreach($arr1 as $key => $value) {                
                         $result->$key = $this->nf($value);
                    }
                    $args = array($result);
            }
            else
              $args = $this->args;
        }
        $transaction = new Transaction();
        $obj = DAOFactory::$daoType();              
        $res = call_user_func_array(array($obj,$nameFunc), $args);
        $transaction->commit();

                // Problem : Need To Always Return Array , so Can't make the difference between existing (true) or not 
                // INSERT DELETE UPDATE : returns always the array of [isValid] attribute
                // SELECT : returns the array of data  OR  the array of error attribute 
        if($res==false) return array("error" => "Error : False return" );
        else {
                if(!is_array($res) && !is_object($res) ) 
                    return ( array("value" => $res) );
              return $res;
        }
    }

    public function processAPI()
    {
        if (method_exists($this, $this->endpoint)) {
            return $this->{$this->endpoint}($this->args);
        }
        return $this->_response('No Endpoint: ' . $this->endpoint, 404);
    }
    private function _response($data, $status = 200)
    {
        header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
        return json_encode($data);
    }
    private function _cleanInputs($data)
    {
        $clean_input = Array();
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                $clean_input[$k] = $this->_cleanInputs($v);
            }
        } else {
            $clean_input = trim(strip_tags($data));
        }
        return $clean_input;
    }
    private function _requestStatus($code)
    {
        $status = array(
            200 => 'OK',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            500 => 'Internal Server Error'
        );
        return ($status[$code]) ? $status[$code] : $status[500];
    }
}

现在,对于GET请求,我在PHP类中使用$ this-&gt; args来检索param并将其用于我的函数。但是当我使用POST时,我得到NULL作为回报,我在这个发布的脚本中检查了很多,但我没有找到检索Post字段的解决方案。 Thx提前:))

1 个答案:

答案 0 :(得分:0)

你能尝试使用curl_setopt($ rCURL,CURLOPT_CUSTOMREQUEST,&#34; POST&#34;);而不是curl_setopt($ rCURL,CURLOPT_POST,1);在api函数中?,

OtherWise你可以使用file_get_contents设置一些选项,如:

$data_string = json_encode($data);

$result = file_get_contents($apiURL.$tab[0]."/".$apiKey."/".$tab[2], null, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/json' . "\r\n"
. 'Content-Length: ' . strlen($data_string) . "\r\n",
'content' => $data_string,
),
)));