Retaining a search string in the URL
June 24, 2008 CakePHP

As you know, for a good reason, CakePHP will use the POST method by default to submit form data. However, there is a case where this could present a problem…

Let’s say you are building a little search tool for all of your articles. It would be nice to allow people to bookmark or copy/paste the search URL, which would look like this:

http://mysite.com/articles/search/Hippopotamus

If you have a form that does the POST of the search term “Hippopotamus” that’s not going to work just like that.

Instead, create a form that will POST to searchRedirect() action, which would look something like:

function searchRedirect() {        
  if(!empty($this->data)) {            
    $this->redirect(array('controller'=>'articles', 'action'=>'search', $this->data['Article']['searchField']));      
  }    
}

Now you can build your search() action to read the value from the URL (which was passed via the redirect) and do whatever it has to display the results… and of course you now have the search term visible in the URL.

The example above is simplistic and you probably want to make sure to use urlencode() urldecode() or some other method to ensure that you read safe data from the URL param. Better yet, you might want to store the search term in the session (and read it from there), so that if someone tampers with the URL, it won’t cause any problems in your app.

P.S. FYI, this can hardly be called a hack as it is actually a common enough practice in web development http://en.wikipedia.org/wiki/Post/Redirect/Get

Comments
  • Phally

    Why use a separate action?

    function search($keyword = null) {
      if (!empty($this->data)) {
        $this->redirect(array($this->data['Article']['searchField']));
      }
      // The rest of the search action.
    }
  • @Phally

    No reason really, other than ideally a given function should preform only one task that it is suited for. Otherwise your functions grow big and code can get messy really quick. Of course, this particular case is not the best example.

*