2011-04-04 41 views
8

PUT請求我有一個問題,現在使用CodeIgniter:我用的是REST Controller library(這是真正真棒)來創建一個API,但我不能讓PUT請求......得到與笨

這是我的代碼:

function user_put() { 
    $user_id = $this->get("id"); 
    echo $user_id; 
    $username = $this->put("username"); 
    echo $username; 
} 

我使用curl發出請求:

curl -i -X PUT -d "username=test" http://[...]/user/id/1 

的user_id是滿員,但是用戶名變量是空的。但它適用於動詞POST和GET。 你有什麼想法嗎?

謝謝!

+0

嘿@Shatter你有沒有得到一個機會來驗證這一點? – jcolebrand 2013-03-11 17:20:34

+0

仍有越野車,$ this-> put('anything')返回false – Syl 2013-10-28 14:45:33

回答

10

據:http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/我們應諮詢https://github.com/philsturgeon/codeigniter-restserver/blob/master/application/libraries/REST_Controller.php#L544地看到,這個方法:

/** 
* Detect method 
* 
* Detect which method (POST, PUT, GET, DELETE) is being used 
* 
* @return string 
*/ 
protected function _detect_method() { 
    $method = strtolower($this->input->server('REQUEST_METHOD')); 

    if ($this->config->item('enable_emulate_request')) { 
    if ($this->input->post('_method')) { 
     $method = strtolower($this->input->post('_method')); 
    } else if ($this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE')) { 
     $method = strtolower($this->input->server('HTTP_X_HTTP_METHOD_OVERRIDE')); 
    }  
    } 

    if (in_array($method, array('get', 'delete', 'post', 'put'))) { 
    return $method; 
    } 

    return 'get'; 
} 

看,看看我們是否已經定義HTTP頭HTTP_X_HTTP_METHOD_OVERRIDE,它使用的是有利於實際動詞,我們已經在網絡上實施。要在請求中使用它,您可以指定標頭X-HTTP-Method-Override: method(如此X-HTTP-Method-Override: put)以生成自定義方法覆蓋。有時框架期望X-HTTP-Method而不是X-HTTP-Method-Override,因此這取決於框架。

如果你正在做的通過jQuery這樣的要求,你將這個塊集成到您的Ajax請求:

beforeSend: function (XMLHttpRequest) { 
    //Specify the HTTP method DELETE to perform a delete operation. 
    XMLHttpRequest.setRequestHeader("X-HTTP-Method-Override", "DELETE"); 
} 
-1

CodeIgniter不支持讀取傳入的PUT請求,如果它不是必需的,我會堅持爲您的API GET/POST,因爲它可能沒有必要。

如果您確實需要閱讀PUT請求,請查看Accessing Incoming PUT Data from PHP

+0

這可能在2011年4月份準確,但目前尚不準確。 – jcolebrand 2012-06-25 16:12:10

2

你可以嘗試檢測方法類型的第一和獨立的不同的情況。如果您的控制器僅處理REST函數,則可以在構造函數中獲取所需信息。

switch($_SERVER['REQUEST_METHOD']){ 
    case 'GET': 
     $var_array=$this->input->get(); 
     ... 
     break; 
    case 'POST': 
     $var_array=$this->input->post(); 
     ... 
     break; 
    case 'PUT': 
    case 'DELETE': 
     parse_str(file_get_contents("php://input"),$var_array); 
     ... 
     break; 
    default: 
     echo "I don't know how to handle this request."; 
}