Php – the proper way to extract and pass parameters to call javascript functionality from the PHP page

coding-standardsjqueryPHPSecurity

This is my situation: I have a search results page in PHP where most of the logic resides in a javascript file in order to avoid refreshing the page every time an action is performed. The first thing I do using PHP is filter out and save valid query string values to PHP variables and I make use of the htmlspecialchars function to prevent injection. Now, I'd like to call my javascript function using those variables, so I created a script tag at the bottom of the page in order to pass the PHP variables to it (see my example).

When I put all of my javascript code inside of its own scope (as I read this was a good security practice), I realized that I could no longer call my function from outside of it. I also realize that the javascript method can still be called with anything a hacker wants, so does that mean I can't really make use of htmlspecialchars in my situation?

Here's a stripped-down version of my code:

<?php
try {       
  if (isset($_GET["id"])) {
    if (!is_numeric($_GET["id"]))
      throw new Exception("URL is not in a correct format");
    $id= $_GET["id"];
  }
  elseif (isset($_GET["keyword"])) {
    $keyword = htmlspecialchars($_GET["keyword"]);
  }
}
catch (Exception $e) {
  // handle error
}
?>
<html>
<head></head>
<body>
  <div class="searchResults"><!-- placeholder --></div>
  <?php
  if (isset($id)) { 
    echo '<script type="text/javascript">ShowSearchResults("id",'.$id.');</script>';        
  }
  elseif (isset($keyword)) { 
    echo '<script type="text/javascript">ShowSearchResults("keyword","'.$keyword.'");</script>'; 
  }
  ?>
</body>
</html>

This is basically the js:

function ShowSearchResults(key,value)
{
    $.getJSON("includes/search_results.php?"+key+"="+value, 
    function(data) {
      // populate search results
      $(".searchResults").html( "search results" );
    })
    .error(function() { 
       $(".searchResults").html( "no results" );
    });
}

My questions are (while keeping security and best practices in mind):

Is it bad practice to pass the query string values to my javascript function from within the body? I initially did this because I had the impression that it was not a good idea to extract query string values using javascript. Maybe I'm wrong there.

Should I be extracting the query string values from the $(document).ready function, and then calling the appropriate javascript functions from there? What is the appropriate way to do that (htmlspecialchars equivalent)?

Keep in mind that within my javascript code, I use $.getJSON to call another server side function (in PHP) that can reject anything insecure.

Any insight would be greatly appreciated.

Best Answer

Just copy one of the functions from this Stack Overflow post on retrieving values from a query string, and reuse it in your JavaScript code, such as this function:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

There's nothing wrong with pulling parameters from the query string in your JavaScript code as long as you are not executing anything you get from the query string. The JavaScript equivalent of htmlspecialchars is here.

However, if the $id was not coming from the query string, lets say it was coming directly from your server, it would be fine to echo it into your HTML and access it from JavaScript. (Try pressing ctrl-u now and see this page's HTML).

Related Topic