If you noticed, I put "stopping" instead "preventing" in the title because I want my PHP application to be as secure as possible. I am wondering if anyone has any better ways to prevent session hijacking then what I have already. I would like to keep the security measures to my PHP code and not in any of the web server settings.

Here is what I am doing right now:

  • When a user logs in, session_regenerate_id() is called
  • A session variable is created which stores the users IP address which is decided from HTTP_X_CLUSTER_CLIENT_IP, HTTP_CLIENT_IP, HTTP_FORWARDED, HTTP_FORWARDED_FOR, or REMOTE_ADDR (whichever is found first)

Anyone have any tips on what else I should be doing? I was also wondering what the best method is to determine the users IP address so it can't be spoofed?


1 Answer 1


First of all remove all of the proposed checks. They are relying upon attacker controlled input to impose security restrictions. Nothing about this is "secure", its just foolish.

Spoofing your IP address over the internet is impossible because of the 3 way handshake, you should try studying networking it is actually pretty interesting. Using the HTTP_FORWARDED_FOR PHP variable for security is a violation of CWE-291: Trusting Self-reported IP address.

So how do you prevent "session hijacking"? Prevent the attacker from obtaining the session id in the first place.

OWASP A9 - Insufficent transport layer protection and OWASP A2- Cross Site Scripting.

Set these PHP session configurations:

session.cookie_httponly = 1 (helps mitigate xss)
session.session.use_only_cookies = 1 (prevents session fixation)
session.entropy_file = "/dev/urandom" (better entropy source)
session.cookie_lifetime = 0  (smaller exploitation window for xss/csrf/clickjacking...)
session.cookie_secure = 1 (owasp a9 violations)
  • 1
    But what about without changing any of the PHP settings and instead just with code? Nov 18, 2012 at 3:18
  • 1
    @ub3rst4r If you think you need something completely new to defend against something everyone has to deal with, you are doing it wrong.
    – rook
    Nov 18, 2012 at 3:19
  • 1
    @ub3rst4r Use ini_set and it’s in your PHP code.
    – Gumbo
    Nov 18, 2012 at 8:10
  • I was also reading the PHP Manual on Sessions and security which states that its important to use SSL in order to stop the session ID from being transferred in plain text. Oct 17, 2013 at 20:30
  • @ub3rst4r I prefer OWAPS's Insufficent transport layer protection write up, as this goes beyond just sessions.
    – rook
    Oct 17, 2013 at 20:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.