0

I have a search page (search.php) that calls an AJAX load and loads the results into the #myresults DIV:

$('#myresults').load('results.php', {"q":"<?php echo urlencode($this->params['url']['q']); ?>","min":<?php echo urlencode($this->params['url']['min']); ?>,max:<?php echo urlencode($this->params['url']['max']); ?>});

The querystring looks like:

http://www.mydomain.com/search?q=test&min=50&max=100

results.php looks like this:

if (isset($data['q']) && isset($data['min']) && isset($data['max'])) {
 $q = urldecode($data['q']);
 $min = urldecode($data['min']);
 $max = urldecode($data['max']);
}

I'm grabbing the querystring values, then posting them to the results page. Is URLEncode needed or should I use htmlspecialchars()? I've seen JSON.stringify() and I'm just not sure how to "best" encode my data (so that it can't be "broken" by those manipulating the querystring) and post it safely to the backend for use in my backend php code. I'm most concerned about apostrophes and quotes, how do i handle them?

2 Answers 2

1

The best thing to do is to remove any characters you know are not allowed which you can do with preg_replace. If you can't do that htmlspecialchars() or htmlentities() will work.

And of course escape the data before you search your database.

Sign up to request clarification or add additional context in comments.

Comments

0

According to the jQuery documentation the load() you will get the variables as POST:

The POST method is used if data is provided as an object; otherwise, GET is assumed.

So you should just treat it as a normal POST.

If you use the variables in a query for example you would use mysql_escape_string() to prevent MySQL injection.

3 Comments

But this isn't a normal POST, right? What if a users has quotes in the querystring?, then the JSON data string is broken: code"q":"<?php echo $this->params['url']['q']; ?>"
So your question actually is how to safely implement user generated strings into a JSON object? I think addslashes() would be enough.
I ended up using addslashes() and it seems to work as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.