Detecting Ajax in PHP and making sure request was from my own website

前端 未结 7 1322
臣服心动
臣服心动 2020-11-29 23:31

I use my PHP back-end to detect AJAX requests by checking for a value in $_SERVER[\'HTTP_X_REQUESTED_WITH\'].

This gives me a reliable detection, making

7条回答
  •  离开以前
    2020-11-30 00:28

    Use POST session secured requests:

    Inside the Webpage (e.g. index.php) we need to store the sessionid

    
    
    ...
    
    
    ...
    
    

    The ajax requests (ajaxrequest.js)

    /* simple getAjax function 
     * @param $url       request url
     * @param $param     parameter (dont use ?)
     * @param callback  function on success
     */
    var spinnerid = '#spinner'; // Spinner as long ajax requests running
    $(document).ajaxStart(function() { $(spinnerid).show(); });
    $(document).ajaxStop(function() { $(spinnerid).hide(); });
    function getAjax( url, param, callback ) {
        var data = null;
        url += "?sid=" + sid + "&" + param;
        $.ajax({
            url: url,
            method: "POST", // uncomment to use GET, POST is secured by session
            cache: false,
            async: true,
            success : function(data){
          callback(data);
        },
    }
    
    getAjax( 'http://domain.com/', 'data=foo', function( data ) {
     // do stuf with data 
     var jsonobj = eval("(" + data + ")");
     var data = jsonobj[0][ 'data' ];
    });
    

    Responsible php side:

    if( isset( $_GET['sid'] ) ) $client_sid = $_GET['sid'];
    
    if( session_id() == null ) session_start();
    
    if( session_id() != $client_sid ) {
        // noID or wrongID, redirect to mainindex
        ignore_user_abort(true);
        header( "HTTP/1.1 403 Forbidden" );
        header("Connection: close", true);
        exit;
    } else {
    
        // get data
        if( isset( $_GET['data'] ) ) {
            $data = $_GET['data'];
        } else if( isset( $_POST['data'] ) ) {
            $data = $_POST['data'];
        } else {
            $data = null;
        }
    
        // do stuff with data
    
        // return data as json
        $resp[0]['data'] = $data; 
        print_r( json_encode( $resp ) );
    }
    

提交回复
热议问题