2014-11-06 46 views
1

我想創建一個restful API唯一的問題是,我無法獲得$ _REQUEST值。相同的代碼在本地主機上正常工作,但不在服務器上。這可能是由於我的htaccess代碼。當URL processApi API調用此API的功能由URL

稱爲例如被稱爲找出功能 http://www.domain.com/file.php/api/test

現在我試圖調用test功能是api

htaccess的代碼重定向我的網址

api類中的第一項功能是processApi那請檢查是否測試功能存在或不

但是這裏面processApi功能$ _REQUEST值爲null

這是發生在服務器,但在本地主機上它做工精細

這是htaccess的代碼

<IfModule mod_rewrite.c> 
    RewriteEngine On 

    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} !-s 
    RewriteRule ^(.*)$ file.php?request=$1 [QSA,NC,L] 

    RewriteCond %{REQUEST_FILENAME} -d 
    RewriteRule ^(.*)$ file.php [QSA,NC,L] 

    RewriteCond %{REQUEST_FILENAME} -s 
    RewriteRule ^(.*)$ file.php [QSA,NC,L] 

</IfModule> 

這是API代碼

class API extends REST 
{    
    private $db = NULL; 

    public function __construct() 
    { 
     parent::__construct(); 
    } 

    public function processApi() 
    { 
     $func = strtolower(trim(str_replace("api/","",$_REQUEST['request']))); 

     if((int)method_exists($this,$func) > 0) 
     { 
        $this->$func(); 
     } 
     else 
     {    
       $error = array('status' => '402', "msg" => 'function not exist'); 
       $this->response($this->json($error), 402); 
     } 
    } 
    } 

    $api = new API; 
    $api->processApi(); 

通過運行此代碼到服務器上我得到了

{"status":"402","msg":"function not exist"} 

只是因爲$ _REQUEST [ '請求']是空

請點我爲什麼我的get $_REQUEST['request'] = NULL。我的htaccess代碼是否給出正確的值$_REQUEST['request']

+0

你試過'var_dump($ func)'?如果它應該像你期望的那樣是'test',那麼爲什麼你的API類沒有函數'test'呢? – 2014-11-06 08:45:40

+0

另外,請記住,PHP不具有對PUT或DELETE請求等內容的本機支持。爲了讓她獲得數據,你需要調用'parse_str(file_get_contents('php:// input'),$ _DATA)',這會將傳遞給服務器的任何數據放在$ _DATA變量中。 – Jhecht 2014-11-06 09:31:12

回答

1

您應該看看PHP的$_SERVER變量而不是$_REQUEST

$_SERVER['REQUEST_URI'] should give you the correct URI for /api/test 

在$ _ SERVER運行var_dump爲您提供有關當前請求(並且正在處理它的服務器環境)

希望這有助於更多的信息!

+0

非常感謝..它解決了我的問題...感謝很多frend ..... – ELITE 2016-05-09 16:12:38

0

這可能是由於您的上一條規則在您的第一條規則之後運行所致。改變你的代碼是這樣的:

<IfModule mod_rewrite.c> 
    RewriteEngine On 

    # skip after rewriting first time 
    RewriteCond %{ENV:REDIRECT_STATUS} !^$ 
    RewriteRule^- [L] 

    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} !-s 
    RewriteRule ^(.*)$ file.php?request=$1 [QSA,L] 

    RewriteCond %{REQUEST_FILENAME} -d [OR] 
    RewriteCond %{REQUEST_FILENAME} -s 
    RewriteRule . file.php [L] 

</IfModule> 
+0

首先感謝您的答案,但不幸的是,在更改'htaccess'代碼與您的代碼後,我仍然得到'$ _REQUEST ['request '''''processApi()'函數中的空值 – user3713959 2014-11-06 21:12:16

+0

將您的file.php重命名爲其他內容並使用以下代碼創建一個新的file.php:'<?php print_r($ _ GET); ?>'告訴我它打印的是什麼 – anubhava 2014-11-06 21:17:54