How to secure my jQuery AJAX calls in PHP and Java

2020-07-27 16:01发布

问题:

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?

回答1:

You are using POST that is good.

  1. More you can use "Session" for security.
  2. For code security you can put your functions and other important code in some different php files and include them in main file. To keep your code visible from directly.


回答2:

there are lots of tricks that hackers use so you just have to make it hard/time consuming enough that the reward is not worth the investment.

First you should never echo back something that came in a post. Hackers are known to perform all sorts of injections with a hole like that.

To avoid that simply unescape the value first.

For MySQL use:mysqli_real_escape_string.

When echoing back HTML (echo or print) use: htmlspecialchars.

For executing code with exec use escapeshellcmd and escapeshellarg.

Example:

<?php
    define('CHARSET', 'ISO-8859-1');
    define('REPLACE_FLAGS', ENT_COMPAT | ENT_XHTML);

    function html($string) {
        return htmlspecialchars($string, REPLACE_FLAGS, CHARSET);
    }
    $myvar = $_POST['q']." how are you?";
    $myvar2 = $_POST['z'];
    echo html($myvar."\n".$myvar2);

?>