添加mod重写的路径

时间:2015-08-14 19:27:13

标签: php apache .htaccess mod-rewrite

我在获取正确使用mod_rewrite的链接方面遇到了一些问题。我试图让路径http://localhost/input.php/colors/1起作用,但它只适用于http://localhost/input.php/colors。下面是我的htaccess文件代码和php代码(包括两者,因为我不知道两者是否都需要)。

    <IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^([^/]+)/(.+)$ Api.php?rquest=$1&id=$2 [QSA,NC,L]


RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^([^/]+)/(.+)$ Api.php?rquest=$1&id=$2 [QSA,NC,L]


RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^([^/]+)/(.+)$ Api.php?rquset=$1&id=$2 [QSA,NC,L] 

</IfModule>

这是Rest.php的php代码:

class Rest
{
    public $allow = array();

    public $content_type = "application/json";

    public $request = array();

    private $method = '';

    private $code = 200;


public function __construct()
{
    $this->inputs();
}


public function getReferer() 
{
    return $_SERVER['HTTP_REFERER'];
}


public function response($data, $status)
{
    $this->code = ($status) ? $status : 200;

    $this->setHeaders();

    echo $data;

    exit;
}


private function getStatusMessage() 
{
    $status = array(
        100 => 'Continue',
        101 => 'Switching Protocols',
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        306 => '(Unused)',
        307 => 'Temporary Redirect',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported');

    return ($status[$this->code]) ? $status[$this->code] : $status[500];
}


public function getRequestMethod()
{
    return $_SERVER['REQUEST_METHOD'];
}


private function inputs()
{
    switch ($this->getRequestMethod()) {
        case "POST":
            $this->request = $this->cleanInput($_POST);
            break;

        case "GET":
        case "DELETE":
            $this->request = $this->cleanInput($_GET);
            break;

        case "PUT":
            parse_str(file_get_contents("php://input"), $this->request);

            $this->request = $this->cleanInput($this->request);
            break;

        default:
            $this->response('', 406);
            break;
    }
}


private function cleanInput($data)
{
    $clean = array();

    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $clean[$key] = $this->cleanInput($value);
        }
    } else {
        if (get_magic_quotes_gpc()) {
            $data = trim(stripslashes($data));
        } 

        $data = strip_tags($data);
        $clean = trim($data);
    }

    return $clean;
}


private function setHeaders()
{
    header('HTTP/1.1 ' . $this->code . ' ' . $this->getStatusMessage());
    header('Content-Type:' . $this->content_type);
}

}

这是Api.php的代码

require_once 'Rest.php';


 class Api extends Rest
 {
public $data = "";

public $id;

const DB_SERVER = 'localhost';
const DB_USER = 'root';
const DB_PASS = '';
const DB_NAME = 'upwork';

private $dbh = null;



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

    $this->dbConnect();
}

private function dbConnect()
{
    $this->dbh = new PDO("mysql:dbname=" . self::DB_NAME . ";host=" . self::DB_SERVER, self::DB_USER, self::DB_PASS);

    if ($this->dbh instanceof PDO) {
        return $this->dbh;
    }

    return false;
}


public function processAPI()
{
    $function = strtolower(trim(str_replace("/", "", $_REQUEST['rquest'])));
    $id = $_REQUEST['id'];

    if ((int)method_exists($this, $function) > 0) {
        $this->$function();
        $this->id = $id;
    } else {
        $this->response('', 404); // method not found
    }
}


private function login()
{

  require_once 'login.php';


  if ($_POST['submit']) {
      // validate input
      $username = trim(stripslashes(strtolower($_POST['username'])));
      $password = trim(stripslashes(strtolower($_POST['password'])));


      if (!empty($username) && !empty($password)) {
          $sql = $this->dbConnect()->query("SELECT username, password, full_name, session_cookie FROM user WHERE username = '$username' AND password = '$password' LIMIT 1");

          $result = $sql->fetch(PDO::FETCH_ASSOC);

          if (!empty($result['username']) && !empty($result['password'])) {
              // all good to go
              $this->response($this->encodeJson($result), 200);
          } else {
              // no records abort
              $this->response($this->encodeJson(array('status' => 'Failed', 'msg' => 'Can\'t find your info in the db')), 204);
          }
       }

       // if invalid input, display error message
       $error = array('status' => 'Failed', 'msg' => 'Invalid username or password');

       $this->response($this->encodeJson($error), 400);
   }
}


private function colors()
{
    if ($this->getRequestMethod() == "GET") {
        if (!empty($this->request['id'])) {
            // fetch color based on id
            $id = (int)$this->request['id'];

            if ($id > 0) {
                $sql = $this->dbConnect()->query("SELECT id, name, red, green, blue FROM color WHERE id = $id");

                $result = $sql->fetchAll(PDO::FETCH_ASSOC);

                if (count($result, 0) > 0) {
                    // good to go
                    $this->response($this->encodeJson($result), 200);
                } else {
                    $this->response($this->encodeJson($result), 204);
                }
            } else {
                $this->response($this->encodeJson('', 204));
            }
        } else {
            // fetch all colors
            $sql = $this->dbConnect()->query("SELECT id, name, red, green, blue FROM color");

            $result = $sql->fetchAll(PDO::FETCH_ASSOC);

            if (count($result, 0) > 0) {
                // good to go
                $this->response($this->encodeJson($result), 200);
            } else {
                $this->response($this->encodeJson('', 204));
            }
        }
    } else if ($this->getRequestMethod() == "POST") {
        require_once 'addcolor.php';

        if ($_POST['submit']) {
            if (!empty($_POST['cname']) && !empty($_POST['red']) && !empty($_POST['green']) && !empty($_POST['blue'])) {
                $insert = $this->dbConnect()->exec("INSERT INTO color (name, red, green, blue) VALUES ('" . $_POST['cname'] . "', 
                    red = '" . $_POST['red'] . "', green = '" . $_POST['green'] . "', blue = '" . $_POST['blue'] . "')");

                if ($insert > 0) {
                    $success = array('status' => 'Success', 'msg' => 'Successfully added color.');

                    $this->response($this->encodeJson($success), 200);
                }
            } else {
                $this->response('', 204);
            }
        }
    }
}


private function deleteColor()
{
    if ($this->getRequestMethod() != "DELETE") {
        $this->response('', 406);
    }

    $id = (int)$this->request['id'];

    if ($id > 0) {
        $sql = $this->dbConnect()->exec("DELETE FROM color WHERE id = $id");

        if ($sql > 0) {
            $success = array('status' => 'Success', 'msg' => 'Successfully deleted color.');

            $this->response($this->encodeJson($success), 200);
        } else {
            // no records found
            $this->response('', 204);
        }
    }
}


private function putColor() 
{
    if ($this->getRequestMethod() != "PUT") {
        $this->response('', 406);
    }

    $id   = (int)$this->request['id'];
    $name = $this->request['name'];
    $r    = $this->request['r'];
    $g    = $this->request['g'];
    $b    = $this->request['b'];

    if ($id > 0) {
        $sql = $this->dbConnect()->exec("UPDATE color SET name = '" . $name . "', red = $r, green = $g, blue = $b WHERE id = $id");

        if ($sql > 0) {
            $success = array('status' => 'Success', 'msg' => 'Successfully updated color');

            $this->response($this->encodeJson($success), 200);
        } else {
            // no records found
            $this->response('', 204);
        }
    }
}


private function encodeJson($data)
{
    // encode array into json
    if (is_array($data)) {
        return json_encode($data, JSON_PRETTY_PRINT);
    }
}
}

    $api = new Api();

    $api->processAPI();

出于某种原因,id未设置或未正确路由。任何帮助,将不胜感激。基本上我要做的是以下内容:

验证

POST /input.php/login 输入:用户,通过 输出:user,pass,full_name + session cookie或者如果user / pass不存在则失败

编辑颜色:

获取/input.php/colors 得到所有颜色 输出:[id,name,r,g b]

列表

获取/input.php/colors/ID 得到颜色细节 输出:id,name,r,g b

POST /input.php/colors 添加新颜色 输入:name,r,g,b

PATCH(PUT)/input.php/colors/ID 更新颜色细节 输入:name,r,g,b

DELETE /input.php/colors/ID 删除颜色

1 个答案:

答案 0 :(得分:1)

你需要实际进行第二次捕获以使用$ 2.

RewriteRule ^([^/]+)/(.+)$ Api.php?rquest=$1&id=$2 [QSA,NC,L]