PHP Form Security With Referer

Howard Zoopaloopa picture Howard Zoopaloopa · May 15, 2010 · Viewed 12k times · Source

I'm putting together a site that will make itself available for user input. I was wondering if writing a function like:

if(getenv("HTTP_REFERER") != 'http://www.myURL.com/submitArea'){
        die('don\'t be an jerk, ruin your own site');   
    }else{
        // continue with form processing    
    }

is enough to prevent cross site form submissions.

EDIT: And if not, what is the best practice for preventing forms from being submitted from other hosts?

Answer

Pekka picture Pekka · May 15, 2010

Nope - HTTP_REFERER can be freely spoofed on client side and is not a reliable indicator of where a request came from.

Update: I misread the part about cross site forgery: For this, checking the referer is a valid security measure, because CSRF rely on manipulated links pointing to protected pages (that the attacked user has privileges on). User @Rook is correct.

The only exception is if the attack can happen from within the web application that is being attacked, e.g. by injecting malicious JavaScript code. In that case, a referer check is useless because the attack is coming from a "safe" URL, but so is arguably a solution based on a session or one-time token, because the token is in reach of the malicious JavaScript and can be easily retrieved.

However, using a one-time token is highly preferable to protect against this kind of attacks because HTTP_REFERER is stripped out by some proxies.