CakePHP sessions

Posted: February 9th, 2010 | Author: | Filed under: Javascript, PHP | No Comments »

If you are developing an CakePHP application where ajax is mostly used. It is advisable that you set the following session configurations inside your core.php.

Configure::write('Session.timeout', '86400'); // expires in 30 days

Configure::write('Security.level', 'medium');

If your application calls more than one ajax request at the same time, it is recommended that you set your ajax requests to synchronous to prevent session regeneration id errors.


Using Zend Framework’s Paginator Library

Posted: June 23rd, 2009 | Author: | Filed under: PHP | Tags: , , | No Comments »

Here’s a tutorial on how to use ZF’s paginator library.

Inside your controller:

    public function displayResultsAction() {
        // First condition gets filtered info from a form and passes it to the model
        if($this->_request->getPost('Submit')) {
            $dept_code= $this->_request->getPost('dept_code');

            $results = $this->report_model->getReports($dept_code);
      	} elseif($this->_request->getParam('dept_code')) {
        // Get the filtered info from the url params being passed by zend paginator
       	    $dept_code= $this->_request->getParam('dept_code');

       	    $results = $this->report_model->getReports($dept_code);
       	} else {
            // do anything here...
            // I just display the default report results
            $dept_code = '';

       	    $results = $this->report_model->getDefaultReports();
        }

        $page = $this->_request->getParam('page', 1);

        $paginator = Zend_Paginator::factory($results);
        //Set item count per page
        $paginator->setItemCountPerPage(20);

        $paginator->setCurrentPageNumber($page);

        $this->view->results = $paginator;
        $this->view->dept_code = $dept_code;
    }

Inside your results view page:

<!-- html code here -->

<table class="view" cellpadding="3" cellspacing="0">
    <thead>
        <tr>
            <th width="100">Id #</th>
            <th width="150">Dept Code</th>
            <th width="200">Department</th>
            <th width="200">Project Name</th>
        </tr>
    </thead>
    <tbody>
    <?php   foreach($this->results as $row) { ?>
        <tr class="view-details">
            <td><?=$row->Id?></td>
            <td><?=$row->DeptCode?></td>
            <td><?=$row->DeptName?></td>
            <td><?=$row->ProjName?></td>
        </tr>
    <?php   }    ?>
    </tbody>
</table>
<br>
<!-- specify path of pagination control under your views in the 3rd param -->
<!-- Adding extra params in the url is specified on the 4th function param here -->
<?=$this->paginationControl($this->results, 'Sliding', 'reports/results-pagination.phtml', array('dept_code' => $this->dept_code))?>

<!-- html code here -->

Inside your pagination file view:

<?php if ($this->pageCount): ?>
<div id="paginationControl">
<!-- Previous page link -->
<?php if (isset($this->previous)): ?>
<?php   if($this->dept_code == '') { ?>
    <a href="<?= $this->url(array('page' => $this->previous)); ?>">&lt; Previous</a> |
<?php   } else { ?>
   <a href="<?= $this->url(array('page' => $this->previous, 'dept_code' => $this->dept_code)); ?>">&lt; Previous</a> |
<?php   } ?>
<?php else: ?>
  <span class="disabled">&lt; Previous</span> |
<?php endif; ?> 

<!-- Numbered page links -->
<?php foreach ($this->pagesInRange as $page): ?>
    <?php if ($page != $this->current): ?>
    <a href="<?=$this->baseUrl()?>/reports/display-results?page=<?=$page?><?=($this->dept_code!= '') ? '&dept_code=' . $this->dept_code: ''?>"><?= $page; ?></a> |
    <?php else: ?>
    <?= $page; ?> |
   <?php endif; ?>
<?php endforeach; ?>

<!-- Next page link -->
<?php if (isset($this->next)): ?>
  <a href="<?=$this->baseUrl()?>/reports/display-results?page=<?=$this->next?><?=($this->dept_code != '') ? '&dept_code=' . $this->dept_code: ''?>">Next &gt;</a>
<?php else: ?>
    <span class="disabled">Next &gt;</span>
<?php endif; ?>
</div>
<?php endif; ?>

Translate timestamp into words using PHP

Posted: May 28th, 2009 | Author: | Filed under: PHP | Tags: , | No Comments »

Here’s a nifty class I use for getting the date difference and translating them into words.

 class Date  {

    	public static function date_diff($dateTimeBegin,$dateTimeEnd) {

    		$dateTimeBegin = @strtotime($dateTimeBegin);

    		if($dateTimeBegin === -1) throw new InvalidDate("$dateTimeBegin: invalid date");

    		$dateTimeEnd=@strtotime($dateTimeEnd);

    		if($dateTimeEnd === -1) throw new InvalidDate("$dateTimeEnd: invalid date");

    		$dif=$dateTimeEnd - $dateTimeBegin;

    		if ($dif == 0) return "< 1 second";

    		if ($dif == 1) return "1 second";

    		$return_val = null;
    		$weeks      = floor($dif / 604800);

    		if ($weeks > 0) {
    			$dif -= $weeks * 604800;
    			$return_val .= "$weeks week".(($weeks>1)?'s':'');
    		}

    		$days = floor($dif / 86400);

    		if ($days > 0) {
    			$dif -= $days * 86400;
    			$return_val .= !is_null($return_val)?' and ':'';
    			$return_val .= "$days day".(($days>1)?'s':'');
    		}

    		$hours = floor($dif/3600);

    		if ($hours > 0) {
    			$dif -= $hours * 3600;
    			$return_val .= !is_null($return_val)?' and ':'';
    			$return_val .= "$hours hour".(($hours>1)?'s':'');
    		}

    		$minutes = floor($dif/60);

    		if ($minutes > 0) {
    			$dif -= $minutes * 60;
    			$return_val .= !is_null($return_val)?' and ':'';
    			$return_val .= "$minutes minute".(($minutes>1)?'s':'');
    		}

    		$seconds = $dif;

    		if ($seconds > 0) {
    			$return_val .= !is_null($return_val)?' and ':'';
    			$return_val .= "$seconds second".(($seconds>1)?'s':'');
    		}

    		return $return_val;
    	}

    	public static function format_date($date) {
    	    $return_val = null;
    		$weeks      = floor($date / 604800);

    		if ($weeks > 0) {
    			$dif -= $weeks * 604800;
    			$return_val .= "$weeks week".(($weeks>1)?'s':'');
    		}

    		$days = floor($date / 86400);

    		if ($days > 0) {
    			$date -= $days * 86400;
    			$return_val .= !is_null($return_val)?' and ':'';
    			$return_val .= "$days day".(($days>1)?'s':'');
    		}

    		$hours = floor($date/3600);

    		if ($hours > 0) {
    			$date -= $hours * 3600;
    			$return_val .= !is_null($return_val)?' and ':'';
    			$return_val .= "$hours hour".(($hours>1)?'s':'');
    		}

    		$minutes = floor($date/60);

    		if ($minutes > 0) {
    			$date -= $minutes * 60;
    			$return_val .= !is_null($return_val)?' and ':'';
    			$return_val .= "$minutes minute".(($minutes>1)?'s':'');
    		}

    		$seconds = $date;

    		if ($seconds > 0) {
    			$return_val .= !is_null($return_val)?' and ':'';
    			$return_val .= "$seconds second".(($seconds>1)?'s':'');
    		}

    		return $return_val;
    	}
    }

Connect to a Unix system using PHP SSH2

Posted: May 22nd, 2009 | Author: | Filed under: PHP | 1 Comment »

In order to use this class, SSH2 lib must be installed in your PHP configuration. Go here for detailed instructions on how to install and compile SSH2 lib in your web server.

class Ssh {

        private $host = '';
        private $user = '';
        private $port = '22';
        private $password = '';
        private $con = null;
        private $shell_type = 'xterm';
        private $shell = null;
        private $log = '';

        public function __construct($params) {
            if($params['host'] != '') $this->host  = $params['host'];
            if($params['port'] != '') $this->port  = $params['port'];
        }

        public function connectShell() {
            $this->con = @ssh2_connect($this->host, $this->port);

            if(!$this->con) {
                $this->log .= "Connection failed!\n";

                return FALSE;
            } else {
                return TRUE;
            }
        }

        public function authPassword($user = '', $password = '' ) {
            if($user != '') $this->user = $user;

            if($password != '') $this->password = $password;

            if(!@ssh2_auth_password($this->con, $this->user, $this->password) ) {
                $this->log .= "Authorization failed!\n";

                return FALSE;
            } else {
                return TRUE;
            }
        }

        public function execShell($command) {
            if(!($stream = @ssh2_exec($this->con, $command)) ){
                $this->log .= "Fail: Unable to execute command!\n";

                return FALSE;
            } else {
                // collect returning data from command
                stream_set_blocking($stream, true );
                $this->log .= stream_get_contents($stream);
                fclose($stream);                

                return TRUE;
            }
        }

        public function sendFile($local_file, $remote_file, $mode = '0644') {
            if(!ssh2_scp_send($this->con, $local_file, $remote_file)) {
                $this->log .= "Cannot send file to server.\n";

                return FALSE;
            } else {
                return TRUE;
            }
        }

        public function getLog() {
            return $this->log;
        }

    }