I have following PHP and Javascript code snippet in which I am making an jQuery AJAX call to get data from PHP and show it in the HTML.
PHP code
<?php
myfunction();
function myfunction()
{
$myvar = $_POST['q']." how are you?";
$myvar2 = $_POST['z'];
echo $myvar."\n".$myvar2;
}
?>
HTML code
<div id="mydiv"></div>
Javascript code
var data =" hello world";
var data2=" hello all";
function run()
{
$.ajax(
{
url: 'myscript.php',
data: {'q': data,'z':data2},
type: 'post',
success: function(output)
{
//alert(output);
document.getElementById("mydiv").innerHTML += output; //add output to div
}
}
);
}
Above code is working fine.
I want to secure this AJAX call to prevent it from hackers because I am making an AJAX call which is visible to all. This code is vulnerable to hackers attack. My question is what and where should I impose extra checks to make my AJAX call secure?
One thing I know that I should use following code snippet in my PHP file
if (!$_POST['q'] && !$_POST['z'])
{
exit;
}|
else
{
myfunction(); //call myfunction only if page is posted
}
What extra checks should I use in PHP and Javascript files?