Skip to content

Instantly share code, notes, and snippets.

@justinxreese
Created April 12, 2011 15:55
Show Gist options
  • Save justinxreese/915786 to your computer and use it in GitHub Desktop.
Save justinxreese/915786 to your computer and use it in GitHub Desktop.
Turn any PHP file into an API
var http = false;
if(navigator.appName = "Microsoft Internet Explorer"){
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
function doSomething(some_param){
http.abort();
http.open("POST","path/to/functions_and_api.php?action=someFunction&params="+some_param);
http.onreadystatechange=function(){
if(http.readyState == 4) {
if(http.responseText){
alert(http.responseText);
}
}
}
http.send(null);
}
/* call doSomething(some_params) to use your new "API" */
<?php
/**
* This snippet of code allows you to turn any php file into one that
* responds to REQUESTS - unveiling all of the functions to web calls
* in the style of an API.
*
* The code as it exists here has gaping security issues. At the very
* simplest you should have an array of allowed function names that is
* checked before executing. I have a more secure version somewhere ...
*/
if($_REQUEST['action'] && $_REQUEST['params']){
$function = $_REQUEST['action'];
if(function_exists($function)){
if($function($_REQUEST['params'])){
echo "Successful {$function}";
else{
echo "Error running function - {$function}";
}
}else{
echo "Unsuccessful call - attempted to run non-existant function";
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment