我想为我正在处理的事情做API,但我无法弄清楚如何修复我现在拥有的东西。
我想要登录,如果密钥正确并且匹配数据库中的IP然后做其他事情
if (isset($_GET['key'])) {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$apikey = $_GET['key'];
//$apikey = mysql_real_escape_string($api);
echo $apikey."<br />".$ip;
$mysql_host = "**.***.**.***";
$mysql_database = "*****";
$mysql_user = "********";
$mysql_password = "******************";
mysql_connect($mysql_host,$mysql_user,$mysql_password);
@mysql_select_db($mysql_database) or die("Unable to select database");
$query="SELECT * FROM `api` WHERE `apikey` = '".$apikey."' AND `ip`='".$ip"'";
$result=mysql_query($query);
if (!$result) {
die(mysql_error());
}
// assign mySQL values from table to php variables
$teest = mysql_result($result,1,'apikey');
echo $teest;
//close the mySQL connection
mysql_close();
} else {
echo "Usage: api.php?key={YourUniqueKey}";
}
答案 0 :(得分:0)
a)提供mysql_ *函数的扩展名标记为deprecatd。最好使用mysqli或PDO。
b)您将两个参数(作为字符串文字)放入sql查询中。两个(字符串)参数必须正确编码/转义,以便它们不会干扰实际查询(结构) 这是由mysql_real_escape_string完成的。但是此功能需要来自连接资源(即连接字符集)的一些信息才能正常工作。因此,只有在您建立了mysql连接viw mysql_connect之后,才能调用mysql_real_escape_string()。
<?php
if ( !isset($_GET['key']) ) {
echo "Usage: api.php?key={YourUniqueKey}";
}
else {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$apikey = $_GET['key'];
echo htmlspecialchars($apikey)."<br />".htmlspecialchars($ip);
$mysql_host = "**.***.**.***";
$mysql_database = "*****";
$mysql_user = "********";
$mysql_password = "******************";
$link = mysql_connect($mysql_host,$mysql_user,$mysql_password) or die('database connection failed');
mysql_select_db($mysql_database, $link) or die("Unable to select database");
$query = sprintf(
"
SELECT
COUNT(*)
FROM
api
WHERE
apikey='%s'
AND ip='%s'
",
mysql_real_escape_string($apikey, $link),
mysql_real_escape_string($ip, $link)
);
$result=mysql_query($query, $link);
if (!$result) {
die(mysql_error());
}
$row = mysql_fetch_row($result);
if ( '1'==$row[0] ) {
echo 'yay';
}
else {
echo 'nay';
}
}