Skip to content

Commit 51482a9

Browse files
gnarfscottgonzalez
authored andcommitted
Demos: PHP Strict mode compliance and use parse_json() for JSON encoding. Fixes #5124 - Ensure all PHP scripts for demos/tests properly escape/filter input data.
1 parent cce7dbe commit 51482a9

File tree

1 file changed

+8
-60
lines changed

1 file changed

+8
-60
lines changed

demos/autocomplete/search.php

Lines changed: 8 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
<?php
2-
2+
// no term passed - just exit early with no response
3+
if (empty($_GET['term'])) exit ;
34
$q = strtolower($_GET["term"]);
4-
if (!$q) return;
5+
// remove slashes if they were magically added
6+
if (get_magic_quotes_gpc()) $q = stripslashes($q);
7+
58
$items = array(
69
"Great Bittern"=>"Botaurus stellaris",
710
"Little Grebe"=>"Tachybaptus ruficollis",
@@ -569,63 +572,6 @@
569572
"Heuglin's Gull"=>"Larus heuglini"
570573
);
571574

572-
function array_to_json( $array ){
573-
574-
if( !is_array( $array ) ){
575-
return false;
576-
}
577-
578-
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
579-
if( $associative ){
580-
581-
$construct = array();
582-
foreach( $array as $key => $value ){
583-
584-
// We first copy each key/value pair into a staging array,
585-
// formatting each key and value properly as we go.
586-
587-
// Format the key:
588-
if( is_numeric($key) ){
589-
$key = "key_$key";
590-
}
591-
$key = "\"".addslashes($key)."\"";
592-
593-
// Format the value:
594-
if( is_array( $value )){
595-
$value = array_to_json( $value );
596-
} else if( !is_numeric( $value ) || is_string( $value ) ){
597-
$value = "\"".addslashes($value)."\"";
598-
}
599-
600-
// Add to staging array:
601-
$construct[] = "$key: $value";
602-
}
603-
604-
// Then we collapse the staging array into the JSON form:
605-
$result = "{ " . implode( ", ", $construct ) . " }";
606-
607-
} else { // If the array is a vector (not associative):
608-
609-
$construct = array();
610-
foreach( $array as $value ){
611-
612-
// Format the value:
613-
if( is_array( $value )){
614-
$value = array_to_json( $value );
615-
} else if( !is_numeric( $value ) || is_string( $value ) ){
616-
$value = "'".addslashes($value)."'";
617-
}
618-
619-
// Add to staging array:
620-
$construct[] = $value;
621-
}
622-
623-
// Then we collapse the staging array into the JSON form:
624-
$result = "[ " . implode( ", ", $construct ) . " ]";
625-
}
626-
627-
return $result;
628-
}
629575

630576
$result = array();
631577
foreach ($items as $key=>$value) {
@@ -635,6 +581,8 @@ function array_to_json( $array ){
635581
if (count($result) > 11)
636582
break;
637583
}
638-
echo array_to_json($result);
584+
585+
// json_encode is available in PHP 5.2 and above, or you can install a PECL module in earlier versions
586+
echo json_encode($result);
639587

640588
?>

0 commit comments

Comments
 (0)