我有一个网站,可以让我获取客户端设备的IP地址,用户代理和主机名。我已将其设置为保存到MySQL数据库,但是当我查看phpmyadmin时,它不会出现。
这是我的代码:
<?php
$servername = "localhost";
$username = "[USERNAME GOES HERE - OBSCURED TO PROTECT]";
$password = "[PASSWORD GOES HERE - OBSCURED TO PROTECT]";
$dbname = "[DBNAME GOES HERE - OBSCURED TO PROTECT]";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$ip = $_SERVER['REMOTE_ADDR'];
$user = $_SERVER['HTTP_USER_AGENT'];
$host = gethostbyaddr($_SERVER['REMOTE_ADDR']);;
$sql = mysqli_query($conn, "INSERT INTO data (ipaddress, useragent, hostname)
VALUES ($ip, $user, $host)");
?>
<!DOCTYPE html>
<html>
<head>
<title>IP Address</title>
<style>
body {
margin: 0;
}
</style>
</head>
<body>
<h1>IP address recorded!</h1>
</body>
<?php
mysqli_close();
?>
有什么想法吗?
答案 0 :(得分:2)
您容易受sql injection attacks攻击,并且多个SQL语法错误 - 没有引用任何数据值,因此您将BARE文本填充到查询中。
$sql = [..snip..] "... VALUES ('$ip', '$user', '$host')") or die(mysqli_error($conn));
^---^--^-----^--^-----^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
注意引号和or die()。如果你有引号,查询可能有效。如果您拥有or die
,那么您首先会被告知您的查询失败。
答案 1 :(得分:-1)
由于我假设您的字段是char或varchar类型,因此每个变量
需要一个引号$ip = mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']);
$user = mysqli_real_escape_string($conn, $_SERVER['HTTP_USER_AGENT']);
$host = gethostbyaddr($ip);
$sql = mysqli_query($conn, "INSERT INTO data (ipaddress, useragent, hostname)
VALUES ('$ip', '$user', '$host')");