头图

在PHP中,header()函数是一个非常强大的工具,它可以用来发送原始的HTTP头信息。以下是 header()函数的七种常见用法:

  1. 页面重定向:使用 header()函数实现页面跳转,例如:
header("Location: http://www.example.com/"); 
  1. 设置响应状态码:例如,发送一个404 Not Found状态码:
header("HTTP/1.0 404 Not Found");
  1. 设置内容类型:例如,设置响应的内容类型为JSON:
header("Content-type: application/json");
  1. 防止页面缓存:可以通过设置响应头信息来禁止客户端缓存页面:
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
  1. 设置字符集:例如,设置字符集为UTF-8:
header("Content-Type: text/html; charset=utf-8");
  1. 文件下载:可以使用 header()函数来实现文件下载功能:
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename="example.zip"");
header("Content-Length: ".filesize("example.zip"));
  1. 设置HTTP认证:例如,使用Basic认证方式:
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';

蓝易云
36 声望4 粉丝