Having issues interpreting json inside php and passing it to mysql - javascript

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.

Related

Capturing an IP Address with Ajax involved

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.

Creating Javascript array via php

After spending an embarrassing number of hours on this, I still can't figure out an answer. I have a Javascript/HTML program that has a large dynamic table in it with lots of buttons in the cells of the table. I'd like to send the user's selections of buttons to a database when the user is finished with the page. I will then use those in the receiving php program to display a graph. I've got all of the values of the buttons into a Javascript array, so now I'd like to send the entire array and then use them as a Javascript array in the new program. Every time I try this, I get no results. Here is an example based on what I've found on stackoverflow:
Sending program:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<script>
var ourObj={};
ourObj.data="4";
ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];
$.ajax({
url: 'testb2.php',
type: 'post',
data: {"points" : JSON.stringify(ourObj)},
success: function(data) {
alert("success");
}
});
</script>
</html>
Receiving php program:
<?php>
// Test if our data came through
echo "starting";
if (isset($_POST["points"])) {
// Decode our JSON into PHP objects we can use
$points = json_decode($_POST["points"]);
// Access our object's data and array values.
echo "Data is: " . $points->data . "<br>";
echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y;
$servername = "localhost";
$username = "xxx";
$password = "yyy";
$dbname = "zzz";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "
INSERT INTO FootprintAction(UserID, ActionValue, fpID)
VALUES (?, ?, ?);
";
if ($stmt = mysqli_prepare($conn, $sql)) {
mysqli_stmt_bind_param($stmt, "iss", $points->data, "1", "1");
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
} else {
//echo "no result from attempt to insert people into fpAction". "<br>";
//echo $sql;
}
}
?>
What I get is a blank screen from the sending program with only an alert saying "success" (i.e., no answer from the receiving program) and no insertion into the database.
Can you suggest what I am doing wrong? Or even better, is there a simple way using php to get a javascript array from a client-side program to a server-side program? The array I'm trying to send is a set of string data, without labels; here's a row of the array:
actions[ 5] = new Array( "Install Photovoltaic (Solar) Panels","6.33","1020","33121","0","25","149.8","0","0","0","1","1","Photovoltaic (solar) systems allow you to produce green electricity on your own rooftop. Vendors often offer both purchase and lease options. ","3","1.5","10","5.75","0");
I'd like to end up with a Javascript array in the receiving program identical to that in the sending program.
Thanks!!!

Saving (with JS Request) and reading (with PHP) XML in MySQL

I'm trying to save some xml content (that I receive as plain text) into my site's database. I read about saving XML content and someone suggested it is not a good idea to save XML in a text field (database), so I decided to do it in a blob. The thing is I'm doing it via CORS, through javascript this way:
var formData = new FormData();
formData.append("name", 'myNewFile');
// THE XML CONTENT
var content = '<a id="a"><b id="b">hey!</b></a>';
var blob = new Blob([content], { type: "text/xml"});
formData.append("file", blob);
var request = new XMLHttpRequest();
request.open("POST", url);
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
resultsContainer.innerHTML = (request.responseText );
}
}
request.send(formData);
On the server, I store it with:
$name = $_POST['name'];
$file = $_POST['file'];
$sql = "INSERT INTO ProfileFiles (name, file)
VALUES ('$name', '$file')";
It seemed to work, the entry was created in the database but I can't see what's inside the BLOB field. So, I tried to read that from server, using PHP, but I'm retrieving just "0" in the file field.
$sql = "SELECT datetime, name, file FROM ProfileFiles";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Timestamp: " . $row["datetime"]."<br>";
echo "Name: " . $row["name"]. "<br>";
echo "Content: " + $row["file"];
echo "<br>----------<br>";
}
}
else
{
echo "Nothing";
}
What am I missing? Thanks in advance! I never worked with PHP.
The reason why you don't get anything in $_POST['file'], is that you are sending it as a file. Files that are posted are in the superglobal variable $_FILES not $_POST. $_FILES['file'] will contain an array
array('name' => '...', 'tmp_name' => '...', 'type' => '...', 'size' => '...');
The content will be saved to a temporary file whose name is stored in $_FILES['file']['tmp_name']
You see, you really go astray here... What you have to do is to send the XML data as a POST variable and not a file. When doing this, you can save the data to the database like you tried it, but with prepared statements, it will be something like (assuming you are using mysqli
$name = $_POST['name'];
$file = $_POST['file'];
$sql = "INSERT INTO ProfileFiles (name, file)
VALUES (?, ?)";
$stmt = $mysqli->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param("ss", $name, $file);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
The point of using a prepared statement is this :
If the file contains a ', you get an error in the query. Also your code is vulnerable to sql injection. You need to escape the strings in the query.
I never used mysqli myself, and the code I gave looks a bit clumsy, so here's an alternative :
$sql = "INSERT INTO ProfileFiles (name, file)
VALUES ('". mysqli_real_escape_string($name)."', '".mysqli_real_escape_string($file) ."')";

Why is my PHP script returning different results on similar inputs?

Background: I am doing ajax calls to a PHP script which returns data to fill a form based on some file key a user inputs. This form is used so users may edit an incorrectly inputted file key from their original submission.
Problem: If a user wanted to edit a file key, they input it into a text box, hit a button for an ajax pull, the form fills, they can then correct their mistakes and submit. However, if they try to edit the new file key again, the form will not fill and I am getting no results returned from the query. This is the php script I have been using to pull the data from the server.
A sample file key might be: 10000010000-0D-MAN.
This is a good response: 10000010000-0D-MAN,N/A,amibaguest,dfgfdgfd,Electrical
This is the response I get on a newly edited file key: Nothing returned. Id: 20000010000-0D-MAN.
Really baffled at the moment. If more information is needed, please let me know.
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("database", $dbhandle)
or die("Could not select database");
$id = $_GET['param'];
if(isset($_GET['param'])) {
$sql = sprintf("SELECT a.File_key, a.Name, a.Uploader, a.File_descriptor, b.keyword1 FROM files as a, keyword as b WHERE a.File_key='%s' AND a.File_key=b.File_key", mysql_real_escape_string($id));
$result = mysql_query($sql);
if($result === FALSE) {
echo mysql_error();
}
if(mysql_num_rows($result)==1) {
while($myrow = mysql_fetch_array($result)) {
$file_key = $myrow["File_key"];
$name = $myrow["Name"];
$uploader = $myrow["Uploader"];
$file_desc = $myrow["File_descriptor"];
$keyword = $myrow["keyword1"];
$text_out .= $file_key.",".$name.",".$uploader.",".$file_desc.",".$keyword;
}// end while
} else {
$text_out = " Nothing returned. Id: ".$id;
}// end else
}// endif
echo $text_out;

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