How to protect a site's cookies/sessions from being hijacked?

Discussion in 'PHP' started by qwikad.com, Jul 31, 2024.

  1. #1
    Been working on a new site that will use browser's cookies to log in users. In layman's terms give me some tips on how to protect site's cookies/sessions from being hijacked. What are some common practices?
     
    qwikad.com, Jul 31, 2024 IP
  2. zaidzahid

    zaidzahid Active Member

    Messages:
    113
    Likes Received:
    9
    Best Answers:
    1
    Trophy Points:
    80
    #2
    you should use secure cookies on your site and set http only,add limit of cookies these are the best practices.
     
    zaidzahid, Aug 2, 2024 IP
  3. qwikad.com

    qwikad.com Illustrious Member Affiliate Manager

    Messages:
    7,263
    Likes Received:
    1,693
    Best Answers:
    31
    Trophy Points:
    475
    #3
    I'd like to do it via htaccess, will this do the job?


    php_flag session.cookie_httponly on


    I also see that different php versions use different ways of doing that. What is common practice of setting a secure cookie in php 8?
     
    Last edited: Aug 7, 2024
    qwikad.com, Aug 7, 2024 IP
  4. GreenHost.Cloud

    GreenHost.Cloud Active Member

    Messages:
    471
    Likes Received:
    34
    Best Answers:
    3
    Trophy Points:
    73
    #4
    To protect your site's cookies and sessions from hijacking, you can follow these tips:
    1. Set HttpOnly and Secure Flags: Use `session.cookie_httponly`, which prevents JavaScript access to cookies, and `session.cookie_secure`, which ensures cookies are only sent over HTTPS.
    2. Use SameSite Attribute: Set the SameSite attribute for cookies to prevent CSRF attacks. You can use `session_set_cookie_params(['samesite' => 'Strict']);` in PHP.
    3. Regenerate Session IDs: Regenerate the session ID on login and at regular intervals using `session_regenerate_id()`.
    4. Validate User Agents and IPs: Maintain a record of user agents and IPs to detect anomalies.
    In your `.htaccess`, you can add:

    php_flag session.cookie_httponly on
    php_flag session.cookie_secure on
    PHP:
    For PHP 8, you can set a secure cookie using:

    session_set_cookie_params([
        'lifetime' => 0,
        'path' => '/',
        'domain' => 'yourdomain.com',
        'secure' => true,
        'httponly' => true,
        'samesite' => 'Strict'
    ]);
    PHP:
    Implementing these practices will help enhance the security of your cookies and sessions.
     
    GreenHost.Cloud, Aug 11, 2024 IP
    qwikad.com likes this.