如何设置所有带有 HTTPOnly 和 Secure 标志的 setcookie() 函数,无论是否设置了 HTTPOnly 或 Secure 标志。
如果我在 .htaccess 中应用代码将上述标志设置为 TRUE,或者在 index.php 中使用 ini_set() 或更改 Apache 配置,这会影响我现有的 Wordpress 工作吗?
或者谁有更好的解决方案?
为
wp_loaded 钩子编写一个钩子函数,并以较大的优先级安装它,这样它就在该钩子上的其他函数之后运行。
add_action( 'wp_loaded', 'add_httponly_to_my_cookies', 9999, 0 );
然后,在钩子函数中,使用php的标头操作。这可能对您有用,但您应该在投入生产之前仔细测试它。
header()函数的第二个参数让我们可以替换标头而不是添加新标头。
public function add_httponly_to_my_cookies() {
if ( headers_sent() ) {
/* darn! too late! cookies already sent. */
return;
}
foreach ( headers_list() as $header ) {
if ( 0 === stripos( $header, 'Set-Cookie:' ) ) {
/* this header is a cookie! */
if ( false === stripos( $header, 'HttpOnly' ) ) {
/* no HttpOnly item, append it */
$header .= '; HttpOnly';
/* replace the cookie in the list of headers */
header( $header, true );
}
}
}
}
此 php 代码需要放入插件或可能是代码片段。