Spread The Knowledge

How to Secure Cookies in PHP

Mahesh Dhaka CEO at WEBHOBS

Cookie is a small file, stored by the server at user's computer and when the computer requests a web page to the browser, it sends the cookie along with it. By using PHP, we can easily create, retrieve and delete the cookies. Let's work on the security of cookies:-

1. Protect Against XSS

While creating the cookie we should use httponly, it will instruct to the browser that Javascript is not allowed to access the cookie. That's the primary defense against cross-site scripting by preventing the hackers to retrieve the information of cookie. However, using the httponly can't guarantee to prevent against cross side scripting but It works well for modern browsers(Firefox 3+, IE 7+ and Chrome));

setcookie( name, value, expire, path, domain, secure, httponly);

2. Disallow To The Sub Domains

The Domain option provides you the control that it's allowed or not to access the cookie via the subdomain. If we really don't need to access the cookies via subdomain then disallow it.

// allow the access to whole domain
setcookie( name, value, expire, path, .example.com , secure, httponly);
// prevent  the access to subdomain
setcookie( name, value, expire, path, www.example.com , secure, httponly);

3. Allow Access To Specific Path

By default all the pages of website are allowed to access the information of cookies but we can limit the access of cookie to a particular path of website.

// Allow the access to all paths
setcookie( name, value, expire, / , .example.com , secure, httponly);
// Allow   the access to a particular folder
setcookie( name, value, expire, /user, www.example.com , secure, httponly);

4. Secure Connection

We can restrict the access of cookie over unsecure connection(http). Put the SSL certificate at website and set secure to true.

// Allow at unsecure connections
setcookie( name, value, expire, / , .example.com , false, httponly);
// Restrict  at unsecure connections
setcookie( name, value, expire, /user, www.example.com , true, httponly);

We learned the 4 ways to make the cookies secure but frankly, nothing is fully secure at the web. We should always be get updated with new security threads and their solutions.

Ask The Queries or Share Your Views

8 Reasons why PHP is best programming language for the web development

The Smackdown b/w Node JS V/S PHP

6 Benefits Of Using PHP 7

How To Send Email Using PHP

Difference b/w PDO and MySQLi

How To Secure Cookies In PHP

8 Security Tips For PHP Developers

6 Security Tips For PHP File Upload

5 Common Attacks At PHP Website

5 Tips to Speed Up Your Website