Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Advertise on

Check AJAX Call Security on PHP page
New on LowEndTalk? Please read our 'Community Rules' by clicking on it in the right menu!

Check AJAX Call Security on PHP page

fresher_06fresher_06 Member
edited November 2012 in Tutorials

Hi All,

We all use AJAX call to get info from external PHP page.So I have come across a basic function which you can keep at the top of your PHP page which is getting called by Jquery through $.ajax.
Its a basic security measure to detect does the page is called directly or is it called by the application from an AJAX call (which is supposed to be).

So put the below checkAjax() function on top of your php page --

// check if it is a Ajax request - exit if not in all the php pages which are called via AJAX function checkAjax() { if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') { exitWithHttpResponseStatus(204); // this function is to send any response header , you can even use it for any other purpose as well } }
/** * Set HTTP response status * * The response status is used browser-side * to determine the outcome of an AJAX request. * * @param integer $code A HTTP status code * @throws RuntimeException Throw exception if headers are already sent * @throws InvalidArgumentException Throw exception if the provided HTTP code is not in the list */
function exitWithHttpResponseStatus($code) { // common HTTP statuses $statuses = array( 200 => '200 OK', 204 => '204 No Content', 404 => '404 Not Found', 500 => '500 Internal Server Error', );
// make sure headers are not sent already! if (headers_sent()) { throw new RuntimeException( 'RuntimeException: headers are already sent' ); }
// supplied $code not implemented. bad. if (!array_key_exists($code, $statuses)) { throw new InvalidArgumentException( sprintf('Exception: status code %d not implemented', $code) ); }
// define the HTTP header $status = sprintf('HTTP/1.1 %s', $statuses[$code]); header($status, $code); exit(); }

I do understand that the headers can be manipulated but at least its a basic security mechanism.
Also for more ways of securing your PHP page can be found in the below discussion --

Any kind of inputs / suggestions are highly welcome.



Sign In or Register to comment.