Edgar Ong Edgar Ong - 1 year ago 100
PHP Question

Php - Codeigniter url spaces

I'm trying to do is when i clicked my specific product, instead of the id of my product would appear in my url, i want to put the name of the product .
what i did today is base_url/controller/method/id

i want to do is base_url/controller/method/product-name or base_url/controller/method/product_name

but in my code what happened is in my product name all the spaces is occupied by %20 what should i do to replace the %20 by either underscore or dash or whatever safe way to call the product name in url.

and whatever i get on that $name(product_name) i will pass it to my model.


public function details($name){

$prod_row = $this->PromoModel->getpromorow($name);
$data['promodetail'] = $prod_row;

$data['promo'] = $this->PromoModel->get_promo();

$data['message']= "<h1> NO PROMOS AVAILABLE</h1>";
$this->load->view('promo/PromoDetail', $data);


public function getpromorow($name) {
$this->db->where('name', $name);
$query = $this->db->get('promo');
return $query->row();

public function get_promo(){
$query = $this->db->get('promo');
return $query->result();


<a href="<?= base_url(). 'promos/details/' . $promo_row->name ?>"> </a>

Answer Source

This should work,

  <a href="<?= base_url(). 'promos/details/' . str_replace(' ', '_', $promo_row->name); ?>"> </a>

As far as - vs _ if you are routing to them, for example say that product name becomes a method in your controller, I don't think PHP allows - in method names, but it doesn't allow spaces either.. You can cheat using __call() but that's a other story for a different day.

If its a parameter, then it shouldn't matter as much. Just if it is a method/function name.

-Note- this is not a CI specific error, look at any url, tell me if you see spaces in them.

UPdate: as a suggestion the best way to handle this is by having a field dedicated to the url name ( such as slug or such ) and when a new product is made just do the transform on the name. Then it's an editable piece of data you have control over. For example what if you have a product with a - in it's name. This will probably cause issues. You can avoid that by having a separate piece of data just for that, it could even be like a SKU number etc. It's more work to setup, but in the long run more maintainable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download