怎样实现php伪静态,php实现伪静态的二种方法介绍

一、根据$_SERVER['PATH_INFO']来操作实现。

示例:http://127.0.0.1/show_new.php/look-id-1.shtmlecho $_SERVER['PATH_INFO'] 的输出为:/look-id-1.shtml。

1、index.php

复制代码 代码示例:

/**

* php伪静态

* www.jbxue.com

*/

$conn=mysql_connect("localhost","root","root")or dir("连接失败");

mysql_select_db("tb_demo",$conn);

$sql="select * from news";

$res=mysql_query($sql);

header("content-type:text/html;charset=utf-8");

echo "

新闻列表

";

echo "添加新闻


";

echo "

echo "

id标题查看详情修改新闻";

while($row=mysql_fetch_assoc($res)){

echo "

{$row['id']}{$row['title']} 查看详情 修改页面";

}

//上面的红色的地址本来该是show_news.php?act=look&id={$row['id']}

echo "

";

//关闭资源

mysql_free_result($res);

mysql_close($conn);

?>

2、show_new.php页面

复制代码 代码示例:

header("Content-type:text/html;charset=utf-8");

$conn=mysql_connect("localhost","root","root");

mysql_select_db("tb_demo",$conn);

mysql_query("set names utf8");

$pa = $_SERVER['PATH_INFO'];

//$pa 打印出来的值是 /look-id-1.html

//通过正则表达式匹配获取的url地址

if(preg_match('/^\/(look)-(id)-([\d])\.shtml$/',$pa,$arr)){

$act = $arr[1]; //这个是请求的look方法

$id = $arr[3]; //这个是获取的id 值

$sql="select * from news where id= $id";

$res=mysql_query($sql);

$res = mysql_fetch_assoc($res);

echo $res['title']."


".$res['content'];

}else{

echo "url地址不合法";

}

mysql_close($conn);

?>

二、根据配置.htaccess来实现

先说下.htaccess文件怎么创建吧,在网站根目录下建立个记事本然后双击打开点击另存为 文件名写成.htaccess ,保存类型选择所有文件,编码选择utf-8的编码好的这是你就在目录看到这个.htaccess文件了。

首先,在apache 开启mod_rewrite.so,AllowOverride None 这里有两处 替换为 AllowOverride All。

比如href 地址写成 one_new-id-1.shtml //这个意思是one_new.php?id=1

这里的.htaccess这样写:

复制代码 代码示例:

#写你的rewrite规则

RewriteEngine On

# 可以配置多个规则,匹配的顺序是从上到下

RewriteRule one_new-id-(\d+)\.shtml$ one_new.php?id=$1 //这里的$1 代表的是第一个参数啊

RewriteRule abc_id(\d+)\.html$ error.php

#设置404错误

#ErrorDocument 404 /error.php

在one_new.php 页面echo $_GET['id'] 肯定会输出 id的值了。

就介绍这些吧,php实现伪静态还是很简单的,希望大家多多实践,写出更加灵活而轻便的伪静态规则。

你可能感兴趣的:(怎样实现php伪静态)