Capturing an IP Address with Ajax involved - javascript

I have a button that when pressed, allows the user to see a catalog. I am not collecting any information from the user at this point. I am only collecting what catalog they downloaded. I would like to change this to collect their IP Addresses to insert into my database.
Would all I have to do is create a variable in my PHP file like this:
$ip = $_SERVER["REMOTE_ADDR"];
Then add it into my PDO statement for inserting into the db?
I have read that many recommend checking $_SERVER["HTTP_X_FORWARDED_FOR"] as well. How could I check both and assign it to the one variable?
Am I doing this correctly?
AJAX
$('.downloadButton').on('click', function (event) {
$.ajax({
url: 'downloadCatalogSend.php',
type: 'POST',
data: {
catalog_name: catalog_name,
button_triggered: button_triggered
}
});
});
PHP
$ip = $_SERVER["REMOTE_ADDR"];
try {
$con = getConfig('pdo');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$catalog_download_insert = "INSERT INTO catalog_download_now
(catalog_name, button_triggered, date_sent, $ip)
VALUES(?, ?, NOW(), ?)
";
$catalog_download_stmt = $con->prepare($catalog_download_insert);
$catalog_download_stmt->execute(array($catalog_name, $button_triggered, $ip));
$hasError = false;
echo $hasError;
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}

Use the null coalesce operator:
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"] ?? $_SERVER["REMOTE_ADDR"];
This will prefer HTTP_X_FORWARDED_FOR (the client IP if the request came from a proxy) if it is set, else fall back to REMOTE_ADDR (the actual IP the request came from.)
Caveat: HTTP_X_FORWARDED_FOR can be easily forged by the client.
Also note, you have this:
$catalog_download_insert = "INSERT INTO catalog_download_now
(catalog_name, button_triggered, date_sent, $ip)
VALUES(?, ?, NOW(), ?)
";
Drop that dollar sign from $ip -- that should be the field name, not the value you're trying to store in it.

Related

Having issues interpreting json inside php and passing it to mysql

I am new to php and I am not sure how to debug this.
I am trying to pass json to a php page and then send that data to mySQL.
I think it is having issues interpreting the data inside the php file or getting the information to the php page. When I open the php file it gives signs that it is properly accessing the database.
Here is my javascript code:
var request = new XMLHttpRequest();
request.open('POST', 'http://website/saveF.php', true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.send(bInfo);
This is taking information in and passing it to a php file to then be added to a mySQL database.
Here is my php code:
This is decoding the jSon and then itterating over each entry inside the array. It then asks the question if it has a website listed or not and stores it into the appropriate table.
//as long as the connection is good then we keep it live.
include_once "head.php";
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
//gettting the information from the front end (index.html)
$inputJSON = file_get_contents('php://input');
//decode all the previously encoded information
$postThings = json_decode($inputJSON, TRUE);
$input = filter_var($postThings, FILTER_SANITIZE_STRING);
//create a variable the is the total length of our array
$totalNum = count($input);
//arrays start at 0
$i = 0;
//you can see where this is going. We have a while loop that will continue as long as i is less than totalnum. Ask me why i didn't use a for loop.... I don't have an answer.
while($i < $totalNum){
$var0 = $input[$i][0];
$var1 = $input[$i][1];
$var2 = $input[$i][2];
$var3 = $input[$i][3];
$var4 = $input[$i][4];
$var5 = $input[$i][5];
$var6 = $input[$i][6];
if($var1 == "Not Listed") {
$sql = "INSERT INTO missing(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
}else{
//here we set the information into the database.
$sql = "INSERT INTO companies(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$i++;
}
First, note that this line:
$input = filter_var($postThings, FILTER_SANITIZE_STRING);
Will return FALSE if sanitization fails on any of the array elements. In your code, you should be testing if($input) immediately after the sanitization.
Furthermore, you will want to sanitize your inputs further to avoid SQL injection and XSS attacks. (e.g. remove SQL escape characters and other injectable characters).
http://php.net/manual/en/mysqli.real-escape-string.php
Last, it is recommended that you use bound parameters or fully sanitized inputs to avoid a SQL injection attack.

How to search for error?

I'm using "Bootstrap Editable" with "in line editing".
I'm printing a table with data from MySQL.
Now i´d like to be able to edit a cell and update my database with PHP.
The "in line edit" script works fine.
But the mysql update doesn't.
Now, when i turn on "php error mode" or tries to "JS alert" my variables in post php, to check if they holds data i can't see any errors or alerts on the front page.
How can i read the error codes or alerts?
This is my code:
HTML
echo "<td><a href='#' id='element_ant' data-type='text' data-pk='".$row['id']."' data-url='php/posts.php' data-title='Anteckning..'>".$row['element_ant']."</a></td>";
PHP
if($_POST['name']=='element_ant'){
$id=$_POST['pk'];
$element_ant=$_POST['value'];
//Prepare query
$query = "SELECT COUNT(*) as count FROM table WHERE id=$id";
try{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
//Result from query
$row = $stmt->fetch();
//Deside insert or update
if($row[0]==0){
$query = "INSERT INTO table(id,element_ant) VALUES(:id,:element_ant)";
}
else{
$query = "UPDATE table SET element_ant = :element_ant WHERE id = :id";
}
// Security measures
$query_params = array(':id' => $id,':element_ant' => $element_ant);
//Connect and execute
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
}
JS
$(document).ready( function () {
$('#element_ant').editable({
url : '../php/elements.php',
title : 'Enter comments'
});
});
1) The url attribute is duplicated, i.e you have declared it as data-url in your HTML and in your Js code as url:. Decide which one is right and use either, not both.
2) In your php, there is if($_POST['name']=='element_ant'); you have to set it in your editable HTML element as such:
<a href='#' id='element_ant' data-name="element_ant"
When the Editable object is being saved, the data-name will be passed as a POST parameter name.
For Client-Side Debugging: Firebug
For Server-Side Debugging: Xdebug
I think you can use some sort of logging framework , or you can write your own logging functions to log your error code on the file system.

after insert no return anything but data have been save

<?php
$host="localhost";
$user="root";
$password="";
$con=mysqli_connect("localhost","root","","recipe");
if ($_GET['type'] == "upload")
{
$title=$_GET['title'];
$creator=$_GET['creator'];
$ingredient=$_GET['ingredient'];
$serving=$_GET['serving'];
$note=$_GET['note'];
$prepare=$_GET['prepare'];
$insertsql = "INSERT INTO upload (title,creator,ingredient,serving,note,prepare)
VALUE ('$title','$creator','$ingredient','$serving','$note','$prepare')";
if(mysql_query($insertsql,$db))
{echo 1; }
else
{echo 0; }
}
?>
<script>
$.ajax({
type : "get",
url : "dataconn.php",
data : "type=upload&title="+title+"&prepare="+prepare+"&creator="+creator+"&ingredient="+ingredien t+"&serving="+serving+"&note="+note,
success : function(data){
alert(data);
}
});
</script>
</head>
</html>
When I pass variable in to PHP from JavaScript it able to save in database but I need some value like the data have been successful save and will come out a alert 1 or 0.
But once I connect to database it cant alert any more. Like some error blocking in database but still can save just does not come out any alert. If I remove it then it running all
It does not sure alert as well.
Change this line:
if(mysql_query($insertsql,$db))
To this line; using mysqli_* extensions and correctly using $con for the query instead of $db which is a connection variable you don’t have set anywhere:
if(mysqli_query($con,$insertsql))
Also, you should set your MySQL calls to return errors like this:
$con=mysqli_connect("localhost","root","","recipe") or die(mysqli_connect_errno());
And change this as well:
$result = mysqli_query($con,$insertsql) or die(mysqli_connect_errno());
if ($result) {
echo 1;
}
else {
echo 0;
}
Also you are using VALUE in the query when it should be VALUES:
$insertsql = "INSERT INTO upload (title,creator,ingredient,serving,note,prepare)
VALUES ('$title','$creator','$ingredient','$serving','$note','$prepare')";
Not to mention in your JavaScript AJAX code you have +ingredien t+ when it should be +ingredien t+:
data : "type=upload&title="+title+"&prepare="+prepare+"&creator="+creator+"&ingredient="+ingredient+"&serving="+serving+"&note="+note,
At the top why are you setting variables for the MySQL connection but then putting values inline?
$host="localhost";
$user="root";
$password="";
$con=mysqli_connect("localhost","root","","recipe");
And finally, I did a cleanup of your main MySQL logic code. I have included mysqli_stmt_bind_param, mysqli_free_result & mysqli_close and set a foreach loop for $_GET values. This simply should work:
// Credentials.
$host="localhost";
$user="root";
$password="";
// Connecting, selecting database
$con = mysqli_connect($host, $user, $password, 'recipe') or die(mysqli_connect_errno());
if (isset($_GET['type']) && !empty($_GET['type']) && $_GET['type'] == "upload") {
// Set a '$_GET' array and roll through each value.
$get_array = array('title', 'creator', 'ingredient', 'serving', 'note', 'prepare');
foreach ($get_array as $get_key => $get_value) {
$$get_value = isset($_GET[$get_value]) && !empty($_GET[$get_value]) ? $_GET[$get_value] : null;
}
// Set the query.
$insertsql = "INSERT INTO `upload` (`title`, `creator`, `ingredient`, `serving`, `note`, `prepare`)"
. " VALUES (?, ?, ?, ?, ?, ?)"
;
// Bind the params.
mysqli_stmt_bind_param($insertsql, 'ssssss', $title, $creator, $ingredient, $serving, $note, $prepare);
// Run the query.
$result = mysqli_query($con, $insertsql) or die(mysqli_connect_errno());
if ($result) {
echo 1;
}
else {
echo 0;
}
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
}

Passing data from ajax to php to mysql weird problems

I asked a similar question earlier, but think I got the wrong point across and learned more about security than fixing the problem I'm having. I am having trouble with my ajax request to post data into a php script and then submit it to a database.
Just to make it clear, the site is local and I will have nobody creating an account besides me and I will be the only one accessing it. I will make it secure once I get this step finished.
Current error I am getting: none, but no data after the success in alert("success" + data)
I have googled/worked for 10+ hours just on this... Any help would be greatly appreciated as I am just learning.
Here is my Javascript:
var firstname = String($("#firstname").val());
var lastname = String($("#lastname").val());
var username = String($("#username").val());
var email = String($("#email").val());
var password = String($("#password").val());
Here is the AJAX:
$.ajax({
type: 'POST',
url: 'create_account.php',
data: {firstname_php: firstname,
lastname_php: lastname,
username_php: username,
email_php: email,
password_php: password},
success: function(data) {
alert("success" + data);
}
});
create_account.php:
$firstname = $_POST['firstname_php'];
$lastname = $_POST['lastname_php'];
$username = $_POST['username_php'];
$email = $_POST['email_php'];
$password = $_POST['password_php'];
echo "$firstname";
// Create connection
$connection = mysqli_connect("localhost","root","root","MyDatabase");
// Check connection
if (mysql_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO users (user_id, user_firstname, user_lastname, user_username, user_email, user_password) VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password)'";
$result = mysqli_query($connection,$sql);
mysqli_close($connection);
You have a single quote in the wrong place in your query:
VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password)'";
^^^
try this:
VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password')";
Everything looks fine in the javascript and ajax (at least as well as I can tell without seeing the html source as well.
However you have at least one php error; mysql_connect_errno doesn't exist and wouldn't be called in relation to the mysqli connector.
so try this instead:
$firstname = $_POST['firstname_php'];
$lastname = $_POST['lastname_php'];
$username = $_POST['username_php'];
$email = $_POST['email_php'];
$password = $_POST['password_php'];
echo "$firstname";
// Create connection
$connection = mysqli_connect("localhost","root","root","MyDatabase");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO users (user_id, user_firstname, user_lastname, user_username, user_email, user_password) VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password')";
$result = mysqli_query($connection,$sql);
mysqli_close($connection);
I haven't used the mysqli connector but other than that it looks fine to me. If it still doesn't work I suggest enabling full php debug info - for example adding this to the top of the php file:
ini_set("display_errors", "1");
error_reporting(E_ALL);
EDIT: as hanlet stated you also have a single quote/apos in the wrong spot. (fixed in my example code)

xmlHttp2 function (var params coding needed!)

In this page where this code is,there is a form of 3 details
country,gender,topic
So the idea is to send these 3 details to startChat.php and so that the php can extract the 3 details.
The code is as below
function startChat()
{
xmlHttp2 = GetXmlHttpObject();
if (xmlHttp2 == null)
{
alert("Browser does not support HTTP Request");
return;
}
var url = "startChat.php";
var params = "country,gender,topic";<<<<<<<<<<<<<<<<<<<<<<<what coding this should be?????
xmlHttp2.open("GET", url, true);
xmlHttp2.send(params);<<<<<<<<is this correct?????
xmlHttp2.onreadystatechange = stateChanged2;
}
And also i would need help with the startChat.php part
<?php
include('config.inc.php');
$preference="$_GET[params]";<<<<<<<<<<<<<<<<<<<<<<<<<<<<what coding this should be????????????????????????????????????
include('database.inc.php');
mysql_query("INSERT INTO users (inchat,preference) values('N','$preference')");
echo mysql_insert_id();
mysql_close($con);
?>
Please help,asking sincerely :(
First off, you ought to use a POST request instead of a GET, because it's clear from your code that this request is supposed to change state on the server.
Your params variable should be form encoded. You can do this with encodeURIComponent, like so:
var params = 'country=' + encodeURIComponent(userCountry) +
'&gender=' + encodeURIComponent(userGender) +
'&topic=' + encodeURIComponent(userTopic);
Second, you ought to sanitize the data before you insert it into your DB. Otherwise you expose yourself to SQL injection attacks.
<
?php
include('config.inc.php');
// need to create db connection before mysql_real_escape_string is called
include('database.inc.php');
$country = mysql_real_escape_string($_POST['country'], $con);
$gender = mysql_real_escape_string($_POST['gender'], $con);
$topic = mysql_real_escape_string($_POST['topic'], $con);
mysql_query("
INSERT INTO users(inchat, country, gender, topic)
VALUES('N','$country', '$gender', '$topic')
");
echo mysql_insert_id();
mysql_close($con);
?>
Note that I've also changed your DB structure. In general, it's best to avoid putting more than one piece of data into a single field (DB normalization).

Categories