这是我目前的代码:
<?php
$key = $_REQUEST['key'];
$url = $_REQUEST['url'];
include_once '../../dbconnect.php';
$query = $conn->query("SELECT * FROM members WHERE apikey='$key' && status='Active'");
$userRow=$query->fetch_array();
$conn->close();
/// Verify the URL starts with http:// or https://
if (0 === strpos($url, 'http://') || 0 === strpos($url, 'https://')) {
$url = $url;
} else {
$url = "http://$url";
}
/// Verify the key is 32 characters
if (!preg_match('/[^A-Za-z0-9]/', $key) && (strlen($key) == 32)) {
/// Verify the URL isn't malicious
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
die('Error: Invalid URL');
} else {
if ($userRow['status'] === 'Active') {
function generateRandomString($length = 8) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$redirect = generateRandomString();
$addshort = $conn->query("INSERT INTO short_".$redirect[0]." (redirect, apikey, url) VALUES ('".$redirect."','".$key."','".$url."')");
if ($conn->query($addshort) === TRUE) {
echo "added correctly";
} else {
echo "there was an error";
}
$conn->close();
} else {
echo "Error: Account Not Active";
}
}
} else {
die('Error: Invalid API Key');
}
?>
这是error_log:
[18-Oct-2016 12:21:31 America/New_York] PHP Warning: mysqli::query(): Couldn't fetch mysqli in /home/username/public_html/subdomains/url/index.php on line 40
[18-Oct-2016 12:21:31 America/New_York] PHP Warning: mysqli::query(): Empty query in /home/username/public_html/subdomains/url/index.php on line 42
[18-Oct-2016 12:21:31 America/New_York] PHP Warning: mysqli::close(): Couldn't fetch mysqli in /home/username/public_html/subdomains/url/index.php on line 48
您可以在第7行看到我第一次连接到数据库:
$query = $conn->query("SELECT * FROM members WHERE apikey='$key' && status='Active'");
这条线正在运作。但是,我第二次连接INSERT
时,我遇到了上述错误:
$addshort = $conn->query("INSERT INTO short_".$redirect[0]." (redirect, apikey, url) VALUES ('".$redirect."','".$key."','".$url."')");
在长时间盯着这段代码时,我有什么遗漏吗?
答案 0 :(得分:3)
在执行第一个SELECT语句后,您的连接已关闭,这意味着连接已提前关闭:
$conn->close();
您需要在所有查询或重新建立连接后使用close()
。是一个更好的选择。
您正在获取用户输入$_REQUEST['key']
,这意味着您的查询已打开以进行SQL注入,这将帮助您了解如何使用SQL注入阻止您的代码:How can I prevent SQL injection in PHP?
答案 1 :(得分:-1)
此:
$addshort = $conn->query("INSERT ...')");
^^^^^^^
if ($conn->query($addshort) === TRUE) {
^^^^^
$addshort
是您的查询结果/句柄/对象,然后您尝试执行 AGAIN ,这不起作用。 query()
需要一个SQL字符串,并且您正在传入一个对象。
最重要的是,你很容易受到sql injection attacks的攻击。</ p>