Archive for December, 2010

CodeIgniter URL Rewrite with .htacccess AND populated $_GET variables

Posted in CodeIgniter, How To, PHP, Web Development on December 7th, 2010 by j3nnings – Be the first to comment

Everytime I start a new CodeIgniter project on Dreamhost I face the same two problems.

  1. How can I get URL rewriting to work properly?
  2. How can I repopulate $_GET variables once they are stripped by CodeIgniter?

The problem with this pair of tasks is that task 2 is dependent on how you solve task 1. I’ve solved both problems (on dreamhost) with the following fixes:

Make sure your config.php has these values set:

$config['base_url'] = "http://domain.com/";
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
$config['enable_query_strings'] = TRUE;

Your .htaccess looks like this:

RewriteEngine on
RewriteCond $1 !^(index\.php|public|favicon\.ico|static|robots\.txt)
RewriteRule ^(.*)$ /index.php?/$1 [L]

And add this to the top of any Controller you wish to use $_GET variables in.

function __construct() {
parse_str(substr(strrchr($_SERVER['REQUEST_URI'], "?"), 1), $_GET);
parent::Controller();
}

Now you’ll be able to access the $_GET variables as you would expect:

echo $this->input->get('foo');