PHP 扩展 - 获取正确的 URI

最近在写的 Azalea MVC 框架中,类似 Zend Framework 根据 url 来获取 Controller Action 等参数。在开发环境中,我使用是 Mac 下自带的 Apache + php_mod 方式,该方式直接获取 $_SERVER['PATH_INFO'] 即可得到请求的 URI,代码如下

zval *server, *uri = NULL;
server = &PG(http_globals)[TRACK_VARS_SERVER];
if ((field = zend_hash_str_find(Z_ARRVAL_P(server), ZEND_STRL("PATH_INFO"))) && Z_TYPE_P(field) == IS_STRING) {
    uri = zend_string_copy(Z_STR_P(field));
}

然而在测试环境中,使用的是 Nginx + php_fpm 方式,不知为何 PATH_INFO 属性并不存在,参考鸟哥的 yaf,得到以下代码解决

#include "ext/standard/url.h" // for php_url_*

zval *server, *field, *uri = NULL;
server = &PG(http_globals)[TRACK_VARS_SERVER];
do {
    // 还是先找 PHP_INFO
    if ((field = zend_hash_str_find(Z_ARRVAL_P(server), ZEND_STRL("PATH_INFO"))) && Z_TYPE_P(field) == IS_STRING) {
        uri = zend_string_copy(Z_STR_P(field));
        break;
    }
    // 接着找 REQUEST_URI
    if ((field = zend_hash_str_find(Z_ARRVAL_P(server), ZEND_STRL("REQUEST_URI"))) && Z_TYPE_P(field) == IS_STRING) {
        if (strncasecmp(Z_STRVAL_P(field), ZEND_STRL("http://")) &&
                strncasecmp(Z_STRVAL_P(field), ZEND_STRL("https://"))) {
            // not http url
            char *pos = strstr(Z_STRVAL_P(field), "?");
            if (pos) {
                // found query
                uri = zend_string_init(Z_STRVAL_P(field), pos - Z_STRVAL_P(field), 0);
            } else {
                uri = zend_string_copy(Z_STR_P(field));
            }
        } else {
            php_url *urlInfo = php_url_parse(Z_STRVAL_P(field));
            if (urlInfo && urlInfo->path) {
                uri = zend_string_init(urlInfo->path, strlen(urlInfo->path), 0);
            }
            php_url_free(urlInfo);
        }
        break;
    }
    // 最后找 ORIG_PATH_INFO
    if ((field = zend_hash_str_find(Z_ARRVAL_P(server), ZEND_STRL("ORIG_PATH_INFO"))) &&
            Z_TYPE_P(field) == IS_STRING) {
        uri = zend_string_copy(Z_STR_P(field));
        break;
    }
} while (0);

最后附上 Apache 和 Nginx 下的 rewrite 规则 :)

; APACHE
Options -Indexes +FollowSymLinks +ExecCGI
DirectoryIndex index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [L]

; NGINX
location / {
    if (!-e $request_filename) {
        rewrite . /index.php last;
    }
}

你可能感兴趣的:(PHP 扩展 - 获取正确的 URI)