简体   繁体   中英

PHP: Respond to ajax request only

Is it possible force PHP only respond to ajax requests?? By setting headers or etc. for example we have this code:

if (str.length == 0) { 
    document.getElementById("txtHint").innerHTML = "";
    return;
} else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
        }
    };
    xmlhttp.open("GET", "gethint.php?q=" + str, true);
    xmlhttp.send();
}

and we want to make an ajax request. Now when we type 'SITENAME.COM/gethint.php?q=' in browser it shows something. How to prevent this event? thanks.

You can't guarantee that somebody won't be able to access this on a non Ajax call, but the following could help prevent non-ajax requests:

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) 
     && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // more code here
}

HTTP headers are fairly easy to set, so it wouldn't be something to secure it... Only disallow the average user from hitting the page directly.

You can try this.

if (strtolower(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH')) === 'xmlhttprequest') {
   // I'm AJAX!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM