虽然这是我的第一个API,但我正在构建一个API来支持一个站点,并提供一个应用程序,我正在寻找一些问题领域,并希望在可能的情况下提供一些建议/提示。
我计划让外部API使用用户名/密码和API密钥进行身份验证,但是,我并不真正希望内部API具有这两种方法。这是因为我希望将来可能分发脚本,并且不希望有人找到用于访问内部API的任何访问代码,在那里他们可以使用这些访问代码访问外部API (任何使用该脚本的站点)。
理想情况下,我希望将这两个API放在一起,以便更容易地管理它们。
以确保对API的直接访问,以便没有人能够尝试直接包含它(在.htaccess中):
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^.*$ - [R=401,L]为了访问外部API,需要进行以下操作(在PHP中):
$url = "http://www.mydomain.com/script/api.php";
$username = "username";
$password = "password";
$apikey = "12345678901234567890";
$postfields = array();
$postfields["username"] = $username;
$postfields["password"] = md5($password);
$postfields["apikey"] = md5($apikey);
$postfields["action"] = "getclients";
$postfields["format"] = "json";
$query_string = "";
foreach ($postfields AS $k=>$v) $query_string .= "$k=".urlencode($v)."&";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$jsondata = curl_exec($ch);
if (curl_error($ch)) die("Connection Error: ".curl_errno($ch).' - '.curl_error($ch));
curl_close($ch);
$array_out = json_decode($jsondata);但是,我不确定(确切地)在我的后端中包含内部API的最佳方法--我曾经想过,也许我可以(在PHP中)执行以下操作:
$postfields = array();
$postfields["action"] = "getclients";
$postfields["format"] = "json";
ob_start();
include("script/api.php");
$array_out = json_decode(ob_get_contents());
ob_end_flush();但是,由于我在API中发送头header ("content-type: text/json charset=utf-8");,火狐只希望我保存输出而不是传递它。我尝试过不发送标题,但是所有API变量都通过包含它的页面传递--这是我不想要的。
我的问题是:
F 213
事先非常感谢!
发布于 2011-09-06 08:57:07
在您的.htaccess中,[OR]的工作方式与我认为您使用它的方式不同。所有RewriteCond都适用于下一个RewriteRule,因此不需要“或”。其次,还需要规则将API请求推送到某种类型的dispatcher文件,如下所示:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* dispatcher.php我不认为通过cURL等在内部调用API函数是有意义的--特别是因为您必须通过身份验证等。在我看来,在内部拥有一个可以直接调用的(面向对象的)‘API’集合会更有意义,比如API::getClients()。然后构建一个dispatcher脚本,将所有传入的Ajax请求推送到其中。该脚本将执行以下操作:
authentication
希望你明白我的意思:)
https://stackoverflow.com/questions/7317167
复制相似问题