doumu6941 2014-11-07 20:59
浏览 69
已采纳

使用apache mod_rewrite实现的PHP POST到RESTful API

I created a PHP RESTful API following this example (code at the bottom). From what I understand, the API converts non-existing URI components to GET parameters in the address via the .htaccess file like this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule api/v1/(.*)$ api/v1/api.php?request=$1 [QSA,NC,L]
</IfModule>

So if I do, e.g.:

http://mysite/api/v1/endpoint1/param1

endpoint1/param1 can be parsed in the API implementation to call a PHP function endpoint1(param1).

Now my issue is, param1 is really long, and I want use AJAX to POST param1, but the POST doesn't go through

For example, for the RESTful API:

http://mysite/api/v1/endpoint1

I POSTed data using AJAX as follows:

$.post('http://mysite/api/v1/endpoint1/',data,callback,'json');

In API.class.php, $_SERVER['REQEUEST_METHOD'] is 'POST', but $_POST is empty array.

My questions are:

What is actually happening when I POST to a virtual URL to be handled by mod_rewrite. Is the end result a GET request by mode_rewrite or a POST request by my AJAX call?

How can I modify the code to get the POSTed data through? (Is it possible to ask mod_rewrite to use the POST method instead?)

I am confused here, any pointers are appreciated.


The interface for the relevant REST api is (API.class.php, please see the example for complete code):

<?php
abstract class API
{
    protected $method = '';
    protected $endpoint = '';
    protected $args = Array();
    protected $file = Null;
    public function __construct($request) {
        header("Access-Control-Allow-Orgin: *");
        header("Access-Control-Allow-Methods: *");
        header("Content-Type: application/json");
        $this->args = explode('/', rtrim($request, '/'));
        $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);
            $this->args[] = ???; //Problem line: how do I add post to the args 
            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;
        }
    }
    public function processAPI() {
        if ((int)method_exists($this, $this->endpoint) > 0) {
            return $this->_response($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]; 
    }
} 
?>
  • 写回答

1条回答 默认 最新

  • dongshengheng1013 2014-11-07 21:06
    关注

    I believe this is the issue you are running into: Is it possible to redirect post data?

    You should change this line in your .htaccess file from: RewriteRule api/v1/(.*)$ api/v1/api.php?request=$1 [QSA,NC,L]

    to: RewriteRule api/v1/(.*)$ api/v1/api.php?request=$1 [QSA,NC,P]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 不懂得怎么运行下载来的代码
  • ¥15 CST导出3D模型图为什么和软件显示不一样?
  • ¥15 加热反应炉PLC控制系统设计(相关搜索:梯形图)
  • ¥15 python 用Dorc包报错,我的写法和网上教的是一样的但是它显示无效参数,是什么问题
  • ¥15 经过滑动平均后的一维信号还原用什么结构好呢?
  • ¥15 指定IP电脑的访问设置
  • ¥30 matlab ode45 未发现警告,但是运行出错
  • ¥15 为什么devc++编译项目会失败啊
  • ¥15 vscode platformio
  • ¥15 代写uni代码,app唤醒