Skip to content

Search with query sent via GET parameters like wordpress

World Wide Web Server edited this page Jul 4, 2012 · 14 revisions

Category:Approaches

Advantages: you can bookmark your searches, and they show up in your history, etc. (I guess this is why wordpress uses it, or maybe its just convenient, whatever).

The problem: Codeigniter removes the contents of $_GET for security reasons (I guess).

In this example the text input box is named "s":

[code] <input type='text' name='s' value='$searchStr'> [/code]

After typing in the searchbox the words "duffy duck" and click the search button you will go to an url like this: http://www.myserver.com/my_controller/my_function/[color=green][b]?s=duffy+duck[/b][/color]

The browser does this automaticly if you set method="get" in the form. But codeigniter form_open() doesnt support this so you will have to write the form manually:

[code] echo '<form method="get" action="'. base_url() . 'my_controller/my_function/">' [/code]

Use $_SERVER['REQUEST_URI'] to get the full text of the url and explode() to extract what you need:

[code] $array = explode('?s=', $_SERVER['REQUEST_URI']); [/code]

Then urldecode it and addslashes for security (you can xss_clean it too)

[code] $searchStr = isset($array[1]) ? addslashes($this->input->xss_clean(urldecode(trim($arr[1])))) : ''; [/code]

You can figure out the rest yourself.

[code] function search() {

$this->load->helper('url');   //required for base_url()

$array = explode('?s=',  $_SERVER['REQUEST_URI']);
$searchStr = isset($array[1]) ? addslashes($this->input->xss_clean(urldecode(trim($arr[1])))) : '';

echo '&lt;form method="get" action="'. base_url() . 'my_controller/my_function/"&gt;'
."Search for phrase:<br />" 
."&lt;input type='text' name='s' value='$searchStr'&gt;"
. "<br />"
.'&lt;input type="submit" Search&gt;';


/*
rest of code goes here
... find data in database and display it
*/

} [/code]

Clone this wiki locally