我构建了一个PHP文件,其唯一目的是隐藏Google搜索的API密钥,但是file_get_contents()的一部分总是回显angular.callbacks._0_({
而不是angular.callbacks._0({
这一小小的变化使其余的响应毫无价值,因为Angular会抛出Uncaught TypeError: angular.callbacks._0_ is not a function
。虽然解决方法确实可以正常运行,但我想知道是否有人找到了这个问题的根源或者更严格的PHP解决方案(没有卷曲或任何其他包。)
search.php
<?php // Created by Deovandski on 2/14/2016
header('Content-type: application/json');
# Setup Base URL and array for Parameters
$host = 'https://www.googleapis.com/customsearch/v1?';
$queries = array();
$queries['cx'] = "XXX";// CSE KEY
$queries['key'] = "XXX"; // API KEY
# Setup possible incoming params
if (isset($_GET['search_term'])) $queries['q'] = $_GET['search_term'];
if (isset($_GET['result_count'])) $queries['result_count'] = $_GET['result_count'];
if (isset($_GET['callback'])) $queries['callback'] = $_GET['callback'];
# Build query and Final URL
$queriesURL = http_build_query($queries) . "\n";
$finalURL = $host.$queriesURL;
echo $finalURL;
/* echo $finalURL output (I only edited the keys out):
https://www.googleapis.com/customsearch/v1?cx=XXX&key=XXX&q=Hatsune+Miku&result_count=10&callback=angular.callbacks._0
*/
// Setup Response
$response = file_get_contents($finalURL);
// workaround
$fixedResponse = str_replace("angular.callbacks._0_", "angular.callbacks._0", $response);
echo $fixedResponse;
?>
这是正确的Google API响应的一部分:
// API callback
angular.callbacks._0({
"kind": "customsearch#search",
"url": {
"type": "application/json",
"template": "https://www.googleapis.com/customsearch/v1?q={searchTerms}&num={count?}&start={startIndex?}&lr={language?}&safe={safe?}&cx={cx?}&cref={cref?}&sort={sort?}&filter={filter?}&gl={gl?}&cr={cr?}&googlehost={googleHost?}&c2coff={disableCnTwTranslation?}&hq={hq?}&hl={hl?}&siteSearch={siteSearch?}&siteSearchFilter={siteSearchFilter?}&exactTerms={exactTerms?}&excludeTerms={excludeTerms?}&linkSite={linkSite?}&orTerms={orTerms?}&relatedSite={relatedSite?}&dateRestrict={dateRestrict?}&lowRange={lowRange?}&highRange={highRange?}&searchType={searchType}&fileType={fileType?}&rights={rights?}&imgSize={imgSize?}&imgType={imgType?}&imgColorType={imgColorType?}&imgDominantColor={imgDominantColor?}&alt=json"
},
我提出了这个问题的实际版本,可以在FTP server上看到。可以通过此link查看PHP文件(包含AngularJS参数)。
答案 0 :(得分:1)
问题是转义序列\n
。哪个是作为请求的一部分传递的。它被解释为空格并作为回调函数名称的一部分,并被API的一侧替换为下划线。
要理解,只需尝试此选项并查看结果:
$queriesURL = http_build_query($queries) . "\n" . "after";
所以只需拿走换行符。