PHP模拟实现url rewrite
我的博客使用的是虚拟主机,也想实现url优化,但是我没有服务器权限,怎么办?
很简单,我们可以从$_SERVER[”REQUEST_URI”]和$_SERVER['PATH_INFO']来下手:
原网站访问地址是 http://kuyuecs.cnblogs.com/test.php?a=1&b=2&c=3
使用了 mode_rewrite 函数后,就可以用 http://kuyuecs.cnblogs.com/test.php/a/1/b/2/c/3来访问了,而且程序基本不用修改.
<?php
function mod_rewrite()
{
if (isset($_SERVER ['PATH_INFO']))
{
$url=substr($_SERVER ['PATH_INFO'],1);
$url=explode('/', $url );
foreach ($url as $key=>$value )
{
if($key%2!=1)
{
if($value!='')
{
$_GET[$value]=$url[$key+1];
$querystring[]=$value.'='.$url[$key+1];
}
}
}
$_SERVER['QUERY_STRING']=implode("&",$querystring );
$_SERVER['PHP_SELF']=substr($_SERVER['PHP_SELF'] ,0,strpos($_SERVER['PHP_SELF'],'.php')+4);
$_SERVER['REQUEST_URI']=$_SERVER['PHP_SELF'].'?'.$_SERVER ['QUERY_STRING'];
}
}
?>
很简单,我们可以从$_SERVER[”REQUEST_URI”]和$_SERVER['PATH_INFO']来下手:
原网站访问地址是 http://kuyuecs.cnblogs.com/test.php?a=1&b=2&c=3
使用了 mode_rewrite 函数后,就可以用 http://kuyuecs.cnblogs.com/test.php/a/1/b/2/c/3来访问了,而且程序基本不用修改.
<?php
function mod_rewrite()
{
if (isset($_SERVER ['PATH_INFO']))
{
$url=substr($_SERVER ['PATH_INFO'],1);
$url=explode('/', $url );
foreach ($url as $key=>$value )
{
if($key%2!=1)
{
if($value!='')
{
$_GET[$value]=$url[$key+1];
$querystring[]=$value.'='.$url[$key+1];
}
}
}
$_SERVER['QUERY_STRING']=implode("&",$querystring );
$_SERVER['PHP_SELF']=substr($_SERVER['PHP_SELF'] ,0,strpos($_SERVER['PHP_SELF'],'.php')+4);
$_SERVER['REQUEST_URI']=$_SERVER['PHP_SELF'].'?'.$_SERVER ['QUERY_STRING'];
}
}
?>