0

我正在尝试使用 PHP 创建一个基本的 REST 样式 API,但我遇到了一个奇怪的问题。当我通过 URL /rest/viewinput.php 访问我的一个页面(viewinput.php)时,页面加载正常。当我尝试通过 /rest/viewinput 时,我收到“找不到页面”错误。

因此,这是确定请求类型以及将其发送到何处的代码。这是在我的 server.php 页面上找到的

//in server.php
public function serve() {
    $uri = $_SERVER['REQUEST_URI'];
    $method = $_SERVER['REQUEST_METHOD'];
    $paths = explode('/', $this->paths($uri));
    array_shift($paths); // 
    $resource = array_shift($paths);

if ($resource == 'rest') {
        $page = array_shift($paths);
        if (empty($page)) {
            $this->handle_base($method);
    } else {
    $this->handle_page($method, $page);
        }

    }
    else {
        // We only handle resources under 'clients'
        header('HTTP/1.1 404 Not Found');
    } 
}

由于它是一个带有确定页面名称的 GET 方法,因此它将传递给此函数

//in server.php
private function handle_page($method, $page) {
    switch($method) {  

    case 'GET':
    if($page == "viewinput"){ //I have both viewinput.php and viewinput just to check both. Only viewinput.php works
       $this->display_info();
    }
     if($page == "viewinput.php"){
       $this->display_info();
    }

    default:
        header('HTTP/1.1 405 Method Not Allowed');
        header('Allow: GET, PUT, DELETE');
        break;
    }
}

然后从这里发送到

//in server.php
function display_info(){
$view = new ViewInputs(); 
$view->view();  //this function is on viewinput.php
}

因此,当我访问 /rest/viewinput.php 时,视图功能会正确显示。当我访问 /rest/viewinput 时,我收到“断开的链接”错误。

我按照在线教程找到了一个 REST 服务器Found Here,它工作得很好。

以下在我的 httpd.conf 文件中

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^/.* rest/server.php

这是我的 viewinput.php 文件。我相信它工作正常(当页面加载时,server.php 上的 serve 函数应该运行。

<?
include_once 'server.php';
class ViewInputs{

  function view(){
      $sql = mysql_query("select * from entry");
      ?> 
      <table>
          <th>ID</th>
          <th>Text</th>
          <col width="200">
          <col width="150">
        <?
        while ($result = mysql_fetch_array($sql)){
            ?>
            <tr><td><? echo $result['id']." "; ?></td><td><? echo $result['text']; ?></td></tr>
            <?
        }
        ?> </table> <?
    }
}
$server = new server();
$server->serve(); 
?>

来自 httpd.conf。我可能错了,但我相信这是允许 .htaccess 文件的方法

DocumentRoot "C:/xampp/htdocs/rest"

<Directory />
   Options FollowSymLinks
   AllowOverride ALL
   Order deny, allow
   Deny from none
</Directory>

<Files ".ht*">
Require all ALLOW
</Files>
4

1 回答 1

1

您的重写规则未正确编写。发生的事情是,当您转到 rest/viewinput.php 时,该文件实际上存在,因此它能够运行。当您去休息/查看输入时,该文件不存在。您可以通过访问http://martinmelin.se/rewrite-rule-tester/检查您的重写规则,您会发现您的重写规则不好。

这样做的目的是让您没有 veiwinput.php 文件,所有内容都应该直接发送到 server.php 文件。您想要的重写规则很可能是这样的:

RewriteRule rest/* rest/server.php

如果你想真正去 viewinput.php 有一个重写规则根本没有意义,只是摆脱它。

如果您希望将 rest/viewinput 视为 rest/viewinput.php,请使用以下命令:

RewriteRule ^rest/([a-z]+) rest/$1.php
于 2012-09-05T17:37:31.530 回答