Skip to content

Search with query sent via GET parameters like wordpress

mlazarov edited this page Jul 12, 2012 · 14 revisions

Category:Approaches Category:Search

Advantages: there are some advantages, depending on what you are trying to acomplish.

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

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

<input type='text' name='s' value='$searchStr'>

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/**?s=duffy+duck**

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:

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

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

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

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

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

You can figure out the rest yourself.

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 '<form method="get" action="'. base_url() . 'my_controller/my_function/">'
    ."Search for phrase:<br />" 
    ."<input type='text' name='s' value='$searchStr'>"
    . "<br />"
    .'<input type="submit" value="Search">';


    /*
    rest of code goes here
    ... find data in database and display it
    */
}
Clone this wiki locally