Reputation: 2177
I am new to wordpress. In few plugin's code, some of the setcookie() functions has HTTPOnly and Secure flag already SET and some of the setcookie() functions are without HTTPOnly or secure flag in a code.
How can I set all setcookie() functions with HTTPonly and Secure flag, No matter HTTPOnly or Secure flag is set or not.
If I apply code for setting above flags to TRUE either in .htaccess, or use ini_set() in index.php or changes in Apache configuration, Will this affect my existing Wordpress working?
Or anyone has better solution?
Upvotes: 4
Views: 12311
Reputation: 108841
Here's a possibility. It depends on various plugins and other code setting their cookies in their init hooks and not later. It's possible to intercept and fix them before they get sent.
Write a hook function for the wp_loaded hook, and install it with a large priority, so it runs after other functions on that hook.
add_action( 'wp_loaded', 'add_httponly_to_my_cookies', 9999, 0 );
Then, in the hook function, use php's header manipulation. This may work for you, but you should test it carefully before putting it into production.
The header() function's second argument lets us replace a header rather than add a new one.
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 );
}
}
}
}
This php code needs to go into a plugin or maybe a code snippet.
Upvotes: 0
Reputation: 1612
As far as I know, it is not possible to pre-set HTTPOnly for any cookie - it is possible to set it for session cookies though.
Take a look at PHP: SetCookie documentation
For Secure bit, your site needs to run also over SSL. For HTTPOnly - in case any scripts depend on values from these cookies, HTTPOnly cookies cannot be read by JS.
You could write your own setSecureCookie() function which internally calls setcookie() ... but thats a complete code rewrite.
Upvotes: 0