当前位置:Gxlcms > PHP教程 > php基于$_SERVER['PATH_INFO']和.htaccess实现伪静态代码详解

php基于$_SERVER['PATH_INFO']和.htaccess实现伪静态代码详解

时间:2021-07-01 10:21:17 帮助过:28人阅读

1.根据$_SERVER['PATH_INFO']来操作实现。

举个列子比如你的网站的地址是 http://127.0.0.1/show_new.php/look-id-1.shtml
你echo $_SERVER['PATH_INFO'] 出来的结果就会是 /look-id-1.shtml 看到这个我想大家可能已经明白了。
index.php

  1. $conn=mysql_connect("localhost","root","root")or dir("连接失败");
  2. mysql_select_db("tb_demo",$conn);
  3. $sql="select * from news";
  4. $res=mysql_query($sql);
  5. header("content-type:text/html;charset=utf-8");
  6. echo "<h1>新闻列表</h1>";
  7. echo "<a href='add_news.html'>添加新闻</a><hr/>";
  8. echo "<table>";
  9. echo "<tr><td>id</td><td>标题</td><td>查看详情</td><td>修改新闻</td></tr>";
  10. while($row=mysql_fetch_assoc($res)){
  11. echo "<tr><td>{$row['id']}</td><td>{$row['title']}</td><td><a href='show_new.php/look-id-{$row['id']}.shtml'>查看详情</a></td><td><a href='#'>修改页面</a></td></tr>";
  12. }
  13. //上面的红色的地址本来该是show_news.php?act=look&id={$row['id']}
  14. echo "</table>";
  15. //关闭资源
  16. mysql_free_result($res);
  17. mysql_close($conn);

show_new.php页面

  1. header("Content-type:text/html;charset=utf-8");
  2. $conn=mysql_connect("localhost","root","root");
  3. mysql_select_db("tb_demo",$conn);
  4. mysql_query("set names utf8");
  5. $pa = $_SERVER['PATH_INFO'];
  6. //$pa 打印出来的值是 /look-id-1.html
  7. //通过正则表达式匹配获取的url地址
  8. if(preg_match('/^\/(look)-(id)-([\d])\.shtml$/',$pa,$arr)){
  9. $act = $arr[1]; //这个是请求的look方法
  10. $id = $arr[3]; //这个是获取的id 值
  11. $sql="select * from news where id= $id";
  12. $res=mysql_query($sql);
  13. $res = mysql_fetch_assoc($res);
  14. echo $res['title']."<hr>".$res['content'];
  15. }else{
  16. echo "url地址不合法";
  17. }
  18. mysql_close($conn);

看到上面的这个我想大家肯定懂了吧 其实这种方式用的不多的下面的给大家说第二种方法了啊

2.根据配置.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 就可以这么写了

  1. <IfModule rewrite_module>
  2. #写你的rewrite规则
  3. RewriteEngine On
  4. # 可以配置多个规则,匹配的顺序是从上到下
  5. RewriteRule one_new-id-(\d+)\.shtml$ one_new.php?id=$1 //这里的$1 代表的是第一个参数啊
  6. RewriteRule abc_id(\d+)\.html$ error.php
  7. #设置404错误
  8. #ErrorDocument 404 /error.php
  9. </IfModule>

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

以上就是php基于$_SERVER['PATH_INFO']和.htaccess实现伪静态代码详解的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行