In this post we are going to be talking about removing parameters from a url and not exposing too much data on the browser's address bar. Consider this url:
This url exposes three parameters which is the controller action, the user id, and a product id (supposing this is an online shopping web app). We will be converting the url to be like:
Now that's more like it. A clean url that only you know what the values are for. This is a small but neccesary step to securing your web apps. We don't want to be telling people what those numbers mean. The trick here is to use Zend Routes
. You create routes in Zend inside you Bootstrap.php
file. Taking the url above we can set a route like so:
<?php class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { /** * Place your custom Routers here */ public function _initCustomRoute() { $front = Zend_Controller_Front::getInstance(); $router = $front->getRouter(); //Get the router $route = new Zend_Controller_Router_Route('product/:user_id/:product_id', array( 'module' => 'default', 'controller' => 'product', 'action' => 'index' )); $router->addRoute('product-index-route', $route); } } ?>
We add custom routes inside _initCustomRoute()
function by getting an instance of the from controller and getting the router from it. We use a Zend_Controller_Router_Route()
object that tell our framework that our framework that based on a url it should route to a specific module, controller and action. Every route must have a unique name when your adding it to the router. Our route above is for a url has a user_id
and a product_id
. Bare in mind that we didn't forget to use the controller name product
. Omitting the controller name will give you an exception. Now lets look at our controller on how we catch these variables:
<?php class ProductController extends Zend_Controller_Action { public function init() { /* Initialize action controller here */ } public function indexAction() { $userid = $this->_request->getParam('user_id'); $productid = $this->_request->getParam('product_id'); .... } } ?>
As you can see nothing has changed on how you get variables inside your controller.
....and That's It!
That's it folks! You now know how to hdie your url parameters on the address bar and it didn't hurt now did it... Happy coding!
Comments