A simple code to export data to excel using PHP and cake php

Standard

A simple code to export data to excel using PHP and cake php

While generating a report in your project, you might have to download the data into excel file using PHP. In most scenario, you have to display the report in a page and create a link to download the report in the excel file. Well in that scenario, i think i can help you with a simplified code of PHP and cakephp.


Core Php

<?php
$filename =”excelreport.xls”;
$contents = “Name\t Email \t Mobile \t \n”;
$contents.= “Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n”;
$contents.= “Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n”;
$contents.= “Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n”;
header(‘Content-type: application/ms-excel’); /// you can set csv format
header(‘Content-Disposition: attachment; filename=’.$filename);
echo $contents;
?>

Cake php Code 
Past this code on controller
controlpanel_controller.php

class ControlpanelController extends AppController {
var $name=”Controlpanel”;
var $layout=false;

function file_export()
{
$this->autoRender=false;
ini_set(‘max_execution_time’, 1600); //increase max_execution_time to 10 min if data set is very large
$results = $this->ModelName->find(‘all’, array());// set the query function
foreach($results as $result)
{
$header_row.= $result[‘Doctor’][‘fname’].”\t”. $result[‘Doctor’][‘lname’] .”\t “.$result[‘User’][’email’].” \t \n”;

}
$filename = “export_”.date(“Y.m.d”).”.xls”;
header(‘Content-type: application/ms-excel’);
header(‘Content-Disposition: attachment; filename=”‘.$filename.'”‘);
echo($header_row);
}

}

Advertisements

How t0 protect .htaccess

Standard

Here is the code which shows the trick to protect the file using .htaccess file.

Protect File using .htaccess

Copy
 # protect file
<Files personal_data.txt>
order allow,deny
deny from all
</Files>

Enable access for particular user

Copy
 # protect file
<Files personal_data.txt>
order allow,deny
deny from all
allow from 1.2.3.4
allow from 45.85.245.105
</Files>

So above code will enable access from 1.2.3.4 and 45.85.245.105 only.

Access modifier public private protected

Standard

Definition of Access Specifiers
Access specifiers specify the level of access that the outside world (i.e. other class objects, external functions and global level code) have on the class methods and class data members. Access specifiers can either be public, private or protected.

Why do we need Access specifiers
Access specifiers are used as a key component of Encapsulation and Data Hiding. By using either of the access specifiers mentioned above i.e. public, private or protected you can hide or show the internals of your class to the outside world.

Explanation of each access specifier

  1. Private
    2. Protected
    3. Public
  1. Private
    A private access specifier is used to hide the data member or member function to the outside world. This means that only the class that defines such data member and member functions have access them. Look at the example below:

class Customer {

private $name;

public function setName($name) {

$this->name = $name;

}

public function getName() {

return $this->name;

}

}

$c = new Customer();

$c->setName(“Sunil Bhatia”);

echo $c->name; //error, $name cannot be accessed from outside the class

//$name can only be accessed from within the class

echo $c->getName(); //this works, as the methods of the class have access

//to the private data members or methods

In the above example, echo $c->name will give you an error as $name in class Customer has been declared private and hence only be accessed by its member functions internally. Therefore, the following line echo $c->getName() will display the name.

  1. Public
    A public access specifier provides the least protection to the internal data members and member functions. A public access specifier allows the outside world to access/modify the data members directly unlike the private access specifier. Look at the example below:

class Customer {

public $name;

public function setName($name) {

$this->name = $name;

}

public function getName() {

return $this->name;

}

}

$c = new Customer();

$c->setName(“Sunil Bhatia”);

echo $c->name;         // this will work as it is public.

$c->name = “New Name” ; // this does not give an error.

In the above example, echo $c->name will work as it has been declared as public and hence can be accessed by class member functions and the rest of the script.

  1. Protected
    A protected access specifier is mainly used with inheritance. A data member or member function declared as protected will be accessed by its class and its base class but not from the outside world (i.e. rest of the script). We can also say that a protected data member is public for the class that declares it and it’s child class; but is private for the rest of the program (outside world). Look at the example below:

class Customer {

protected $name;

public function setName($name) {

$this->name = $name;

}

public function getName() {

return $this->name;

}

}

class DiscountCustomer extends Customer {

private $discount;

public function setData($name, $discount) {

$this->name = $name; //this is storing $name to the Customer

//class $name variable. This works

// as it is a protected variable

$this->discount = $discount;

}

}

$dc = new DiscountCustomer();

$dc->setData(“Sunil Bhatia”,10);

echo $dc->name; // this does not work as $name is protected and hence

// only available in Customer and DiscountCustomer class

In the above example, echo $dc->name will not work work $name has been defined as a protected variable and hence it is only available in Customer and DiscountCustomer class.

You will learn more about inheritance later in this tutorial series. You should revisit this tutorial and read more on the protected section again when you understand inheritance better.

Important Note of Access Specifier in PHP5
In PHP5, access specifiers are public by default. This means that if you don’t specify an access specifier for a data member or method then the default ‘public’ is applicable.

Feel free to write comments if you need more examples or if you need to ask a question on PHP5 Class. You can also subscribe to my notification service to be informed as an when a new tutorial article goes online.

abstract class and interface class

Standard

Interface
An interface is a contract between unrelated objects to perform a common function. An interface enables you to specify that an object is capable of performing a certain function, but it does not necessarily tell you how the object does so, this means that it leaves for classes implementing an interface to define its behaviour.

To extend from an Interface, keyword implements is used.

We can have a class extend from more than one Interface.

interface Storable {
function getContentsAsText();
}

class Document implements Storable {
public function getContentsAsText() {
return “This is Text of the Document\n”;
}
}

class Indexer {
public function readAndIndex(Storable $s) {
$textData = $s->getContentsAsText();
//do necessary logic to index
echo $textData;
}
}

$p = new Document();

$i = new Indexer();
$i->readAndIndex($p);

In the above example, Document and the Indexer class are two independant classes. The Indexer class is designed to index the contents of any text. Using the Storable interface above, we declare a method getContentsAsText() in the Document class. Because the Indexer class is only concerned with the TEXT, hence we can call getContentsAsText() method on the object of Document. This way any class if it implements the method getContentsAsText() can get indexed.

abstract Class

An abstract class is a class with or without data members that provides some functionality and leaves the remaining functionality for its child class to implement. The child class must provide the functionality not provided by the abstract class or else the child class also becomes abstract.

Objects of an abstract and interface class cannot be created i.e. only objects of concrete class can be created

To define a class as Abstract, the keyword abstract is to be used e.g. abstract class ClassName { }

Example of Abstract Class

abstract class Furniture {
private $height, width, length;

public function setData($h, $w, $l) {
$this->height = $h;
$this->width = $w;
$this->length = $l;
}

//this function is declared as abstract and hence the function
//body will have to be provided in the child class
public abstract function getPrice();

}

class BookShelf extends Furniture {

private $price;

public setData($h, $w, $l, $p) {
parent::setData($h, $w, $l);
$this->price = $p;
}

//this is the function body of the parent abstract method
public function getPrice() {
return $this->price;
}
}
In the above example, the method getPrice() in class Furniture has been declared as Abstract. This means that its the responsibility of the child class to provide the functionality of getPrice(). The BookShelf class is a child of the Furniture class and hence provides the function body for getPrice().

Difference between Abstract Class and Interface
Abstract Classes

An abstract class can provide some functionality and leave the rest for derived class
The derived class may or may not override the concrete functions defined in base class
The child class extended from an abstract class should logically be related
Interface

An interface cannot contain any functionality. It only contains definitions of the methods
The derived class must provide code for all the methods defined in the interface
Completely different and non-related classes can be logically be grouped together using an interface

How to install symfony framework on your localhost

Standard

<IfModule mod_rewrite.c>
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app_dev.php [QSA,L]
</IfModule>

 

httpd_vhost file

virtual directory:
<VirtualHost *:80>
ServerName symfony.localhost
DocumentRoot C:/xampp/htdocs/myproject/web
SetEnv APPLICATION_ENV “development”
<Directory C:/xampp/htdocs/symfony/web>
AllowOverride All
Order allow,deny
Allow from all
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /app_dev.php [QSA,L]
</IfModule

</Directory>
</VirtualHost>

hosts file

127.0.0.1 symfony.localhost

Now you can run

http://symfony.localhost/app_dev.php

 

You have to create the database name “like     symfony

After that you click the configure file and go step by step

dymfonyddd

 

Now you can start you development

 

 

 

 

Install zend framework 2

Standard

many people facing issue in  configuration of Zend Framework 2 lately. The manual on Zend Framework‘s website is horrible (in terms of beginner manual and documentation) and is designed for advanced user’s with Zend Framework 1 extensive experience.

Many users are still unable to create a first basic folder structure to begin using Zend Framework 2 library. The initial example is provided here. I’m going to break it down for you guys.

(Note: This instruction guide assumes you have successfully installed Apache web server and PHP 5.3 or above)

Method 1: by downloading skeleton application

Step 1: First Download the Zend Framework Skeleton Application from here. Secondly, extract the files into your root (www) localhost folder and rename the folder to anything you want. I will call it “zf_project1”.path look like this – C:\Program Files\php_5_4_15_Win32_VC9_x86\www\zf_project1
This file provides you with all the necessary files to create your basic folder structure.

Step 2: Open your Terminal. (In Windows 7, click Start and in the search box type “cmd” (no quotes), and click cmd.exe.

Step 3: Once opened, use the “cd” command to navigate to the folder where you extracted your zip file you downloaded in step 1 (“zf_project1”). My command looks like this “cd C:\Program Files\php_5_4_15_Win32_VC9_x86\www\zf_project1″. You should be inside the folder now and your line in Terminal should resemble this “C:\Program Files\php_5_4_15_Win32_VC9_x86\www\zf_project1>

Step 4: Now type this command, “php composer.phar self-update” and press Enter.

For me look like this:

C:\Program Files\php_5_4_15_Win32_VC9_x86\www\zf_project1>php composer.phar self-update

Output look like bellow:

Updating to version f56b985884b1631dbcbc675434ead96168462824.

Downloading: 100%

Step 5: Type another command, “php composer.phar install”. This will create your directories for basic skeleton application.

For me look like this:

C:\Program Files\php_5_4_15_Win32_VC9_x86\www\zf_project1>php composer.phar install

Output look like bellow:

Loading composer repositories with package information

Installing dependencies (including require-dev)

– Installing zendframework/zendframework (2.2.0)

Loading from cache

zendframework/zendframework suggests installing ext-intl (ext/intl for i18n features (included in default builds of PHP))

zendframework/zendframework suggests installing doctrine/annotations (Doctrine Annotations >=1.0 for annotation features)

zendframework/zendframework suggests installing ircmaxell/random-lib (Fallback random byte generator for Zend\Math\Rand if OpenSSL/Mcrypt extensions are unavailable)

zendframework/zendframework suggests installing ocramius/proxy-manager (ProxyManager to handle lazy initialization of services)

zendframework/zendframework suggests installing zendframework/zendpdf (ZendPdf for creating PDF representations of barcodes)

zendframework/zendframework suggests installing zendframework/zendservice-recaptcha (ZendService\ReCaptcha for rendering ReCaptchas in Zend\Captcha and/or Zend\Form)

Writing lock file

Generating autoload files

That’s all. Now, open your browser and navigate to your localhost and zf_project1/public folder (mine looks like this: http://localhost/zf_project1/public/). You should see this website. If you do, then every step has been successfully completed.

Method 2: by using zendtool

Step 1: First Download the Zend Tool from here. Secondly, extract the files into your root (www) localhost folder and rename the folder to anything you want. I will call it “zendtool. So zendtool path look like this – C:\Program Files\php_5_4_15_Win32_VC9_x86\www\zendtool

This file provides you with all the necessary files to create your basic folder structure.

Step 2: Download the zftool.phar from packages.zendframework.com

And copy it to zendtool folder.

Step 3: Open your Terminal. (In Windows 7, click Start and in the search box type “cmd” (no quotes), and click cmd.exe.

Step 4: Once opened, use the “cd” command to navigate to the folder where you created your project in your root (www) localhost folder. My command looks like this “cd C:\Program Files\php_5_4_15_Win32_VC9_x86\www″. You should be inside the root folder now and your line in Terminal should resemble this “C:\Program Files\php_5_4_15_Win32_VC9_x86\www>″.

Step 5: Now type this command, “php zendtool/zftool.phar version” and press Enter, To check zendtool. For me look like this:

C:\Program Files\php_5_4_15_Win32_VC9_x86\www>php zendtool/zftool.phar version

Output look like bellow:

ZFTool – Zend Framework 2 command line Tool

The ZFTool is using Zend Framework 2.2.0

This means zendtool install and working fine.

Step 6: Now type this command,”php zendtool/zftool.phar create project zf_project1” and press enter, to create project “zf_project1”. For me look like this:

C:\Program Files\php_5_4_15_Win32_VC9_x86\www>php zendtool/zftool.phar create project zf_project1

Output look like bellow:

ZF2 skeleton application installed in zf_project1.

In order to execute the skeleton application you need to install the ZF2 library.

Execute: “composer.phar install” in zftest

For more info in zftest/README.md

 

Step 7: Now use the “cd” command to navigate to the project. My command looks like this “cd zf_project1

C:\Program Files\php_5_4_15_Win32_VC9_x86\www>cd zf_project1

Now you should be inside the project folder and your line in Terminal should resemble this “C:\Program Files\php_5_4_15_Win32_VC9_x86\www\zf_project1>″.

Step 8: Now type this command, “php composer.phar self-update” and press Enter.

For me look like this:

C:\Program Files\php_5_4_15_Win32_VC9_x86\www\ zf_project1>php composer.phar self-update

Output look like bellow:

Updating to version 1a7f734bc78df99553a742dfac6651a4863c00c6.

Downloading: 100%

Step 9: Now type this command, “php composer.phar install” and press Enter.

For me look like this:

C:\Program Files\php_5_4_15_Win32_VC9_x86\www\ zf_project1>php composer.phar install

Output look like bellow:

Loading composer repositories with package information

Installing dependencies (including require-dev)

– Installing zendframework/zendframework (2.2.0)

Loading from cache

zendframework/zendframework suggests installing ext-intl (ext/intl for i18n features (included in default builds of PHP))

zendframework/zendframework suggests installing doctrine/annotations (Doctrine Annotations >=1.0 for annotation features)

zendframework/zendframework suggests installing ircmaxell/random-lib (Fallback random byte generator for Zend\Math\Rand if OpenSSL/Mcrypt extensions are unavailable)

zendframework/zendframework suggests installing ocramius/proxy-manager (ProxyManager to handle lazy initialization of services)

zendframework/zendframework suggests installing zendframework/zendpdf (ZendPdf for creating PDF representations of barcodes)

zendframework/zendframework suggests installing zendframework/zendservice-recaptcha (ZendService\ReCaptcha for rendering ReCaptchas in Zend\Captcha and/or Zend\Form)

Writing lock file

Generating autoload files

That’s all. Now, open your browser and navigate to your localhost and zf_project1/public folder (mine looks like this: http://localhost/zf_project1/public/). You should see this website. If you do, then every step has been successfully completed.

References:

1.)    http://framework.zend.com/manual/2.2/en/user-guide/overview.html

2.)    http://framework.zend.com/manual/2.2/en/user-guide/skeleton-application.html

3.)    https://github.com/zendframework/ZFTool/

4.)    http://framework.zend.com/manual/2.2/en/modules/zendtool.introduction.html

Update 1 – 12-06-3013

if you see this:

C:\Program Files\php_5_4_15_Win32_VC9_x86\www\zf_project1>php composer.phar install
Composer only officially supports PHP 5.3.2 and above, you will most likely encounter problems with your PHP 5.3.1, upgrading is strongly
recommended.
Loading composer repositories with package information
Installing dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
– The requested package php >=5.3.3 could not be found.
Problem 2
– zendframework/zendframework 2.2.0rc3 requires php >=5.3.3 -> no matching package found.
– zendframework/zendframework 2.2.0rc2 requires php >=5.3.3 -> no matching package found.
– zendframework/zendframework 2.2.0 requires php >=5.3.3 -> no matching package found.
– Installation request for zendframework/zendframework >2.2.0rc1 -> satisfiable by zendframework/zendframework[2.2.0, 2.2.0rc2, 2.2.0r
c3].

Potential causes:
– A typo in the package name
– The package is not available in a stable-enough version according to your minimum-stability setting
see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion&gt; for more details.

Read <http://getcomposer.org/doc/articles/troubleshooting.md&gt; for further common problems.

This means PHP version not appropriate, you must have 5.3.3 or above.

So now first upgrade php:

download your desired version of php binary from http://windows.php.net/download/ website. download Thread Safe binary zip version. Unzip the downloaded version of the PHP in a separate folder. Please make sure that your new php folder name is not “PHP”. May be you can use filder name as the version name. For example for php 5.4 you can use php54.

Copy the new php folder into your xampp folder. Now go to yourxampp/apache/conf/extra folder. Open file httpd-xampp.conf from the folder extra. Change the following variables:

variable LoadFile and PHPINIDir

Variable PHPINIDir to be / Varaible LoadModule to be //php5apache2_2.dl

Save the file httpd-xampp.conf. Restart your XAMPP apache server. If your server get restarted successfully then your server php version is upgraded.

References:

http://hype-free.blogspot.in/2007/07/updating-php-in-xampp-for-windows.html

http://stackoverflow.com/questions/2154762/upgrading-php-in-xampp-for-windows

Update 2- 13-06-3013

if you see this:

C:\Program Files\php_5_4_15_Win32_VC9_x86\www\zf_project1>php composer.phar install
Loading composer repositories with package information
Installing dependencies (including require-dev)
– Installing zendframework/zendframework (2.2.0)
Downloading: 100%
Downloading: 100%
Downloading: 100%

 

[Composer\Downloader\TransportException]
The “http://nodeload.github.com/zendframework/zf2/zip/release-2.2.0&#8243; file could not be downloaded: failed to open stream: Unable to f
ind the socket transport “ssl” – did you forget to enable it when you configured PHP?

 

install [–prefer-source] [–prefer-dist] [–dry-run] [–dev] [–no-dev] [–no-custom-installers] [–no-scripts] [–no-progress] [-v|vv|vv
v|–verbose] [-o|–optimize-autoloader]

This means openssl not enabled in php, you must enable it.

So now first enable openssl php:

  1. Rename php.ini-production to php.ini (in C:\xampp\php\ folder)
  2. Edit php.ini and uncomment extension_dir=ext.
  3. Also uncomment extension=php_openssl.dll.

References:

http://stackoverflow.com/questions/1705856/socket-transport-ssl-in-php-not-enabled

http://stackoverflow.com/questions/2154762/upgrading-php-in-xampp-for-windows

Now i hope you will install  ZF2.