PHP - header()的用法 -收集

    科技2023-09-25  72

    1.应用场景

    主要用于了解php header的用法.

    设置响应头, 浏览器的响应方式.

    2.学习/操作

    1. 跳转页面 header('Location:'.$url); //Location和":"之间无空格。

     

    2. 声明content-type header('content-type:text/html;charset=utf-8');

     

    3. 返回response状态码 header('HTTP/1.1 404 Not Found');

     

    4. 在某个时间后执行跳转 header('Refresh: 10; url=http://www.baidu.com/'); //10s后跳转。

     

    5. 控制浏览器缓存 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT"); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache");

     

    6. 执行http验证 header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Basic realm="Top Secret"');

     

    7. 执行下载操作 header('Content-Type: application/octet-stream'); //设置内容类型 header('Content-Disposition: attachment; filename="example.zip"'); //设置MIME用户作为附件 header('Content-Transfer-Encoding: binary'); //设置传输方式 header('Content-Length: '.filesize('example.zip')); //设置内容长度

     

     

    8. 设置cookie以及如samesite属性等

    if (PHP_VERSION_ID < 70300) {      setcookie('samesite-test', '1', 0, '/; samesite=strict'); } else {     header('Set-Cookie: samesite-test=1; path=/; samesite=strict'); }

    截图:

     

    代码封装

    /**  * Support samesite cookie flag in both php 7.2 (current production) and php >= 7.3 (when we get there)  * From: https://github.com/GoogleChromeLabs/samesite-examples/blob/master/php.md and https://stackoverflow.com/a/46971326/2308553   *  * @see https://www.php.net/manual/en/function.setcookie.php  *  * @param string $name  * @param string $value  * @param int $expire  * @param string $path  * @param string $domain  * @param bool $secure  * @param bool $httponly  * @param string $samesite  * @return void  */ function setCookieSameSite(     string $name,      string $value,     int $expire,      string $path,      string $domain,     bool $secure,      bool $httponly,      string $samesite = 'None' ): void {     if (PHP_VERSION_ID < 70300) {         setcookie($name, $value, $expire, $path . '; samesite=' . $samesite, $domain, $secure, $httponly);         return;     }     setcookie($name, $value, [         'expires' => $expire,         'path' => $path,         'domain' => $domain,         'samesite' => $samesite,         'secure' => $secure,         'httponly' => $httponly,     ]); }

     

     

     

    后续补充

    ...

    3.问题/补充

    1.为什么PHP无法输出特殊字符?

    TBD

     

    2.Header 中content-type的值设置

    https://mp.csdn.net/editor/html/100046672 // PHP - 如何下载服务器上的文件

    4.参考

    https://www.php.cn/php-weizijiaocheng-394656.html  //PHP - header()的7种用法

    https://mp.csdn.net/editor/html/100046672 // PHP - 如何下载服务器上的文件

    https://stackoverflow.com/questions/39750906/php-setcookie-samesite-strict  // PHP setcookie “SameSite=Strict”?

    后续补充

    ...

     

    Processed: 0.014, SQL: 8