[PHP][PHPExcel] Create Report Excel from PHP


Description
     Create report excel from PHP , only basic write :)

How To
    1. Download PHPExcel class Download Here
    2. after download you will see 3 folder (classes , example , documentation).
    3. if you want to learn you can find at example's folder , but the crucial part is Classes Folder , without that we cannot create excel.
    4. ok now we test the basic write from php to excel. here's the folder structure in your webserver :
        - Classes
        - Index.php //we create this file

        Here's the listing code for index.php :

<?php
/** Include PHPExcel */
require_once dirname(__FILE__) . '\Classes\PHPExcel.php';

// create object
$objPHPExcel = new PHPExcel();

// create metadata
$objPHPExcel->getProperties()->setCreator("name creator")
->setLastModifiedBy("name")
->setTitle("Report")
->setSubject("Report")
 ->setDescription("Report BOD")
->setKeywords("office PHPExcel php")
->setCategory("Test result file");

// insert data cell
$objPHPExcel->setActiveSheetIndex(0)
                      ->setCellValue('A1', 'this is A1')
                      ->setCellValue('B2', 'this is B2')
                      ->setCellValue('C1', 'this is C1')
                      ->setCellValue('D2', 'this is D2');

// create object for write
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

// save path and transform to excel , choose one if you think is easy
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
   or
$objWriter->save('C:\wamp\www\iniExcel.xlsx');
?>


*Note : don't forget __FILE__ is a magic constant from PHP (GET full path and filename of the file. )

[Cakephp] Helper Form

Deskripsi
How to use form helper

Required 
1. Understand Model , Controller , Routes , view , etc

How To
1. Form helper always write in view.
2. Here's the minimal syntax helper form must have
   $this->Form->create('model',array('url'=>array('controller'=>'myctrl','action'=>'myact',param1,..);
   $this->Form->input('field',array(*attribute*));
   $this->Form->submit('submit',array(*attribute*));
   $this->Form->end();

3.Here's the attribute for input

   - 'div'=>false/true
   - 'label'=>false/true
   - 'style'=>'your css here'
   - 'required'=>'required' // show exception when field is empty on click submit
   - 'maxlength'=>'50' //means 50 character
   - 'type' => 'text/select/textarea/date/hidden'
   - 'value' => 'abc' // fill the value for input object except select and date

    * for attribute type='select', you must add attribute options, for example

      $this->Form->input('field',array('type'=>'select','options'=>array('a','b','c')));

    * for attribute type='date' , you can customize format date like this 

      $this->Form->input('field',array('type'=>'date','dateFormat' => 'DMY'));// it will display current date

      but if you want using another value date instead current date you can write like this

      this->Form->input('field',array('type'=>'date','dateFormat' => 'DMY','dateFormat' => 'DMY','selected' => date('Y-m-d',strtotime('3/19/2014 00:00:00')))); // why Y-m-d because without dateFormat DMY the default is YMD.

[Cakephp] Authentication

Deskripsi
How to implement Authentication (login) using Cakephp Framework 2.X

Required 
1. Understand Form , Model , Controller , Routes

How To
1. Create table in your database and give it name "user", create 3 field : user_id, username , password.
2. Create Model , give it name "testModel.php"

<?php
class testModel extends AppModel
{
    var $useDBConfig = 'default';
    var $name = 'testModel '; //must same with file name
    var $primaryKey = 'id_user'; // primary key table
    var $useTable = 'user'; // same as table name in database
 
    public $validate = array(
        'username' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A username is required'
            )
        ),
        'password' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A password is required'
            )
        ));
}
?>

3. open file in path app/controller/AppController.php
   add code like this :


class AppController extends Controller { //you can find this line in the bottom  

/* Executing All Controller*/
var $uses = array('userlogin');
/* ----- */

public $components = array(
       'Session',
       'Auth' => array(
       'loginAction' => array('controller' => 'autentikasi','action' => 'login'),
       'authenticate' => array(
       'Form' => array(
       'userModel' => 'userlogin',
       'fields' => array('username' => 'username/email',
                          'password' => 'password' )
                       )
                       ),
       'Form','Basic',
       'loginRedirect' => array('controller' => 'Main',
       'action' => 'index'
        ),
       'logoutRedirect' => array(
       'controller' => 'autentikasi',
       'action' => 'login'
       ),
       'authorize' => array('Controller'), // <- activate isAuthorize()
       )
       );

  

 public function beforeFilter(){
        $this->layout = false;
        $this->Auth->deny('*');
        // don't forget to allow the action you'll be execute , if not it always forever loop to login page.
        $this->Auth->allow('login','not_supported');
 }

  

    public function isAuthorized($user) {

        // jika berhasil login , dapatkan data user

        if (isset($user['userlogin']['username']))

        {

            $dataUser = $this->userlogin->find('all', array('fields'=>array('userlogin.username','userlogin.role'),

                                                            'limit' => 10,

                                                            'conditions' => array('userlogin.username' => $user['userlogin']['username'],

                                                                                  'userlogin.password' => $user['userlogin']['password']

                                                                                   ),

                                                            'order'=>array('userlogin.username' => 'ASC')));

                if(!empty($dataUser))

                { 

                    $this->Session->write('login',true);

                    $this->Session->write('username',$dataUser[0]['userlogin']['username']);

                    $this->Session->write('role',$dataUser[0]['userlogin']['role']);

                    return true;

                }

                else

                {

                    $this->redirect($this->Auth->logout()); //force logout if false username and password

                    return false; //return false auth->login

                }

        }

        else

        {

            echo "Session failure please relogin !";

            return false;

        }

    }

}





4. open or create file in path app/controller/testAuthController.php
<?php

class testAuthController extends AppController {
var $uses = array('testModel ');

    public function index() {
                if ($this->request->is('post')) {
                    if ($this->Auth->login($this->request->data))
                   {
                     return $this->redirect($this->Auth->redirect());
                   }
                   else
                  {
                    $this->Session->setFlash(__('Invalid username or password, try again'));
                  }
               }
    }

    public function logout() {
    return $this->redirect($this->Auth->logout()); // this is calling logout redirect for button logout
    }
 
}

5. Now create form login for index action
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('testModel',array('url'=>array('controller'=>'testAuth','action'=>'index'))); ?>
                        <fieldset>
                            <legend>
                            <?php echo __('Please enter your username and password'); ?>
                            </legend>
                            <?php echo $this->Form->input('username'); // this data passing to username auth
                                  echo $this->Form->input('password'); // this data passing to password auth
                            ?>
                        </fieldset>
                        <?php echo $this->Form->end(__('Login'));
?>

6. Create routes for pretty url, open file in app/config/routes
add line :
 Router::connect('/', array('controller' => 'testAuth', 'action' => 'index', 'home'));
Router::connect('/login/*', array('controller' => 'testAuth', 'action' => 'index'));

Note :
1. if user not login , all page cannot be access and always redirect to login page.
2. if success login , all user can access ALL PAGE , to handle this authorization each user, you can use SESSION :)
3. if user logout , automaticly redirect to login page.

Work Greats , Happy Learning...

Note:
- Edited : fix code authentication