能够获取用户请求网址的参数,可以做很多有意思的事情,下面举几个例子。
一、知识储备
#测试网址: http://localhost/blog/testurl.php?id=5
//获取域名或主机地址
echo $_SERVER['HTTP_HOST']."<br>"; #localhost
//获取网页地址
echo $_SERVER['PHP_SELF']."<br>"; #/blog/testurl.php
//获取网址参数
echo $_SERVER["QUERY_STRING"]."<br>"; #id=5
//获取用户代理
echo $_SERVER['HTTP_REFERER']."<br>";
//获取完整的url
echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
#http://localhost/blog/testurl.php?id=5
//包含端口号的完整url
echo 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
#http://localhost:80/blog/testurl.php?id=5
//只取路径
$url='http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"];
echo dirname($url);
#http://localhost/blog
二、实例应用
1、301重定向
必应每日一图从jishusongshu.com/bing迁移到了api.szfx.top/bing
在jishusongshu.com/bing文件夹内添加index.php文件
<?php
$url = $_SERVER['PHP_SELF'];
header('HTTP/1.1 301 Moved Permanently');//发出301头部
header('Location: https://api.szfx.top'.$url);//跳转到我的新域名地址
?>
jishusongshu.com/bing/api文件夹内添加index.php文件
<?php
$day = $_GET['day'];
$blur = $_GET['blur'];
$type = $_GET['type'];
$gray = $_GET['gray'];
if(!$day){
$day=0;
}
$url= 'https://api.szfx.top/bing/api/?day='.$day;
if($blur){
$url=$url.'&blur='.$blur;
}
if($type){
$url=$url.'&type='.$type;
}
if($gray){
$url=$url.'&gray='.$gray;
}
header('HTTP/1.1 301 Moved Permanently');//发出301头部
header('Location:'.$url);//跳转到我的新域名地址
?>
效果:访问jishusongshu.com/bing跳转api.szfx.top/bing/index.php
2、由id打开WP文章
需求分析:资源下载页面添加返回到文章功能,演示页面
https://www.jishusongshu.com/download.php?id=264
<? php
$id = $_GET['id'];
?>
<a href="https://www.jishusongshu.com/?p=<?php echo $id; ?>">返回文章</a>
注:get_the_ID()的WP函数用于获取当前文章id。
3、UA解析获取
user_agent.php文件下载:
https://cloud.jishusongshu.com/drive/php-source/php_user_agent.rar
<?php
include('user_agent.php');
$user_agent = $_SERVER['HTTP_USER_AGENT'];//获取UA代码
$ua = new CI_User_agent($user_agent);
header('Content-type: application/json');
$json_return = [];
$json_return = array(
"browser" => $ua->browser(),
"os" => $ua->platform()
);
echo json_encode($json_return, JSON_UNESCAPED_UNICODE);
返回数组:
{
browser: "Chrome",
os: "Windows 8.1"
}
由此搭建的api:https://api.szfx.top/userinfo/
三、参考资料
博客园-阿波罗任-PHP中获取当前页面的完整URL