目前,我正在尝试接收使用网站上联系表格的用户的ip地址,并将其与其他信息一起发送到firebase。对于HTML和PHP,我使用了本教程中的确切代码:http://www.danielpinero.com/how-to-add-ip-address-html-form。
这是firebase代码:
// Initialize Firebase (ADD YOUR OWN DATA)
var config = {
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXXXXXXXXXXXXXX",
databaseURL: "XXXXXXXXXXXXXXXXXXXX",
projectId: "XXXXXXXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXXXXXXX",
messagingSenderId: "XXXXXXXXXXXX"
};
firebase.initializeApp(config);
// Reference messages collection
var messagesRef = firebase.database().ref('messages');
// Listen for form submit
el = document.getElementById('contactForm')
if(el){
el.addEventListener('submit', submitForm);
}
// Submit form
function submitForm(e){
e.preventDefault();
// Get values
var name = getInputVal('name');
var email = getInputVal('email');
var message = getInputVal('msg');
var ip = getInputVal('ip')
// Save message
saveMessage(name, email, message, ip);
// Clear form
document.getElementById('contactForm').reset();
}
// Function to get get form values
function getInputVal(id){
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(name, email, message, ip){
var newMessageRef = messagesRef.push();
newMessageRef.set({
name: name,
email:email,
message:message,
ip:ip
});
}
相反,我希望显示用户的实际IP。我是PHP的新手。如果有人可以帮助我,那就太好了。
编辑(index.php):
<form id="contactForm" method="post" class="cta">
<div class="col gtr-uniform gtr-50">
<div class="col-8 col-12-xsmall inputs"><input type="text" name="name" id="name" placeholder="Name" /></div>
<div class="col-8 col-12-xsmall inputs"><input type="email" name="email" id="email" placeholder="Email Address" /></div>
<div class="col-8 col-12-xsmall inputs"><textarea id="msg" rows="4" cols="50" placeholder="Message"></textarea></div>
<input id="ip" type="hidden" name="ip" value="<?=$ip;?>">
<div class="col-4 col-12-xsmall"><input type="submit" value="Get Started" class="fit primary" /></div>
</div>
</form>
答案 0 :(得分:0)
第一个问题是您在var ip = getInputVal('ip')
第二个问题是将此<input id="ip" type="hidden" name="ip" value="<?=$ip;?>">
更改为<input id="ip" type="hidden" name="ip" value="<?php echo $ip;?>">
使用它来获得更好的客户端IP结果:
<?php
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$ip = get_client_ip();
?>
现在,对于js变量,您可以通过多种方式填充它:
<script>var ip = "<?php echo $ip;?>"; </script>
或者您可以将其填充为隐藏输入的值,并通过js获取该值:
<script>var ip = document.getElementById('inputID').value; </script>