How to get the a date before current date in PHP

Filed Under (General) by Wenbert on 31-01-2008

Tagged Under :

Given 2008-01-31 as the current date and the value of “$days_before” is 2, the code will echo 2008-01-29. The date 2 days before the current date.

  1.  
  2. $days_before = 2;
  3. $current_date = date(‘Y-m-d’);
  4. $str = strtotime($current_date)-(86400*$days_before); //1 day has 86400
  5. echo date(‘Y-m-d’,$str);
  6.  

Get Difference Between 2 Dates Using PHP

Filed Under (General) by Wenbert on 29-01-2008

Tagged Under :

Here is how you get the number of days between two dates.

  1.  
  2.  
  3. function getdays($day1,$day2)
  4. {    
  5.      return round((strtotime($day2)-strtotime($day1))/(24*60*60),0);
  6. }
  7. $begin = date("Y-m-d"); // we set today as an example
  8. $end = "2007-01-29";
  9.  
  10. echo getdays($begin,$end).‘ days’;

This was taken from the manual - posted by: michiel at mb-it dot nl

A Very Quick Zend Framework VS. Code Igniter Comparison

Filed Under (General) by Wenbert on 25-01-2008

Tagged Under : ,

Before anything else, I want the readers to know that I have used Zend Framework for a few months prior to using Code Igniter. I hang out in #zftalk (freenode) when I have time. So I am more of a ZF guy than a CI person. But after working with Code Igniter for a couple of weeks, I realized how much a love ZF over it (CI). Working and coding in ZF is more enjoyable than working in CI - I don’t know if it just me, but I don’t feel comfortable coding in Code Igniter.. I have had instances in CI where I think I could have done a better job if I wrote it in ZF - espcially with the ZF Components.

Code Igniter has some pretty nice features though. For instance, you can deploy an MVC project in less than a minute. You just have to configure the files an then viola! You are now up and running. While with ZF, you would have to make your own bootstrap file and you would have to choose which directory structure you will use. I think this is why a lot of people use CI. The learning curve is very easy and deployment is fast. But the joy ends there - well at least for me since I love exploring the unknown.

I have complete confidence that Zend Framework will be able to handle any project - from web sites to custom web applications — just about anything. It might take longer to configure and deploy, but in the end it is all worth it. I also find it very comforting that the Zend Framework Components are made by people who “really” know PHP. I have had bad experiences using “hacks”, poorly-tested user-contributed plug-ins by using other open-source ready-made CMSes.

In the end, both frameworks have their strengths and weakness. Code Igniter is fast to deploy and easy to configure. For Zend Framework, no matter what other people say about it– I love it :P FTW!

Zend Framework Zend_Auth and a Plugin to Check Access to a Page

Filed Under (General) by Wenbert on 02-01-2008

Tagged Under : ,

I have written this simple user authentication and user access privilege plugin in one of my Web Apps.

First, in my AuthController, I have something like this:

  1.  
  2.     public function loginAction()
  3.     {
  4.         try {
  5.             if ($this->_request->isPost()) {
  6.                 // collect the data from the user
  7.                 $f = new Zend_Filter_StripTags();
  8.                 $username = $f->filter($this->_request->getPost(‘username’));
  9.                 $password = $f->filter($this->_request->getPost(‘password’));
  10.                 $password = md5($password);
  11.              
  12.                 if (empty($username)) {
  13.                     $this->_flashMessenger->addMessage(‘Provide a username.’);
  14.                     $this->_redirect(‘auth/’);
  15.                 } else {
  16.                     // setup Zend_Auth adapter for a database table
  17.                     $dbAdapter = Zend_Registry::get(‘dbAdapter’);
  18.                     $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
  19.                     $authAdapter->setTableName(‘users’);
  20.                     $authAdapter->setIdentityColumn(‘username’);
  21.                     $authAdapter->setCredentialColumn(‘password’);
  22.                      
  23.                     // Set the input credential values to authenticate against
  24.                     $authAdapter->setIdentity($username);
  25.                     $authAdapter->setCredential($password);
  26.                      
  27.                     // do the authentication  
  28.                     $auth = Zend_Auth::getInstance();
  29.                     $result = $auth->authenticate($authAdapter);
  30.                     if ($result->isValid()) {
  31.                         // success: store database row to auth’s storage
  32.                         // system. (Not the password though!)
  33.                         $data = $authAdapter->getResultRowObject(null, ‘password’);
  34.    
  35.                         $auth->getStorage()->write($data);
  36.                        
  37.                         $user = Zend_Auth::getInstance()->getIdentity();
  38.                        
  39.                         $dbAdapter = Zend_Registry::get(‘dbAdapter’);
  40.                        
  41.                         $sql = ‘SELECT
  42.                            ug.*,
  43.                            g.*
  44.                            FROM user_group ug
  45.                            LEFT JOIN groups g ON ug.group_id = g.id
  46.                            WHERE ug.user_id="’.$user->id.‘"’;
  47.                         $groups = $dbAdapter->fetchAll($sql);
  48.                                            
  49.                         $mygroups = array();
  50.                         foreach ($groups AS $group) {
  51.                            
  52.                             //query permissions table
  53.                             $sql =
  54.                                SELECT *
  55.                                FROM permissions
  56.                                WHERE group_id="’.$group[‘group_id’].‘"
  57.                            ’;
  58.                             $group_permission = $dbAdapter->fetchAll($sql);
  59.                            
  60.                             $mygroups[][‘group_name’] = $group[‘group_name’];
  61.                             $mygroups[‘group_permission’] = $group_permission;
  62.                         }
  63.                                            
  64.                         //get the Zend_Auth and then save the roles
  65.                         $authNamespace = new Zend_Session_Namespace(‘Zend_Auth’);
  66.                         $authNamespace->storage->mygroups = $mygroups;
  67.  
  68.                         $this->_flashMessenger->addMessage(‘Login Successful.’);
  69.                         $this->_redirect(‘/’);
  70.                     } else {
  71.                         $this->_flashMessenger->addMessage(‘Login Failed. Please enter a valid username/password.’);
  72.                         $this->_redirect(‘/auth/’);
  73.                     }
  74.                 }
  75.             }
  76.         } catch (Exception $e){
  77.             echo $e->getMessage();
  78.         }
  79.         $this->view->messages = $this->_flashMessenger->getMessages();
  80.         $this->_helper->viewRenderer->setNoRender(); //suppress auto-rendering
  81.  

I know I should have done the queries in my User Model instead of inserting them in-line with the loginAction. Anyways, I did that do give you an idea of what I am querying.

Now, for the plugin. In my library folder, beside the Zend folder - which contains all the Zend Framework core files, I have a directory called Ekini.

../library/Ekini/Controller/Plugin/

Inside the Plugin directory, I have this file called: CheckHasAccess.php

The file contains the following code:

  1.  
  2. < ?php
  3. class Ekini_Controller_Plugin_CheckHasAccess extends Zend_Controller_Plugin_Abstract {
  4.  
  5.     /**
  6.      * Checks if a user is allowed to access the current controller
  7.      * Returns true if allowed
  8.      * redirects to the noaccess.phtml found in auth controller if user is not allowed
  9.      *
  10.      * @param Zend_Controller_Request_Abstract $request
  11.      * @return unknown
  12.      */
  13.     public function preDispatch(Zend_Controller_Request_Abstract $request)
  14.     {  
  15.         try {
  16.            
  17.             $moduleName         = $this->getRequest()->getModuleName();
  18.             $controllerName     = $this->getRequest()->getControllerName();
  19.             $actionName         = $this->getRequest()->getActionName();
  20.             $frontController    = Zend_Controller_Front::getInstance();
  21.             $user = Zend_Auth::getInstance()->getIdentity();
  22.            
  23.            
  24.             if($controllerName == ‘admin’ AND !isset($user)) {
  25.                 throw new Exception(‘You must login to access this page.’);
  26.             }
  27.            
  28.             //check $user->mygroups[’group_permission’] array
  29.             //echo $moduleName.’ ‘.$controllerName.’ ‘.$actionName;
  30.             //Zend_Debug::dump($user->mygroups[’group_permission’]);
  31.            
  32.             if (isset($user)) {
  33.                 $permissions = $user->mygroups[‘group_permission’];
  34.                
  35.                 //check for module ONLY - controller and action must be NULL
  36.                 for($i=0;$i<count ($permissions);$i++) {
  37.                     if ($permissions[$i][‘module_name’] == $moduleName AND
  38.                         $permissions[$i][‘controller_name’] == NULL AND
  39.                         $permissions[$i][‘action_name’] == NULL AND
  40.                         $permissions[$i][‘permission’] == ‘deny’) {
  41.                         throw new Exception(‘You are not allowed to access this module.’);    
  42.                         }
  43.                 }
  44.                
  45.                 //check for controller+module - action is blank
  46.                 for($i=0;$i<count($permissions);$i++) {
  47.                     if ($permissions[$i][‘module_name’] == $moduleName AND
  48.                         $permissions[$i][‘controller_name’] == $controllerName AND
  49.                         $permissions[$i][‘action_name’] == NULL AND
  50.                         $permissions[$i][‘permission’] == ‘deny’) {
  51.                         throw new Exception(‘You are not allowed to access this controller.’);    
  52.                         }
  53.                 }
  54.                
  55.                 //check for the module / controller / action - look for deny
  56.                 for($i=0;$i<count($permissions);$i++) {
  57.                     //echo $permissions[$i][’module_name’].’ ‘.$permissions[$i][’permission’].’<br>’;
  58.                     if ($permissions[$i][‘module_name’] == $moduleName AND
  59.                         $permissions[$i][‘controller_name’] == $controllerName AND
  60.                         $permissions[$i][‘action_name’] == $actionName AND
  61.                         $permissions[$i][‘permission’] == ‘deny’) {
  62.                        
  63.                         throw new Exception(‘You are not allowed to access this page.’);
  64.                     }
  65.                 }
  66.                
  67.                 //if guest session exists, unset it
  68.                 Zend_Session::sessionExists(‘Guest_Session’)?Zend_Session::namespaceUnset(‘Guest_Session’):;
  69.                
  70.             } elseif(Zend_Session::namespaceIsset(‘Guest_Session’)) {
  71.                 //this part executes only when the Guest_Session is set
  72.                 //so that we only have to query the database once
  73.                 //querying the database is in the else
  74.                 //after querying, the Guest_Session is set.
  75.                
  76.                 $guest = new Zend_Session_Namespace(‘Guest_Session’);
  77.                
  78.                 $permissions = $guest->guestRoles;
  79.                 //Zend_Debug::dump($guest);
  80.                 //echo ‘guest session exists!’;
  81.                 //check for module ONLY - controller and action must be NULL
  82.                 for($i=0;$i</count><count ($permissions);$i++) {
  83.                     if ($permissions[$i][‘module_name’] == $moduleName AND
  84.                         $permissions[$i][‘controller_name’] == NULL AND
  85.                         $permissions[$i][‘action_name’] == NULL AND
  86.                         $permissions[$i][‘permission’] == ‘deny’) {
  87.                         throw new Exception(‘You are not allowed to access this module.’);    
  88.                         }
  89.                 }
  90.                
  91.                 //check for controller+module - action is blank
  92.                 for($i=0;$i<count($permissions);$i++) {
  93.                     if ($permissions[$i][‘module_name’] == $moduleName AND
  94.                         $permissions[$i][‘controller_name’] == $controllerName AND
  95.                         $permissions[$i][‘action_name’] == NULL AND
  96.                         $permissions[$i][‘permission’] == ‘deny’) {
  97.                         throw new Exception(‘You are not allowed to access this controller.’);    
  98.                         }
  99.                 }
  100.                
  101.                 //check for the module / controller / action - look for deny
  102.                 for($i=0;$i<count($permissions);$i++) {
  103.                     //echo $permissions[$i][’module_name’].’ ‘.$permissions[$i][’permission’].’<br>’;
  104.                     if ($permissions[$i][‘module_name’] == $moduleName AND
  105.                         $permissions[$i][‘controller_name’] == $controllerName AND
  106.                         $permissions[$i][‘action_name’] == $actionName AND
  107.                         $permissions[$i][‘permission’] == ‘deny’) {
  108.                        
  109.                         throw new Exception(‘You are not allowed to access this page.’);
  110.                     }
  111.                 }  
  112.             } else {
  113.                 //query the database for permissions and then set Guest_Session
  114.                 $guestSession = new Zend_Session_Namespace(‘Guest_Session’);
  115.                
  116.                 //Not logged in, so check guest/unregistered user
  117.                 //query permissions table
  118.                 $dbAdapter = Zend_Registry::get(‘dbAdapter’);
  119.                 $sql =
  120.                    SELECT *
  121.                    FROM permissions
  122.                    WHERE group_name="guest"
  123.                ’;
  124.                 $permissions = $dbAdapter->fetchAll($sql);
  125.                
  126.                 //set this to session, so that we will not be querying the db for every guest that is logged in.
  127.                 $guestSession->guestRoles = $permissions;
  128.                
  129.                 //check for module ONLY - controller and action must be NULL
  130.                 for($i=0;$i</count><count ($permissions);$i++) {
  131.                     if ($permissions[$i][‘module_name’] == $moduleName AND
  132.                         $permissions[$i][‘controller_name’] == NULL AND
  133.                         $permissions[$i][‘action_name’] == NULL AND
  134.                         $permissions[$i][‘permission’] == ‘deny’) {
  135.                         throw new Exception(‘You are not allowed to access this module.’);    
  136.                         }
  137.                 }
  138.                
  139.                 //check for controller+module - action is blank
  140.                 for($i=0;$i<count($permissions);$i++) {
  141.                     if ($permissions[$i][‘module_name’] == $moduleName AND
  142.                         $permissions[$i][‘controller_name’] == $controllerName AND
  143.                         $permissions[$i][‘action_name’] == NULL AND
  144.                         $permissions[$i][‘permission’] == ‘deny’) {
  145.                         throw new Exception(‘You are not allowed to access this controller.’);    
  146.                         }
  147.                 }
  148.                
  149.                 //check for the module / controller / action - look for deny
  150.                 for($i=0;$i<count($permissions);$i++) {
  151.                     //echo $permissions[$i][’module_name’].’ ‘.$permissions[$i][’permission’].’<br>’;
  152.                     if ($permissions[$i][‘module_name’] == $moduleName AND
  153.                         $permissions[$i][‘controller_name’] == $controllerName AND
  154.                         $permissions[$i][‘action_name’] == $actionName AND
  155.                         $permissions[$i][‘permission’] == ‘deny’) {
  156.                        
  157.                         throw new Exception(‘You are not allowed to access this page.’);
  158.                     }
  159.                 }
  160.             }
  161.             return true;
  162.            
  163.         } catch (Exception $e) {
  164.             $this->getResponse()->setHttpResponseCode(403);
  165.             $request->setControllerName(‘error’);
  166.             $request->setActionName(‘noaccess’);
  167.         }
  168.     }
  169.    
  170. }
  171. </count>

I know, lots of repition :P But I will refactoring this part when I have time. But I hope you got the idea of the entire thing.

Well, if you didn’t lemme explain it a bit.

First of all, the loginAction - logs in the user. It get the user details including the groups where the user is under. I have stored these details in the Session.

The CheckHasAccess Plugin gets called everytime someone loads a page. Plugins behave like this. Here are table structures for your reference.


--
-- Table structure for table `permissions`
-- 

CREATE TABLE `permissions` (
  `id` int(11) NOT NULL auto_increment,
  `group_id` int(11) NOT NULL,
  `group_name` varchar(250) NOT NULL,
  `module_name` varchar(250) default 'default',
  `controller_name` varchar(250) default NULL,
  `action_name` varchar(250) default NULL,
  `permission` enum('allow','deny') NOT NULL default 'allow',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;

--
-- Dumping data for table `permissions`
-- 

INSERT INTO `permissions` VALUES (1, 1, 'admin', 'default', 'admin', NULL, 'allow');
INSERT INTO `permissions` VALUES (3, 3, 'registereduser', 'default', 'admin', NULL, 'deny');
INSERT INTO `permissions` VALUES (7, 1, 'admin', 'default', 'index', NULL, 'allow');
INSERT INTO `permissions` VALUES (4, 2, 'moderator', 'default', 'admin', 'createsitevar', 'deny');
INSERT INTO `permissions` VALUES (5, 2, 'moderator', 'default', 'admin', 'managesitevars', 'deny');
INSERT INTO `permissions` VALUES (6, 2, 'moderator', 'default', 'admin', 'deletesitevar', 'deny');

--
-- Table structure for table `groups`
-- 

CREATE TABLE `groups` (
  `id` int(11) NOT NULL auto_increment,
  `group_name` varchar(250) NOT NULL,
  `group_desc` varchar(250) NOT NULL,
  `group_parent` int(11) NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `group_name` (`group_name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `groups`
-- 

INSERT INTO `groups` VALUES (1, 'admin', 'Administrators', 0);
INSERT INTO `groups` VALUES (2, 'moderators', 'Moderators', 0);
INSERT INTO `groups` VALUES (3, 'registereduser', 'Registered User / Member', 0);
INSERT INTO `groups` VALUES (4, 'guest', 'Guest', 0);

--
-- Table structure for table `user_group`
-- 

CREATE TABLE `user_group` (
  `id` bigint(20) NOT NULL auto_increment,
  `user_id` int(11) NOT NULL,
  `group_id` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

--
-- Dumping data for table `user_group`
-- 

INSERT INTO `user_group` VALUES (1, 1, 1);
INSERT INTO `user_group` VALUES (2, 2, 2);
INSERT INTO `user_group` VALUES (3, 3, 3);
Subscribe to Rss Feed : Rss