Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
    
Nice username. :) Are you saying the queries are in JavaScript? You might need to show an example jut so we all can see. Hope this helps. –  jmort253 May 18 at 16:05
    
@jmort253 thx :) I added an example of my js in the post. Is that what you meant? –  http203 May 18 at 16:16
1  
The server is writing an ID to the client, and then the client turns around and makes another request to the server to get more data. Could you simplify things by just making a getJSON request with the original ID, or is that not available to you at the time? As for putting JavaScript in it's own scope, are you referring to the Constructor or Module patterns? You can encapsulate some functions but still make your public ones public. –  jmort253 May 18 at 16:33
1  
@jmort253 Thank you for your suggestions. I've cleaned up the code to make a single request, it makes more sense now. As for putting the JS in its own scope, I've put the entirely of my file inside (function() { ... })(); –  http203 May 18 at 22:38
    
Oh okay, @http203, that would be the module pattern, and you can expose any function you need access to via window.Class = Class or window.myMethod = myMethod. Not sure if this helps or not. Good luck! –  jmort253 May 18 at 23:20

1 Answer 1

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).

share|improve this answer
    
Thanks for the info! Just to clarify, when I get the params via js, it calls decodeURIComponent before returning it. When I output the keyword to the search box, I call escapeHtml on it (from your 2nd link). Then I call encodeURI on the originally retrieved param to pass it to my getJSON call. Then, on the server, I retrieve it again and call htmlspecialchars and use prepared statements via PDO before sending it to the DB. Is this the right approach? Is it overkill and did I miss anything important? –  http203 May 18 at 22:46
1  
@http203 You won't need to call htmlspecialchars if you are using prepared statements properly. htmlspecialchars is used when you're generating html for the browser. Otherwise your steps are ok. –  vikki May 19 at 7:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.