Trevor
Trevor

Reputation: 2457

htmlspecialchars + htmlentities not working

I'm setting up pagination on a search page and trying to the search query to each number.

 href="?s=search+term"

The problem is when a user enters special characters such as #, it will comment out anything behind it.

Normally I use htmlentities to turn it into %23 however it is not working in this situation. Keep in mind that the first time it searchs it looks like this in the search query

 href="?s=%23+search+term"

and upon clicking a page number the search query then looks like this

 href="?s=#%20search%20term"

Which, when executed by php, is commented out. Any ideas on how to bypass this?

Upvotes: 0

Views: 117

Answers (1)

Sam Dufel
Sam Dufel

Reputation: 17598

You'll need to use urlencode() on the search term to properly encode it for use in a url.

http://php.net/manual/en/function.urlencode.php

As a better option, you can generate the entire querystring from an array using http_build_query():

$params = [
    's' => "my search term",
    'p' => "3"
];
echo http_build_query($params);  // will echo a properly encoded querystring

Upvotes: 3

Related Questions