Pages

Wednesday, May 16, 2012

(CakePHP)(cron job shell script) Send email automatically

This blog post describe how to set email alert to your cakephp website.
For send email automatically you have to write a shell script to your web site. In cakephp we write in the app\vendors\shells folder. I wrote my.php to send email.
In app\vendors\shells\ my.php i wrote
<?php

class MyShell extends Shell {

    var $uses = array('Client');

    function main() {
        App::import('Core', 'Controller');
        App::import('Component', 'Email');

        $this->Controller = & new Controller();
        $this->Email = & new EmailComponent(null);
        $this->Email->initialize($this->Controller);
        $this->Controller->ext = '.php';

        $start_date = date("Y-m-d");
        $end_date = date('Y-m-d', strtotime('+31 days'));
        $host_and_maintain_end_within_month = $this->Client->find('all', array('conditions' => array(array('Hosting_end_date between ? and ?' => array($start_date, $end_date)))));
        $this->Controller->set('clients', $host_and_maintain_end_within_month);

        $this->Email->to = 'tomail@gmail.com';  // $email[0]['User']['email'];
        $this->Email->subject = 'Expire Date Information '. $start_date;
        $this->Email->sendAs = 'html';
        $this->Email->template = 'alert';//template in app\views\elements\email\html\alert.ctp 
        $this->Email->smtpOptions = array(
            'port' => '465',
            'timeout' => '30',
            'host' => 'ssl://smtp.gmail.com',
            'username' => 'frommail@gmail.com',
            'password' => 'frompassword',
        );
        $this->Email->delivery = 'smtp';
        $this->Email->send();
    }

}
?> 

Tuesday, May 15, 2012

Cakephp security concepts

  • Protecting against Cross site scripting (XSS)
For sanitization against XSS it’s generally better to save raw HTML in database without modification and sanitize at the time of output/display.
We can use
$this->data = Sanitize::clean($this->data, array('encode' => false));
In either  beforeSave()  or afterFind() menthods. It is good to sanitize in the afterFind() method of the Model. This would be called after a search, which you are probably doing before displaying your data.

To sanitize in a view, you should use the CakePHP convenience function is a short cut for htmlspecialchars, which will render all attempts at XSS completely harmless.  This wouldn't physically remove the XSS code, but just present it in a way that cannot harm your application.
echo h('<script>alert("xss");</script>');
Would produce
&lt;script&gt;alert(&#039;xss&#039;);&lt;/script&gt; 
To protect from Cross Site Request Forgery You have to add the Security component to the $components array of your controller(s):
public $components = array('Security');
CakePHP will then automatically add a nonce to your form when you use the Form helper to create your forms.When using the Security Component you must use the FormHelper to create your forms. The Security Component looks for certain indicators that are created and managed by the FormHelper (especially those created in create() and end()). Dynamically altering the fields that are submitted in a POST request (e.g. disabling, deleting or creating new fields via JavaScript) is likely to trigger a black-holing of the request. See the $validatePost or $disabledFields configuration parameters.

  • Protecting against SQL injection
CakePHP already protects you against SQL Injection if you use CakePHP's ORM methods (such as   find()  and save()) and proper array notation  (ie.  array('field' => $value))  instead of raw SQL.
save(array $data = null, boolean $validate = true, array $fieldList = array());
Featured above, this method saves array-formatted data. The second parameter allows you to sidestep validation, and the third allows you to supply a list of model fields to be saved. For added security, you can limit the saved fields to those listed in $fieldList.

If $fieldList is not supplied, a malicious user can add additional fields to the form data (if you are not using Security component), and by this change fields that were not originally intended to be changed.

It is important to note, that updateAll() does not escape the fields, so be cautious when using it. Using the SecurityComponent you get automatic form spoofing protection. Data validation is a big integrated part of  models. The AuthComponent hashes and salts passwords properly.

Saturday, March 24, 2012

(CakePHP) Change validation rule for a field in controller.

In this blog post I'm going to explain how to add different validations for same field in different function in
controller.
For example 
in one view(greaterthanadd.ctp) i wanted to add number which is grater than 18.
and in other view(lesserthanadd.ctp) i wanted to add number which is less than 18.
This is doing for the same database table same column.
In CakePHP (1.3) we can call modle using
$this->Model_name;
So we can access the validation array in controller
$this->Model_name->validate['fieldName']['ruleName'];
In this example I am using table called numbers and field call number.
function greaterthanadd() { 
   if (!empty($this->data)) { 
//************
//validation strat
//************ 
     $this->Number->validate['number']['greaterthan'] = array(
          'rule' => array('comparison', '>=', 18), 
          'message' => 'Must be at least 18.'); 

//************
//validation end
//************ 

     if ($this->Number->save($this->data)) { 
        $this->Session->setFlash(__('The number has been saved', true)); 
        $this->redirect(array('action' => 'index')); 
     } else {
        $this->Session->setFlash(__('The number could not be saved. Please, try again.', true)); 
             } 
      } 
}


function lesserthanadd() {
      if (!empty($this->data)) {

//************
//validation strat
//************ 

       $this->Number->validate['number']['greaterthan'] = array(
            'rule' => array('comparison', '<=', 18),
            'message' => 'Must be at least 18.');

//************
//validation end
//************ 

       if ($this->Number->save($this->data)) {
           $this->Session->setFlash(__('The number has been saved', true));
           $this->redirect(array('action' => 'index'));
            } else {
           $this->Session->setFlash(__('The number could not be saved. Please, try again.', true));
            }
        }
    }