Can not store HTML when sent to php/sql through ajax - php

I'd like to store some div content when a button is pressed. I need/want to save the html tags as well in order to reuse.
When I replace the post variables by any type of string, it works flawlessly. I tried cleaning the html variable from line breaks but it didn't do it, tried also to shell the $HTML post in a $var = <<<HTML HTML, but this didn't work either.
Here is the javascript :
$("#save").click(function(){
var pageHTML = $("#page_wrap").html();
var name_page = "name";
jQuery.ajax({
type: "POST",
url: "php/saveModel.php",
data: { nHTML: pageHTML,
page : name_page
},
success:function(data){
var responseData = jQuery.parseJSON(data);
var new_div = responseData.message;
$("#page_wrap > *").remove();
$("#page_wrap").prepend(new_div);
$('.editable').aloha();
}
})
})
And here is the php :
<?php
mysql_connect('localhost','name','pwd');
mysql_select_db('db');
mysql_query("SET NAMES 'utf8'");
$id = $_POST['page'];
$HTMLpost = $_POST['nHTML'];
$insertSignup = mysql_query("UPDATE Table_name SET model_test='$HTMLpost' WHERE identifiant='$id'");
if($insertSignup){
$status = "success";
$message = "OK";
}
else {
$status = "error";
$message = "NOT OK";
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
?>
Thanks !

Simple answer: use mysql_real_escape_string() to change the quotes to make it safe for entry into the database.
$HTMLpost = mysql_real_escape_string($_POST['nHTML']);
$insertSignup = mysql_query("UPDATE Table_name SET model_test='$HTMLpost' WHERE identifiant='$id'");
Longer answer: You should not be using the mysql_() functions as they are being depreciated. Check out prepared statements with PDO or mysqli instead - they will safely handle this for you (and they are not being depreciated).
Reading: http://php.net/manual/en/pdo.prepared-statements.php or google for more - plenty of examples around. Best to learn now before you get stung when the mysql_() functions do get removed.

Related

Whether a website search coded with PHP (with .txt file as indexing file) vulnerable to any attacks (like SQL Injection & XSS)?

I have a website search coded with PHP. It is essentially a PHP-AJAX search which gets triggered on onkeyup event of the search input field. The onkeyup triggers an AJAX call to a PHP file which reads indexes-file.txt file containing the indexes, by using PHP's file() function.
Although, here I am not dealing with Database, so I think that there is no chance for SQL-Injection or an XSS attack (correct me if I am wrong).
Also, I know about mysqli_real_escape_string() and htmlentities() function, their importance, and use case. What I am trying to know is whether this particular PHP-AJAX method is vulnerable or not.
Further, is there any other type of vulnerability exists in this type of case apart from server-side vulnerabilities?
The onkeyup function is:
function results(str) {
var search_term = $("#search")
.val()
.trim();
if (search_term == "") {
// ...
} else {
$.ajax({
url: "websearch.php",
type: "post",
data: {
string: search_term
},
dataType: "json",
success: function(returnData) {
for(var i in returnData) {
for(var j in returnData[i]) {
$('#results').append('<div><a target="_blank" href="'+returnData[i][j]+'">'+Object.keys(returnData[i])+'</a></div>');
}
}
}
});
}
}
the indexes-file.txt contains:
books*books.php
newspaper*newspaper.php
download manual*manual.php
...
and my websearch.php file contains:
<?php
error_reporting(0);
$indexes = 'indexes-file.txt';
$index_array = file($indexes, FILE_IGNORE_NEW_LINES);
foreach($index_array as $st) {
$section = explode('*', $st);
$k = $section[0];
$kklink = $section[1];
$l_arr[] = array($k => $kklink);
}
//Get the search term from "string" POST variable.
$var1 = isset($_POST['string']) ? trim($_POST['string']) : '';
$webresults = array();
//Loop through our lookup array.
foreach($l_arr as $kk){
//If the search term is present.
if(stristr(key($kk), $var1)){
//Add it to the results array.
foreach($kk as $value) {
$webresults[] = array(key($kk) => $value);
}
}
}
//Display the results in JSON format so to parse it with JavaScript.
echo json_encode($webresults);
?>
If you are not dealling with database it may be not vulnerable to sql injection but it's probably vulnerable to xss to prevent xss and script execution you should use:
Prevent XSS
PHP htmlentities() Function
basic example of filter the inputs
<?php
echo '<script>alert("vulnerable");</script>'; //vulnerable to xss
?>
filtering the inputs with htmlentities()
<?php
$input = '<script>alert("vulnerable");</script>';
echo htmlentities($input); //not vulnerable to external input code injection scripts
?>
so it prevent script and html tags injection from execute on site
read more here
for database you should use pdo with prepared statements
Prevent SQL injection
Use PDO
Correctly setting up the connection
Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
read more here
Fixing your code
<?php
error_reporting(0);
$indexes = 'indexes-file.txt';
$index_array = file($indexes, FILE_IGNORE_NEW_LINES);
foreach($index_array as $st) {
$section = explode('*', $st);
$k = $section[0];
$kklink = $section[1];
$l_arr[] = array($k => $kklink);
}
//Get the search term from "string" POST variable.
$var1 = isset($_POST['string']) ? trim($_POST['string']) : '';
$webresults = array();
//Loop through our lookup array.
foreach($l_arr as $kk){
//If the search term is present.
if(stristr(key($kk), $var1)){
//Add it to the results array.
foreach($kk as $value) {
$webresults[] = array(key($kk) => $value);
}
}
}
//Display the results in JSON format so to parse it with JavaScript.
echo htmlentities(json_encode($webresults));
//fixed
?>
Everytime you echo something from the outside use htmlentities
echo htmlentities(json_encode($webresults));
Your array problem I tested with a demo json string it's working fine
<?php
$webresults =
'
{ "aliceblue": "#f0f8ff",
"antiquewhite": "#faebd7",
"aqua": "#00ffff",
"aquamarine": "#7fffd4",
"azure": "#f0ffff",
"beige": "#f5f5dc",
"bisque": "#ffe4c4",
"black": "#000000",
}';
echo htmlentities(json_encode($webresults));
?>

Select Query doesnt work on ajax file

$('select[name="third_category"]').change(function() {
var first_cat = $('#main_category').val();
var second_cat = $('#top_category').val();
var third_cat = $(this).val();
$.ajax({
type:'POST',
url:'ajax/fields_ajax.php',
data:{'first_cat':first_cat, 'second_cat':second_cat, 'third_cat':third_cat},
success:function(data){
var field_box = document.getElementsByClassName('field_box');
$(field_box).append(data);
}
});
});
My goal is, when user select third option i collect all the option's values on the page. Then i'm going to use them for my mysql queries. That is my fields_ajax.php file.
<?php
session_start();
ob_start();
include 'inc/session.php';
include 'inc/config.php';
include 'inc/mysql.class.php';
ini_set('display_errors', 0);
if( isset($_POST) ){ // secure script, works only if POST was made
$first_cat = $_POST[first_cat];
$second_cat = $_POST[second_cat];
$third_cat = $_POST[third_cat];
$category_field_query = "SELECT * FROM categories WHERE id = $first_cat";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
echo "<p>".$cat_field->fields."</p>";
} ?>
I can carry all values without problem. But when i use them on query, there's no response. Mysqli connection working correctly, my query works on other php files. And when I try something else instead of trying mysql query, ajax file response it without problem.

Inserting Variables From Jquery Always Fails

i have some problem, i made some local website using php.
I have a file called functions.php which this is the code:
public function saveAll($idmt_salesarea, $thn_bln, $no_pesanan, $tgl_pesan, $idms_langganan, $idms_kodebarang, $quantity, $harga, $jumlah, $disc_cash, $disc_kredit){
$message = "Waiting input...";
try{
$con = new db();
$conn = $con->connect();
$query = "INSERT INTO mt_pesanan(idmt_salesarea,thn_bln,no_pesanan,tgl_pesan,idms_langganan, idms_kodebarang,quantity,harga,jumlah,disc_cash,disc_kredit) VALUES ($idmt_salesarea, '$thn_bln', '$no_pesanan', '$tgl_pesan', $idms_langganan, $idms_kodebarang, '$quantity', $harga, $jumlah, '$disc_cash', '$disc_kredit')";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn) . " " . mysqli_errno());
if($result == 1){
$message = "Success";
} else if($result == 0){
$message = "Failed";
}
}catch(Exception $exc){
echo $exc->getCode();
}
$con->disconnect();
return $message;
}
i Take the input parameter from file called: index.php and pass the parameter using AJAX Jquery. The parameter itself is sent and pointing to file called insert.php
here's the insert.php file:
<?php
include_once 'functions.php';
$idmt_salesarea = isset($_GET['salesarea']);
$thn_bln = isset($_GET['thn_bln']);
$no_pesanan = isset($_GET['nopes']);
$tgl_pesan = isset($_GET['tglpes']);
$idms_langganan = isset($_GET['idlangganan']);
$idms_kodebarang = isset($_GET['idbarang']);
$quantity = isset($_GET['quantity']);
$harga = isset($_GET['harga']);
$jumlah = isset($_GET['jumlah']);
$disc_cash = isset($_GET['disc_cash']);
$disc_kredit = isset($_GET['disc_kredit']);
if (($disc_cash == null) || ($disc_kredit == null)) {
$disc_cash = 0;
$disc_kredit = 0;
}
$insert = new functions();
$insert->saveAll($idmt_salesarea, $thn_bln, $no_pesanan, $tgl_pesan, $idms_langganan, $idms_kodebarang, $quantity, $harga, $jumlah, $disc_cash, $disc_kredit);
?>
but when i check the error, that is the variable that cannot get from insert.php file (using $_GET statement).
How proper way to gain the variable? because all the parameter is set.
I know this is combining object oriented style and old fashion php coding. Any ideas?
thanks in advance.
UPDATE
here's the index.php file using jquery ajax to sent the data
function sendAll(){
var tgl_pesan = $('#dpc').val();
var sales_area = $('#sales_area').val();
var nopes = $('#no_pesanan').val();
var thnbln = getTahunBulan();
var id_langganan = $('#kode_langganan').val();
var id_barang = $('#kode_barang').val();
var quantity = getQuantity();
var harga = $('#harga').val();
var jumlah = $('#jumlah').val();
var disc_cash = $('#cash').val();
var disc_kredit = $('#kredit').val();
var max = $('#max').val();
$.ajax({
type:"POST",
**url:"insert.php",**
data:{
salesarea:sales_area,
thn_bln:thnbln,
nopes:nopes,
tglpes:tgl_pesan,
idlangganan:id_langganan,
idbarang:id_barang,
quantity:quantity,
harga:harga,
jumlah:jumlah,
disc_cash:disc_cash,
disc_kredit:disc_kredit,
max:max
},
success:function(msg){
alert("Data Inserted");
},
error:function(msg){
alert("Data Failed to save" + msg);
}
});
the ajax itself is pointing to file insert.php which the insert.php is executing function from another file called functions.php
The problem is with this code:
$idmt_salesarea = isset($_GET['salesarea']);
$thn_bln = isset($_GET['thn_bln']);
$no_pesanan = isset($_GET['nopes']);
$tgl_pesan = isset($_GET['tglpes']);
$idms_langganan = isset($_GET['idlangganan']);
$idms_kodebarang = isset($_GET['idbarang']);
$quantity = isset($_GET['quantity']);
$harga = isset($_GET['harga']);
$jumlah = isset($_GET['jumlah']);
$disc_cash = isset($_GET['disc_cash']);
$disc_kredit = isset($_GET['disc_kredit']);
For each of those variables, you are assigning the result of isset(), which will evaluate to either TRUE or FALSE. If you want to bind the actual value of your $_GET input, change each line from this syntax:
$idmt_salesarea = isset($_GET['salesarea']);
To
$idmt_salesarea = isset($_GET['salesarea']) ? $_GET['salesarea'] : '';
However this code isn't really maintainable, and I would also recommend using arrays instead of passing that many arguments to your saveAll() method.
In response to your update
If you are sending an AJAX request with type: "POST", you cannot access your input data via the PHP $_GET super global, you have to use $_POST. However, what I said before is still valid, as you aren't binding values to your variables properly.
Although I do not get what you are saying completely, still based on your description the problem can be you sending the variable using ajax call. If the ajax call is async you might not get the value by the time you use it.
So you can either set async:false in the ajax call (which is not a good way) or trigger any thing that uses that variable from within the success callback handler of the ajax call.
It would be really helpful if you can share the piece of code which explains the following statement of yours.... "i Take the input parameter from file called: index.php and pass the parameter using AJAX Jquery. The parameter itself is sent and pointing to file called insert.php"

AngularJS can't save to Database

i've only recently started with Angular and I still have some difficulties...
I can't seem to update my database with my angular data, however i can get data from my database.
This is my code where I want to try and Post my data.
$scope.submit = function(infographic){
var data = {
id: infographic.PK_InfoID,
label: infographic.label,
value: infographic.value
};
console.log(data);
$http.put("dataout.php", data).success(function(data) {
console.log(data);
});
};
And here is the PHP i use:
if(isset($_POST['id'])){
$id = $_POST['id'];
$label = $_POST['label'];
$value = $_POST['value'];
$query = "UPDATE tblInfo SET label = '".$label"', value = '".$value"' WHERE PK_InfoID = '$id'";
mysql_query($query);
}
Can someone help me please?
Thx
Angular will send the request data as a json-encoded string. PHP will not be able to parse that string, thus $_POST is empty.
Use something like:
<?php
$data = json_decode(file_get_contents('php://input'), true);
if (json_last_error() === JSON_ERROR_NONE) {
// use $data instead of $_POST
print_r($data);
}
on the receiving side.
Debug your PHP file:
file_put_contents('/tmp/postContents.txt', print_r($_POST, true));
That will tell you if your PHP script receives the data you expect.
Also: Make sure you're not creating SQL injection security issues. You should escape the values ($label, etc.). Google "sql injection php" for info.

prototype ajax not properly executing query

So I decided to start using prototype and here's my first question. I'm trying to send out an ajax request to a php page which updates s single record. When I do this by hand (ie: typing the address + parameters it works fine but when I use this code from javascript:
var pars = 'trackname=' + track + '&tracktime=' + time;
new Ajax.Request('php/setSongTime.php', {
method: 'get',
parameters: pars,
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
The onSuccess fires and displays the correct information from php, but the update is not made. What the php returns is the UPDATE string, so I'm checking the parameters and they look fine. Does anyone see a problem? Thanks...
Total javascript:
/*This file handles all the user-based computations*/
//variable declarations to be used throughout the session
var untimedSongArray = [];
function beginProcess(){
new Ajax.Request('php/getUntimed.php', {
method: 'get',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
untimedSongArray = response.split("+");
alert(response);
getFlashMovie("trackTimer").timeThisTrack(untimedSongArray[0]);
//alert("Success! \n\n" + response);
//var html = response;
},
onFailure: function(){ alert('Something went wrong...') }
});
}
function getFlashMovie(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName]; }
function setSongTime(track, time){
alert("track " + track + " has a time of " + time);
//$.get("php/setSongTime.php", { trackname: track, tracktime: time } );
var pars = 'trackname=' + track + '&tracktime=' + time;
new Ajax.Request('php/setSongTime.php', {
method: 'get',
parameters: pars,
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
});
}
Total php code:
<?php
//turn on error reporting
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
//header('Content-Type: text/xml');
/////////////Main script
//pull variables
//need to do some error checking here
$trackname = ($_GET['trackname']);
$tracktime = ($_GET['tracktime']);
//remove leading track information
$trackname = str_replace('../music_directory/moe/moe2009-07-18/', '', $trackname);
$trackname = str_replace('.mp3', '', $trackname);
//echo $trackname;
//connect with database
$con = mysql_connect("localhost","root","");
if(!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("musicneverstopped", $con);
//end connecting to database
//////////////////////////////////////////
//update given song time
$sql = "UPDATE songs SET length = ".$tracktime." WHERE unique_song_id = ".$trackname;
echo $sql;
mysql_query("UPDATE songs SET length = '$tracktime' WHERE unique_song_id = '$trackname'");
//error check
//if(!$attempt){
//die(mysql_error());
//}
//////////////////////////////////////////
//close database connection
mysql_close($con);//close mysql connection
?>
Anyone see any failing errors?
Try echoing the exact same SQL you actually run in mysql_query (store it in $sql then pass that into the query, instead of writing out the query twice).
Then try running the query that gets echoed out in the response directly in the mysql command line on your server and see what happens.
Also, just to echo Max on the importance of escaping your SQL queries, I would add to the input sanitisation that you should use bind variables in your query, rather than just concatenating your user input with the rest of the SQL.
Something like this would ensure your variables are suitably escaped to avoid an SQL injection attack.
$sql = "UPDATE songs SET length = '%s' WHERE unique_song_id = '%s'";
$query = sprintf(
$sql,
mysql_real_escape_string($tracktime),
mysql_real_escape_string($trackname)
);
mysql_query($query);
Found it! Somehow I was getting an extra space before the finalized $trackname. ltrim fixed it right up. Thanks to everyone and thanks to those that mentioned security features. I'll definitely implement those. Dan

Categories