利用PHP中的header函数跳转页面或者设置HTTP响应头
发布时间:2023-06-26 01:44:04
header函数是PHP中一个非常有用的函数,可以用来跳转页面或者设置HTTP响应头,下面将详细讲解它的用法。
1. 跳转页面
可以使用header函数来跳转页面,其基本语法如下:
header('Location: http://www.example.com');
需要注意的是,在这里location的URL必须是绝对路径。比如,http://www.example.com就是一个绝对路径,而/example则不是。这是因为PHP会将相对路径看作在自身server上,而这是不正确的。
注意,在使用header('Location: url')时一定要确保在前面没做过任何输出,因为header只能被发送一次,将其放在页面中间可能会导致其不起作用。比如:
<html>
<head>
<title>Jump to Example.com</title>
</head>
<body>
<?php
header('Location: http://www.example.com');
exit;
?>
</body>
</html>
2. 设置HTTP响应头
header函数还可以用来设置HTTP响应头,其基本语法如下:
header('Content-Type: text/html; charset=utf-8');
这个例子中的Content-Type header表示响应的内容类型是HTML,并且使用utf-8编码。
还有一些常见的HTTP响应头可以用header函数来设置,比如:
header('Expires: Mon, 26 Jul 2021 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: http://www.example.com');
header('HTTP/1.1 404 Not Found');
根据需要,可以参考相应的HTTP标准协议文档来设置不同的HTTP响应头。
3. 总结
总的来说,header函数是PHP中一个非常实用的函数,可以用来跳转页面或者设置HTTP响应头。在使用header函数时,需要注意的是:
在跳转页面时,location的URL必须是绝对路径,而且header函数应该在前面没有做任何输出的情况下使用;
在设置HTTP响应头时,应该根据需要设置相应的HTTP响应头,同时注意一些常见的HTTP响应头。
