在 PHP 联系表单中获取用户的 IP 地址

3

我正在尝试从php联系表单中获取用户IP地址,我有以下代码,但我想知道是否可以使用clean_string以这种方式向自己发送IP地址的电子邮件?

<?php

session_start();




if(isset($_POST['fullname'])) {

include 'freecontact2formsettings.php';

function died($error) {
    echo "Sorry, but there were error(s) found with the form you submitted. ";
    echo "These errors appear below.<br /><br />";
    echo $error."<br /><br />";
    echo "Please go back and fix these errors.<br /><br />";
    die();
}

if(!isset($_POST['fullname']) ||
    !isset($_POST['Address1']) ||
    !isset($_POST['city']) ||   
    !isset($_POST['Postcode']) ||
    !isset($_POST['contactnum']) ||
    !isset($_POST['emailaddress'])







    ) {
    died('Sorry, there appears to be a problem with your form submission.');        
}
$ip = $_SERVER['HTTP_CLIENT_IP']; 
$ansb0_from = $_POST['fullname']; // required
$ansb1_from = $_POST['Address1']; // required
$ansb3_from = $_POST['city']; // required   
$ansb4_from = $_POST['Postcode']; // required
$ansb5_from = $_POST['contactnum']; // required
$ansb6_from = $_POST['emailaddress']; // required


$error_message = "";


$email_message = "PHP CONTACT FORM:\r\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:");
  return str_replace($bad,"",$string);
}


$email_message .= "Forename: ".clean_string($ansb0_from)."\r\n";
$email_message .= "Address 1: ".clean_string($ansb1_from)."\r\n";
$email_message .= "City: ".clean_string($ansb3_from)."\r\n";
$email_message .= "Postcode: ".clean_string($ansb4_from)."\r\n";
$email_message .= "Contact Number: ".clean_string($ansb5_from)."\r\n";
$email_message .= "Email Address: ".clean_string($ansb6_from)."\r\n";
$email_message .="IP Address: ".clean_string($ip)."\n\n"; 











$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email_to, $email_subject, $email_message, $headers);
header("Location: $thankyou");
?>
<script>location.replace('<?php echo $thankyou;?>')</script>
<?php
}
die();
?>

此外,
$ip = $_SERVER['HTTP_CLIENT_IP'];

这个问题出在联系表单脚本页面上,而不是用户输入信息的实际form.php页面上。我认为这就是我的错误所在,对吗?


1
请使用此代码 $_SERVER['REMOTE_ADDR']; - Vahid Farahmand
附注 - 在您的clean_string()函数中使用str_ireplace()而不是str_replace(),以进行不区分大小写的匹配。但是,对于意识到电子邮件注入的人加1分,这里似乎很少有人注意到。 - Michael Berkowski
除非它是 X_FORWARDED_FOR。查看 phpBB 的源代码并找到他们如何获取用户的 IP(以及检查代理等)。 - Brad Christie
2个回答

10
你不希望在表单本身中包含IP。这样可以显示,编辑和更改它。相反,只需使用以下内容在服务器端捕获它:$_SERVER['REMOTE_ADDR'];
顺便提醒一下,谷歌搜索此问题应该可以返回50亿个有效结果。

@BradChristie:我现在仔细看了一下代码,你是对的。标题只是有点让我困惑。如果他使用正确的服务器变量,他的方法是正确的。 - OptimusCrime

1
你想要检查$_SERVER["REMOTE_ADDR"]$_SERVER["HTTP_X_FORWARDED_FOR"] 两者,因为如果用户在代理服务器后面,后者可能是必要的。
你可以在这里阅读更多: https://dev59.com/O3A75IYBdhLWcg3w-OVA#3003233

除非你知道是谁设置了代理 forwarded-for 头信息,否则不要依赖于它。任何用户都可以在请求中包含此头信息并伪造他们的 IP。 - deceze

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接