PHP check http referer for form submitted by AJAX, secure?
Posted
by Michael Mao
on Stack Overflow
See other posts from Stack Overflow
or by Michael Mao
Published on 2010-05-09T14:36:41Z
Indexed on
2010/05/09
14:48 UTC
Read the original article
Hit count: 267
Hi all:
This is the first time I am working for a front-end project that requires server-side authentication for AJAX requests. I've encountered problems like I cannot make a call of session_start
as the beginning line of the "destination page", cuz that would get me a PHP Warning :
Warning: session_start() [function.session-start]:
Cannot send session cache limiter -
headers already sent (output started at C:\xampp\htdocs\comic\app\ajaxInsert
Book.php:1)
in C:\xampp\htdocs\comic\app\common.php on line 10
I reckon this means I have to figure out a way other than checking PHP session variables to authenticate the "caller" of this PHP script, and this is my approach :
I have a "protected" PHP page, which must be used as the "container" of my javascript that posts the form through jQuery $.ajax();
method
In my "receiver" PHP script, what I've got is:
<?php
define(BOOKS_TABLE, "books");
define(APPROOT, "/comic/");
define(CORRECT_REFERER, "/protected/staff/addBook.php");
function isRefererCorrect()
{
// the following line evaluates the relative path for the referer uri,
// Say, $_SERVER['HTTP_REFERER'] returns "http://localhost/comic/protected/staff/addBook.php"
// Then the part we concern is just this "/protected/staff/addBook.php"
$referer = substr($_SERVER['HTTP_REFERER'], 6 + strrpos($_SERVER['HTTP_REFERER'], APPROOT));
return (strnatcmp(CORRECT_REFERER, $referer) == 0) ? true : false;
}
//http://stackoverflow.com/questions/267546/correct-http-header-for-json-file
header('Content-type: application/json charset=UTF-8');
header('Cache-Control: no-cache, must-revalidate');
echo json_encode(array
(
"feedback"=>"ok",
"info"=>isRefererCorrect()
));
?>
My code works, but I wonder is there any security risks in this approach? Can someone manipulate the post request so that he can pretend that the caller javascript is from the "protected" page?
Many thanks to any hints or suggestions.
© Stack Overflow or respective owner