PHP扩展学习: 实现简单URL解析

/*
  +----------------------------------------------------------------------+
  | PHP Version 5                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2013 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author: sakmon<2014/09/25>                                                             |
  +----------------------------------------------------------------------+
*/

/* $Id$ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "ext/standard/url.h"
#include "php_sakmon.h"

/* If you declare any globals in php_sakmon.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(sakmon)
*/

/* True global resources - no need for thread safety here */
static int le_sakmon;

/* {{{ sakmon_functions[]
 *
 * Every user visible function must have an entry in sakmon_functions[].
 */
const zend_function_entry sakmon_functions[] = {
	PHP_FE(bmsh_parse_url, NULL)
    PHP_FE_END	/* Must be the last line in sakmon_functions[] */
};
/* }}} */

/* {{{ sakmon_module_entry
 */
zend_module_entry sakmon_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
	STANDARD_MODULE_HEADER,
#endif
	"sakmon",
	sakmon_functions,
	PHP_MINIT(sakmon),
	PHP_MSHUTDOWN(sakmon),
	PHP_RINIT(sakmon),		/* Replace with NULL if there's nothing to do at request start */
	PHP_RSHUTDOWN(sakmon),	/* Replace with NULL if there's nothing to do at request end */
	PHP_MINFO(sakmon),
#if ZEND_MODULE_API_NO >= 20010901
	PHP_SAKMON_VERSION,
#endif
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_SAKMON
ZEND_GET_MODULE(sakmon)
#endif

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("sakmon.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_sakmon_globals, sakmon_globals)
    STD_PHP_INI_ENTRY("sakmon.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_sakmon_globals, sakmon_globals)
PHP_INI_END()
*/
/* }}} */

/* {{{ php_sakmon_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_sakmon_init_globals(zend_sakmon_globals *sakmon_globals)
{
	sakmon_globals->global_value = 0;
	sakmon_globals->global_string = NULL;
}
*/
/* }}} */

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(sakmon)
{
	/* If you have INI entries, uncomment these lines 
	REGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(sakmon)
{
	/* uncomment this line if you have INI entries
	UNREGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(sakmon)
{
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(sakmon)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(sakmon)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "sakmon support", "enabled");
	php_info_print_table_end();

	/* Remove comments if you have entries in php.ini
	DISPLAY_INI_ENTRIES();
	*/
}
/* }}} */

/* Remove the following function when you have successfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_sakmon_compiled(string arg)
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(bmsh_parse_url)
{
	zval  *uri,*settled_uri = NULL;
	char  *suffix = NULL;
	int  suffix_len = 0;
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &suffix_len) == FAILURE ) 
	{
		return;
	}
    uri = bmsh_request_query(TRACK_VARS_SERVER, ZEND_STRL("REQUEST_URI") TSRMLS_CC);
	if (Z_TYPE_P(uri) != IS_NULL) 
	{
		if (strstr(Z_STRVAL_P(uri), "http") == Z_STRVAL_P(uri)) 
		{
			php_url *url_info = php_url_parse(Z_STRVAL_P(uri));

			if (url_info && url_info->path) 
			{
				MAKE_STD_ZVAL(settled_uri);
				ZVAL_STRING(settled_uri, url_info->path, 1);
			}

			php_url_free(url_info);
		} else {
			char *pos  = NULL;
			if ((pos = strstr(Z_STRVAL_P(uri), "?")) ) 
			{
				MAKE_STD_ZVAL(settled_uri);
				ZVAL_STRINGL(settled_uri, Z_STRVAL_P(uri), pos - Z_STRVAL_P(uri), 1);
				
			} 
			else 
			{
				settled_uri = uri;
			}
		}
		zval_ptr_dtor(&uri);
		zval *script_name;
		script_name = bmsh_request_query(TRACK_VARS_SERVER, ZEND_STRL("SCRIPT_NAME") TSRMLS_CC);
		size_t  dir_len;
		char 	*dir = estrndup(Z_STRVAL_P(script_name), Z_STRLEN_P(script_name));

		dir_len = php_dirname(dir, Z_STRLEN_P(script_name));
		zval_ptr_dtor(&script_name);

		if( strstr(Z_STRVAL_P(settled_uri),dir) == Z_STRVAL_P(settled_uri) )
		{
			char *sp = NULL;
			sp = strrchr(Z_STRVAL_P(settled_uri),Z_STRLEN_P(settled_uri)-dir_len);
			if( sp != IS_NULL )
			{
				ZVAL_STRINGL(settled_uri,sp,strlen(sp), 1);
			}
			efree(sp);
		}
	}
	
	if( Z_TYPE_P(settled_uri) != IS_NULL && suffix_len>0 )
	{
		if( strstr(Z_STRVAL_P(settled_uri),suffix) == Z_STRVAL_P(settled_uri)+Z_STRLEN_P(settled_uri)-suffix_len )
		{
			ZVAL_STRINGL(settled_uri, Z_STRVAL_P(settled_uri), Z_STRLEN_P(settled_uri)-suffix_len, 1);
		}
	}
	array_init(return_value);
	char *delim = "/";
    char *p = strtok(Z_STRVAL_P(settled_uri), delim);
    char  *c;
    zval *val;
    if(p != IS_NULL)
    { 
    	add_next_index_stringl(return_value, p,strlen(p),1);
    	p = strtok(NULL,delim);
    	if(p != IS_NULL)
    	{
    		add_next_index_stringl(return_value, p,strlen(p),1);
    		while((p = strtok(NULL,delim)) )
    		{
    			if( (c = strtok(NULL,delim)) )
    			{
    				MAKE_STD_ZVAL(val);
    				ZVAL_STRINGL(val,c,strlen(c),1);
    				if( zend_hash_exists(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_GET]) ,p,strlen(p)+1) ==  FAILURE )
    				{
    					zend_hash_add( Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_GET]) ,p,strlen(p)+1,&val,sizeof(zval *),NULL);
    				}
    				else
    				{
    					zend_hash_update( Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_GET]) ,p,strlen(p)+1,&val,sizeof(zval *),NULL);
    				}
    			}
    		}
    	}
    }
    zval_ptr_dtor(&settled_uri);
    return ;
}

zval * bmsh_request_query(uint type, char * name, uint len TSRMLS_DC) {
	zval 		**carrier = NULL, **ret;

	#if (PHP_MAJOR_VERSION == 5) && (PHP_MINOR_VERSION < 4)
		zend_bool 	jit_initialization = (PG(auto_globals_jit) && !PG(register_globals) && !PG(register_long_arrays));
	#else
		zend_bool 	jit_initialization = PG(auto_globals_jit);
	#endif

	switch (type) {
		case TRACK_VARS_POST:
		case TRACK_VARS_GET:
		case TRACK_VARS_FILES:
		case TRACK_VARS_COOKIE:
			carrier = &PG(http_globals)[type];
			break;
		case TRACK_VARS_ENV:
			if (jit_initialization) {
				zend_is_auto_global(ZEND_STRL("_ENV") TSRMLS_CC);
			}
			carrier = &PG(http_globals)[type];
			break;
		case TRACK_VARS_SERVER:
			if (jit_initialization) {
				zend_is_auto_global(ZEND_STRL("_SERVER") TSRMLS_CC);
			}
			carrier = &PG(http_globals)[type];
			break;
		case TRACK_VARS_REQUEST:
			if (jit_initialization) {
				zend_is_auto_global(ZEND_STRL("_REQUEST") TSRMLS_CC);
			}
			(void)zend_hash_find(&EG(symbol_table), ZEND_STRS("_REQUEST"), (void **)&carrier);
			break;
		default:
			break;
	}


	if (!carrier || !(*carrier)) {
		zval *empty;
		MAKE_STD_ZVAL(empty);
		ZVAL_NULL(empty);
		return empty;
	}

	if (!len) {
		Z_ADDREF_P(*carrier);
		return *carrier;
	}

	if (zend_hash_find(Z_ARRVAL_PP(carrier), name, len + 1, (void **)&ret) == FAILURE) {
		zval *empty;
		MAKE_STD_ZVAL(empty);
		ZVAL_NULL(empty);
		return empty;
	}

	Z_ADDREF_P(*ret);
	return *ret;
}
/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and 
   unfold functions in source code. See the corresponding marks just before 
   function definition, where the functions purpose is also documented. Please 
   follow this convention for the convenience of others editing your code.
*/


/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
sakmon.h
/*
  +----------------------------------------------------------------------+
  | PHP Version 5                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2013 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author:                                                              |
  +----------------------------------------------------------------------+
*/

/* $Id$ */

#ifndef PHP_SAKMON_H
#define PHP_SAKMON_H

extern zend_module_entry sakmon_module_entry;
#define phpext_sakmon_ptr &sakmon_module_entry

#define PHP_SAKMON_VERSION "0.1.0" /* Replace with version number for your extension */

#ifdef PHP_WIN32
#	define PHP_SAKMON_API __declspec(dllexport)
#elif defined(__GNUC__) && __GNUC__ >= 4
#	define PHP_SAKMON_API __attribute__ ((visibility("default")))
#else
#	define PHP_SAKMON_API
#endif

#ifdef ZTS
#include "TSRM.h"
#endif

PHP_MINIT_FUNCTION(sakmon);
PHP_MSHUTDOWN_FUNCTION(sakmon);
PHP_RINIT_FUNCTION(sakmon);
PHP_RSHUTDOWN_FUNCTION(sakmon);
PHP_MINFO_FUNCTION(sakmon);

PHP_FUNCTION(bmsh_parse_url);

zval * bmsh_request_query(uint type, char * name, uint len TSRMLS_DC);
/* 
  	Declare any global variables you may need between the BEGIN
	and END macros here:     

ZEND_BEGIN_MODULE_GLOBALS(sakmon)
	long  global_value;
	char *global_string;
ZEND_END_MODULE_GLOBALS(sakmon)
*/

/* In every utility function you add that needs to use variables 
   in php_sakmon_globals, call TSRMLS_FETCH(); after declaring other 
   variables used by that function, or better yet, pass in TSRMLS_CC
   after the last function argument and declare your utility function
   with TSRMLS_DC after the last declared argument.  Always refer to
   the globals in your function as SAKMON_G(variable).  You are 
   encouraged to rename these macros something shorter, see
   examples in any other php module directory.
*/

#ifdef ZTS
#define SAKMON_G(v) TSRMG(sakmon_globals_id, zend_sakmon_globals *, v)
#else
#define SAKMON_G(v) (sakmon_globals.v)
#endif

#endif	/* PHP_SAKMON_H */


/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
安装扩展,修改ngx配置让其对目录的访问都重写的指定文件(如index.php); 测试:PHP调用bmsh_parse_url()URL解析方法,传入参数URL后缀,这里使用.html伪静态。 PHP代码:
$c = bmsh_parse_url('.html');
var_dump($c);
var_dump($_GET);
访问http://localhost/controller/action/k1/v1/k2/v2/k3/v3.html?a=1&b=2&c=3&d=4&k3=v4,浏览器输出内容如下:
array(2) { [0]=> string(10) "controller" [1]=> string(6) "action" } 
array(7) { ["a"]=> string(1) "1" ["b"]=> string(1) "2" ["c"]=> string(1) "3" ["d"]=> string(1) "4" ["k3"]=> string(2) "v3" ["k1"]=> string(2) "v1" ["k2"]=> string(2) "v2" }
注意这里传了两个键k3的参数,路径上的把?后面的替换掉了。

转载于:https://my.oschina.net/sakmon/blog/393921

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值