当前位置:首页php > 正文

PHP中Header()函数设置HTTP头总结

作者:野牛程序员:2024-02-01 11:26:26php阅读 2881

PHP中的header()函数用于发送原始的 HTTP 头。以下是关于header()函数的一些要点:

  • 基本用法


  • header(string $header, bool $replace = true, int $http_response_code = null): void
    • $header:要发送的 HTTP 头信息。

    • $replace:一个布尔值,指示是否替换之前的相同类型的头。默认为 true,表示替换。

    • $http_response_code:可选参数,用于设置 HTTP 状态码。

  • 常见用法


  • // 设置文档类型
    header('Content-Type: text/html; charset=utf-8');
    // 设置重定向
    header('Location: https://example.com/new_page.php');
    // 设置缓存控制
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Pragma: no-cache');
    header('Expires: 0');
    // 设置HTTP响应码
    header('HTTP/1.1 404 Not Found');
  • 注意事项

    • 调用header()函数之前,不能有任何输出,包括 HTML 标签、空格、换行符等。

    • 最好在 PHP 文件的开头调用header()函数。

    • 一旦使用了header()函数,就不能再发送 HTTP 响应主体内容了,否则会导致错误。

  • 安全性注意事项

    • 避免从用户输入直接构造header()内容,以防止HTTP头注入攻击。

    • 使用header()之前,应该验证和过滤所有输入,确保不会包含恶意内容。

  • 错误处理

    • 如果header()函数调用失败,例如在输出内容后调用,PHP 会抛出警告(Warning)或者致命错误(Fatal Error)。

  • 建议

    • 尽量减少使用header()函数,避免直接操作 HTTP 头,而是使用更高级别的框架或库来处理 HTTP 请求和响应。

总的来说,header()函数在 PHP 中是一个强大的工具,可以用于控制和定制 HTTP 响应的各个方面,但是需要谨慎使用以确保安全性和正确性。

以下是一些使用header()函数的代码示例:

  1. 设置文档类型和字符集

    header('Content-Type: text/html; charset=utf-8');
  2. 执行重定向

    header('Location: http://yncoders.com/new_page.php');
  3. exit(); // 重定向后一般需要立即终止脚本执行
  4. 设置缓存控制

    header('Cache-Control: no-cache, no-store, must-revalidate');
  5. header('Pragma: no-cache');header('Expires: 0');
  6. 设置HTTP响应码

    phpCopy codeheader('HTTP/1.1 404 Not Found');
  7. 设置下载文件

    header('Content-Disposition: attachment; filename="example.zip"');
  8. header('Content-Type: application/octet-stream');
  9. header('Content-Length: ' . filesize('example.zip'));
  10. readfile('example.zip');
  11. 处理图片输出

    $image = file_get_contents('example.jpg');
  12. header('Content-Type: image/jpeg');
  13. echo $image;
  14. 设置跨域资源共享 (CORS) 头

    header('Access-Control-Allow-Origin: *');
  15. header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
  16. header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization');

这些示例展示了header()函数的多种用法,可以根据具体的需求在 PHP 中使用。记住,在调用header()函数之前确保没有输出任何内容,并在需要时及时退出或终止脚本执行。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击