Home  >  Article  >  Backend Development  >  PHP implements pseudo-static code based on $_SERVER['PATH_INFO'] and .htaccess.

PHP implements pseudo-static code based on $_SERVER['PATH_INFO'] and .htaccess.

伊谢尔伦
伊谢尔伦Original
2017-07-17 16:24:052915browse

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

$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 "<h1>新闻列表</h1>";
echo "<a href=&#39;add_news.html&#39;>添加新闻</a><hr/>";
echo "<table>";
echo "<tr><td>id</td><td>标题</td><td>查看详情</td><td>修改新闻</td></tr>";
while($row=mysql_fetch_assoc($res)){
 echo "<tr><td>{$row[&#39;id&#39;]}</td><td>{$row[&#39;title&#39;]}</td><td><a href=&#39;show_new.php/look-id-{$row[&#39;id&#39;]}.shtml&#39;>查看详情</a></td><td><a href=&#39;#&#39;>修改页面</a></td></tr>";
}
//上面的红色的地址本来该是show_news.php?act=look&id={$row[&#39;id&#39;]}
echo "</table>";
//关闭资源
mysql_free_result($res);
mysql_close($conn);

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[&#39;PATH_INFO&#39;];
//$pa  打印出来的值是  /look-id-1.html
//通过正则表达式匹配获取的url地址
if(preg_match(&#39;/^\/(look)-(id)-([\d])\.shtml$/&#39;,$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[&#39;title&#39;]."<hr>".$res[&#39;content&#39;];
}else{
 echo "url地址不合法";
}
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 就可以这么写了

<IfModule rewrite_module>
#写你的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
</IfModule>

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

 

The above is the detailed content of PHP implements pseudo-static code based on $_SERVER['PATH_INFO'] and .htaccess.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn