Skip to content

Instantly share code, notes, and snippets.

@dsmeringe
Created February 14, 2013 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsmeringe/4952481 to your computer and use it in GitHub Desktop.
Save dsmeringe/4952481 to your computer and use it in GitHub Desktop.
Example php search script returning results as JSON/JSONP. See also https://gist.github.com/dsmeringe/5134955 for "queryClass"
<?php
/**
* Search support for websites using JSON/JSONP.
* Built to be used with a jquery ui autocomplete field.
*
* This example is slightly generalized compared to it's original..
*
* Search parameter for search values is 'term', like
* quicksearch.php?term=search-value
*
* supply parameter 'callback=callbackFuncName' to supply a jsonp callback function.
*
* @author David Smeringe <david@merea.se>
*/
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");//remove if cross domain shouldn't be allowed
//get input values, generalize to support both get and post
$GP = isset($_GET['term'])? $_GET : $_POST;
//terminate with empty result if we don't have any search value
if (!isset( $GP['term'])) {
exit (json_encode(array()));
}
//initalize storage - where we got our data
require_once('queryClass.php');
$queryObj;
try {
$queryObj = new queryClass();
} catch (Exception $e) {
//handle errors
exit(json_encode($e->getMessage()));
}
$queryObj->hitsLimit = 15;
$queryObj->externalDBSettingsFile = 'connect.php';//holds db credentials
$queryObj->limitToLanguage = isset($GP['lang'])? $GP['lang']:0;//swedish?
if (isset($GP['hitslimit']) && $GP['hitslimit']<=300)
$queryObj->hitsLimit = $GP['hitslimit'];
try {
$queryObj->initializeDB();
//destroyer command
//drop old cached data?
if (isset($GP['destroyer'])) {
$k = $queryObj->dropStorageTable ();
exit(json_encode($k?"dropped the data" : "didn't drop"));
}
//search? (returns an array of results)
$result = $queryObj->search( $GP['term'], null, queryClass::GROUPSEARCH_SEARCHKEY);
$retval = array();
//return all columns?
if (isset($GP['returnFullHit'])) {
$retval = $result;
} else { //create a label/value list
foreach ($result as $r) {
$retval[] = array('label'=>$r['searchkey'], 'value'=>$r['searchkey']);
}
}
//retun a JSON string
$json = json_encode($retval);
if (!isset($GP['callback']))
exit( $json);
if (is_valid_callback($GP['callback']))
exit( $_GET['callback'] . '('.$json.')');
} catch (Exception $e) {
die(json_encode($e->getMessage()));
}
unset($queryObj);
// something went wrong if we end up here..
// bad request
header('status: 400 Bad Request', true, 400);
/**
* Validate JSON callback function
*
* @param string $subject
* @return boolean
*/
function is_valid_callback($subject)
{
$identifier_syntax
= '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*+$/u';
$reserved_words = array('break', 'do', 'instanceof', 'typeof', 'case',
'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue',
'for', 'switch', 'while', 'debugger', 'function', 'this', 'with',
'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum',
'extends', 'super', 'const', 'export', 'import', 'implements', 'let',
'private', 'public', 'yield', 'interface', 'package', 'protected',
'static', 'null', 'true', 'false');
return preg_match($identifier_syntax, $subject)
&& ! in_array(mb_strtolower($subject, 'UTF-8'), $reserved_words);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment