Just another WordPress.com site

Archive for the ‘php’ Category

PHP N-tier: Introduction N-Tier Strategy

PHP N-tier: Introduction N-Tier Strategy
PHP N-Tier Strategy Step By Step Tutorial – Part 1: May be you face complicated situation in your client’s architecture. They use many technology for solve their complicated business process. If it happen, n-tier may be possible one solution you can choice. It this post, we begin to understanding possible N-Tier architecture.
General principle that we must consider if wants to build N-tier application:
  • Every layer must be independent physically. It doesn’t mean every layer have to exist in separated computer. But, every layer can be distributed every where (separated computer or not).
  • Each layer must transfer information only to/from previous/next layer.
  • You can change technology used in every layer without change entire system. Example, – you want to change database layer- from mySql to PostgreSQL.
Following sample architecture design use 5-tier:
  • Presentation GUI, do parse HTML, XHTML, WML.
  • Presentation Logic do rendering process HTML, XHTML to send using HTTP to browser. It accepts data from business logic and tie to HTML. This process run at php at web server.
  • Business Logic, manipulate and transform data. Simple, task of this layer is fetch data from data access tier and prepare before send to presentation logic. This process run at server that utilize XML.
  • Data access tier have task to connect and retrieve data from database.
  • Data tier is aplication database such as mySQL, PostGreSQL, and others.

PHP N-tier: Possible n-tier Application Use PHP

PHP N-Tier Strategy Step By Step Tutorial – Part 2: In this post, we will try to design n-tier application use PHP. This is my 5-tier design:
  • Presentation GUI: Using smarty template to generate HTML.
  • Presentation Logic: PHP.
  • Business Logic: Use NuSOAP.
  • Data Access Tier: Using ADOdb.
  • Data tier: Using mySQL.
We ever talked about nusoap, adodb, and mysql. If you still understand about them, please read posts about them.

PHP N-tier: Database Layer Using MySQL

PHP N-Tier Strategy Step By Step Tutorial – Part 3: For practice, we will build simple application to show 5-tier design. We will begin from database layer. At the database layer, we use MySQL.
Create a database, for example “test”. Then create table. This is the query:

“CREATE TABLE `books` (

Next, try to insert sample data, such as:

“INSERT INTO `test`.`books` (
`id` ,
`title` ,
NULL , ‘PHP Undercover’, ‘Wiwit Siswoutomo’
), (
NULL , ‘PHP Enterprise’, ‘Wiwit Siswoutomo’

Ok, next post we will try how to connect database use PHP ADOdb as data access tier.

PHP N-tier: Data Access Tier Using PHP ADOdb

PHP N-Tier Strategy Step By Step Tutorial – Part 4: In this post, we will build data access tier. We use PHP Adodb. About PHP Adodb, you can read at here.
For this practice, create a folder named “ntier” within www/test. Place your all PHP ADOdb folder at here. Thus, you have www/test/ntier/adodb.
Then create a file named “dataaccess.php” within www/test/ntier. Enter following code

 $databasetype = ‘mysql’;
$server = ‘localhost’;
$user   = ‘root’;
$password = ‘admin’;
$database = ‘test’;
 $db = ADONewConnection($databasetype);
$db->debug = false;
$db->Connect($server, $user, $password, $database);
 $recordSet = &$db->Execute(‘select * from books’);
 if (!$recordSet)
  print $conn->ErrorMsg();
  while (!$recordSet->EOF) {
    print $recordSet->fields[0].’ ‘.$recordSet->fields[1].’ ‘.$recordSet->fields[2].’
 $recordSet->Close(); # optional

Test it. Open your browser. point to http://localhost/test/ntier/dataacces.php.

PHP N-tier: Building Business Logic

PHP N-Tier Strategy Step By Step Tutorial – Part 5: After create connection to database at this post, we will process this data. We prepare this data in order to can to send using webservices. We named this: business logic layer.
This practice only work well for php 4. In php 5, we will talk next serial post. Because there is embedded function in php 5. First, copy library of nusoap within www/test/ntier/lib. If you don’t understant to place nusoap, please read this post.
Open again file dataacces.php within www/test/ntier. Update like following:

// call library
require_once ( ‘./lib/nusoap.php’ ); //nusoap
require_once (‘adodb/adodb.inc.php’);//adodb
 // create instance
$server = new soap_server();
 // initialize WSDL support
$server->configureWSDL( ‘hello’ , ‘urn:hellowsdl’ );
 // place schema at namespace with prefix tns
$server->wsdl->schemaTargetNamespace = ‘urn:hellowsdl’;
 // register method
$server->register(‘books’,  // method name
array(), // input parameter
‘urn:hellowsdl’ , // namespace
‘urn:hellowsdl#hello’, // soapaction
‘rpc’, // style
‘encoded’, // use
‘Load list of book to the caller’ // documentation
 // configuration database
  // method
function books(){
  $db = ADONewConnection(__databasetype__);
  $db->debug = false;
  $db->Connect(__server__, __user__, __password__, __database__);
   $recordSet = &$db->Execute(‘select * from books’);
   if (!$recordSet){
        return new soap_fault(‘Server’,”,$conn->ErrorMsg());
  } else {
    while (!$recordSet->EOF) {
          $books[] = array(‘id’=>$recordSet->fields[0],
     $recordSet->Close();       #optional    

  // return value to client
  $obj = new soapval(‘return’,’array’,$books);
  return $obj->serialize();

Then, test it. Open your browser. Point to http://localhost/test/ntier/dataacces.php. You will get like this:

PHP N-tier: Building Presentation Logic

PHP N-Tier Strategy Step By Step Tutorial – Part 6: After create business logic, now we try to catch the data. We called this: presentation logic layer. We still use nusoap to do this job.
Just for practice, we will create client same folder/location with server function. Create a file named “client_book.php” within www/test/ntier. Enter following code:

require_once (‘lib/nusoap.php’);
 $client = new soapclient(‘http://localhost/test/ntier/dataacces.php’);
 $response = $client->call(‘books’);
  echo “FAULT: Code: (“.$client->faultcode.”)
  echo “String: “.$client->faultstring;
  $r = $response[0];
  $count = count($r);












Id Title Author


Now, open your browser and point to http://localhost/test/ntier/client_book.php.

PHP N-tier: Building Presentation GUI

PHP N-Tier Strategy Step By Step Tutorial – Part 7: We have grabbed data from server at presentation logic. And we tie data to html at previous post. It will give us more flexible if we you template system. So, we can change any layout without change all. for this job, we use smarty template.
Exactly, what is smarty template? I rewrite from their readme: Smarty is a template engine for PHP. Many other template engines for PHP provide basic variable substitution and dynamic block functionality. Smarty takes a step further to be a “smart” template engine, adding features such as configuration files, template functions, and variable modifiers, and making all of this functionality as easy as possible to use for both programmers and template designers.
First, please download smarty template at smarty.php.net. Extract compressed file to www/test/ntier. You will get folder named like “smarty-2.6.xx”. Rename, for simply, become: “smarty”.
Then, create folders named “templates” and “templates_c” within www/test/ntier.
Open again your client_book.php, rewrite with this code:

// call library
require_once (‘./lib/nusoap.php’);
require_once (‘./smarty/libs/smarty.class.php’);
 // retrieve data from server
// use webservice by nusoap
$client = new soapclient(‘http://localhost:8048/test/ntier/dataacces.php&#8217;);
$response = $client->call(‘books’);
  echo “FAULT: Code: (“.$client->faultcode.”)
  echo “String: “.$client->faultstring;
  // start using smarty
  $smarty = new Smarty;

  // assign parameters
  $smarty->assign(“title”,”Books Collection”);

  //load template

Now, you can see. Your code be more clean. No html tag over there. All html tag will be place at template.
Create a file named “template.tpl” within www/test/ntier/templates. Then enter following code:








{foreach key=key item=item from=$books}

  {foreach key=key item=item from=$item}



Id Title Author

Congrat! you have understand how to build 5-tier use php. You can expand this tutorial as you need.

memcached using php and perl

Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering.
The system uses a client–server architecture. The servers maintain a key–value associative array; the clients populate this array and query it. Keys are up to 250 bytes long and values can be at most 1 megabyte in size.
Clients use client side libraries to contact the servers which, by default, expose their service at port 11211. Each client knows all servers; the servers do not communicate with each other. If a client wishes to set or read the value corresponding to a certain key, the client’s library first computes a hash of the key to determine the server that will be used. Then it contacts that server. The server will compute a second hash of the key to determine where to store or read the corresponding value.
Perl script for fetching a Memcached result.

use Cache::Memcached;
use Digest::MD5;
use Digest::MD5 qw(md5 md5_hex md5_base64);
my $memcli = new Cache::Memcached {
    ‘servers’ => [ “” ],
    ‘debug’ => 0
my $serviceID=$ARGV[0];
print “Service ID__”.$serviceID.” **_\n”;
my $perlKey=’perl_’.$serviceID;
my $result = $memcli->get($perlKey);
#print “already : ___”.$result.”________\n”;
if($result eq “”)
#hit a php page to set memcache values if this key does not exist.
        use LWP::UserAgent;
        #my $serviceID = 12;
        my $url= “;;
        my $ua       = LWP::UserAgent->new();
        my $response = $ua->post( $url, { ‘id’ => $serviceID } );
        my $content  = $response->decoded_content();
        $result = $memcli->get($perlKey);
else {
        print “\n cached result \n “.$result;

Now the php page

$dbOBJ = new DB();
$conn = $dbOBJ->connectDB();
if ($conn){
$qry=’select id, abc, def, ghi, jkl, mno, pqr from table where id=’.$id; $memcache = new Memcache;
$memcache->connect(‘localhost’, 11211) or die (“Could not connect”);
$cache_result = array();
//$memcache->set($perlKey, $perlString, 0, 1);
$cache_result = $memcache->get($perlKey); // Memcached object
// Second User Request
echo “
$curser = OCIParse($conn,$qry);
OCIFetchInto($curser , $values);
$demos_result[]=$values; // Results storing in array
$memcache->set($key, $demos_result, 0, 100);
$perlString = $val1.’,’. $val2.’,’. $val3.’,’. $val4.’,’. $val5.’,’. $val6;
$memcache->set($perlKey, $perlString, 0, 10);
echo $errorMessage=’Other error’;

Fetch files from remote server automatically in PHP using Curl

PHP provides multiple ways to download and upload files to remote servers, such as fopen, fsockopen, cURL library, and other methods. fopen is the simplest but not the best. A while ago I wrote a function to fetch remote file by using fsockopen. However, I found a lot of problems when I use it. Then I read the PHP Cookbook and decided to try cURL library. After I implemented it in the independent class, it works like a charm. The following is the class source code.

// I adopt cURL library to download files
// It is reliable and fast, less hassle than fopen/fsockopen etc.

// this following three lines include testing code
// $file = new Remotefile("http://downloads.pcworld.com/pub/new/patches___drivers/utilities/framxpro.zip");
// $file->save2file("");
class Remotefile
// the url components
private $url = "";
// data get back from server
private $header = array();
private $content = "";
private $extension = "";

function __construct($url)

private function curl_url()
$c = curl_init($this->url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($c, CURLOPT_HEADER, 1);
$buffer = curl_exec($c);

// process data
$rnrn = "\r\n\r\n";
$pos = strpos($buffer,$rnrn);

if($pos === false)
// string $rnrn NOT found in $buffer
echo "Something is not correct!
// string $rnrn found in $buffer
$this->content = substr($buffer, $pos+4);
$header = substr($buffer, 0, $pos);

private function initialize($url)
// initialize all variables
$this->url = $url;
// fetch the remote file

private function processHeader($header)
$lines = explode("\r\n", $header);
$this->header["status"] = $lines[0];
foreach($lines as $line)
$data = explode(": ",$line);
if ($data[1] != "")
$this->header[$data[0]] = $data[1];
//echo "$data[0] |===| $data[1]

private function redirectedURL()
return $this->header["Location"];

private function getMIMEtype()
// check redirection url
$rdurl = $this->redirectedURL();
if ($rdurl)
$ext = ereg_replace("^.+\\.([^.]+)$", "\\1", $rdurl);
$this->extension = $ext;
$mtype = $this->header["Content-Type"];
$temps1 = split("/",$mtype);
$temps2 = split(";",$temps1[1]);
$ext1 = $temps2[0];
$this->extension = $ext1;
if (($temps1[0] == "application"))
$ext2 = ereg_replace("^.+\\.([^.]+)$", "\\1", $this->url);
if ($ext2)
$this->extension = $ext2;
$this->extension = trim($this->extension);
//echo "file extension = ".$this->extension."

function getHeader()
return $this->header;

function getContent()
return $this->content;

function save2file($folder)
// write to file
$filename = date('YmdHis').".".$this->extension;
$target_path = getcwd();
if ($folder)
$target_path .= "/$folder";
$target_path .= "/".$filename;
$Handle = fopen($target_path, 'w');
fwrite($Handle, $this->content);
return $filename;



I adopt cURL library to download files. It is reliable and fast, less hassle than fopen/fsockopen etc. To use the above class, at Ubuntu yot have to install libcurl and php5-curl by the following command:

apt-get install curl libcurl3 libcurl3-dev php5-curl

After this is done, just restart apache2 server by

/etc/init.d/apache2 restart

post a file using PHP to remote server without ftp

Recently I was working for a product where i have to post a file to a remote server where remote server dont allow outbout FTP.
And in this process i found a couple of methods to post file to server;

my required file was in Xml and have to post that xml to remote server where I can fetch that data
Its quite simple and easy method.

here are my findings

local file name : postfile.php
remote file name : receivexml.php

code for postfile.php

$thistext=”<?xml version=”1.0″?>
                        <expiry_message>Expiry Message</expiry_message>

$ch = curl_init(‘http://rem.ote.server.ip/receivexml.php&#8217;);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, “POST”);
curl_setopt($ch, CURLOPT_POSTFIELDS, $thistext);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
‘Content-Type: application/xml’,
‘Content-Length: ‘ . strlen($thistext)) );                                                                                                                  
$result = curl_exec($ch);

code for  receivexml.php

echo “test xml”;
    $postText = file_get_contents(‘php://input’);
$xml = new SimpleXMLElement($postText);
$result = $xml->xpath(‘/SERVICES/ serv1234/short’);
while(list( , $node) = each($result)) {
    echo $short=$node;
$myFile = “/directory/path/to/xml/”.$short.”.xml”;
$fh = fopen($myFile, ‘w’) or die(“can’t open file”);
fwrite($fh, $stringData);

in receivexml.php

  1. received the file and stored in  $postText
  2. parsed the xml data with xpath
  3. set the file name to a tag value in this case “short”
  4. write data to file.

Installing Nginx With PHP5 And MySQL Support On Ubuntu 12.04 (precise)

add relevant PPA in the source list.
 edit like

nano /etc/apt/sources.list

as i am using ubuntu 12.04 (precise ) so add following

deb http://ppa.launchpad.net/nginx/development/ubuntu precise main 
deb-src http://ppa.launchpad.net/nginx/development/ubuntu precise main

 First, for good measure lets make sure our server is all up-to-date.

apt-get update

Installing MySQL

Then let’s begin by installing MySQL:

apt-get install mysql-server mysql-client
after entering the above command you will also be prompted for a MySQL “root” user password…

Installing PHP

Next up, lets install PHP5 and a few common extensions (here is a list if you are in need of other extensions):

apt-get install php5-cgi php5-cli php5-mysql php5-curl php5-gd php5-idn php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-mhash php5-pspell php5-recode php5-sqlite php5-tidy php5-xmlrpc php5-xsl

As you may have noticed, we have installed php-cgi, that is because we will be running a FastCGI interface.
here are some articles online which recommend using lighttpd for its FastCGI interface, this is totally not needed. PHP has its own FastCGI interface which works perfectly well (thanks to Tomasz Sterna for a great article on FastCGI with Nginx)

At this point, we will be using a little bit of vim to do a bit of file editing, so here is a quick primer on using vim.
Lets create the following file:  

vim /etc/init.d/php-fastcgi

 This file will have the following content:


PHP_CGI_NAME=`basename $PHP_CGI`

start() {
      echo -n “Starting PHP FastCGI: “
      start-stop-daemon –quiet –start –background –chuid “$USER” –exec /usr/bin/env — $PHP_CGI_ARGS
      echo “$PHP_CGI_NAME.”
stop() {
      echo -n “Stopping PHP FastCGI: “
      killall -q -w -u $USER $PHP_CGI
      echo “$PHP_CGI_NAME.”

case “$1” in
      echo “Usage: php-fastcgi {start|stop|restart}”
      exit 1
exit $RETVAL

 As Tomasz Sterna mentions, you will need to fiddle with the PHP_FCGI_CHILDREN and PHP_FCGI_MAX_REQUESTS variables depending on your server’s amount of memory and compute power. I am running a baseline 256 MB / 10 GB Rackspace Cloud Server so I use the following settings which seem to work very well (as seen above):


Moving on … after you’ve created and saved the file we will make it executable and then start up the FastCGI service with the following commands:

chmod +x /etc/init.d/php-fastcgi
/etc/init.d/php-fastcgi start

We will want the service to auto start when we reboot our server, so we also do the following:

 update-rc.d php-fastcgi defaults

Installing Nginx

Installing Nginx is easy, use the following commands to install and then start up the Nginx server.

apt-get install nginx
/etc/init.d/nginx start

After installing Nginx, it will be automatically configured to start when we reboot our server (unlike the PHP FastCGI service we had to setup), so we are all set.

Testing Nginx and PHP

At this point we can see that Nginx is working by typing the server’s IP address into a web browser (http://%5BIP_ADDRESS%5D/). You should get a “Welcome to nginx!” message.
Now lets test PHP, we will create a generic phpinfo.php file with the following:

echo "" > /var/www/nginx-default/phpinfo.php

/var/www/nginx-default/ is the Nginx server default root directory…
If you use your browser to go to  


,you will notice that it doesn’t work … before this will work, we have to enable FastCGI in the Nginx config file. Open up the following file:

vim /etc/nginx/sites-available/default

in the server {

change #root /usr/share/nginx/www; 

to root /var/www;

Find the following lines (scroll to line 47):

#location ~ \.php$ {
    #fastcgi_index  index.php;
    #fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;

 and change them to (removing the # character from each line, changing line 50 and adding a space between include and fastcgi_params on line 51):

location ~ \.php$ {
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /var/www/nginx-default/$fastcgi_script_name;
    include fastcgi_params;

Now lets restart Nginx so our config changes will take effect:

/etc/init.d/nginx restart

 Now use your web browser to go to http://%5BIP_ADDRESS%5D/phpinfo.php, you should see a PHP info page.

Installing phpMyAdmin + phpMyAdmin Vhost Configuration 

apt-get install phpmyadmin

You will see the following questions:
Web server to reconfigure automatically: <– select none (because only apache2 and lighttpd are available as options)
Configure database for phpmyadmin with dbconfig-common? <– No
You can now find phpMyAdmin in the /usr/share/phpmyadmin/ directory. Now we must configure our vhost so that nginx can find phpMyAdmin in that directory.
Open /etc/nginx/sites-available/

nano /etc/nginx/sites-available/

 and add the following part to the server {} container:

server {
location /phpmyadmin {
root /usr/share/;
index index.php index.html index.htm;
location ~ ^/phpmyadmin/(.+\.php)$ {
try_files $uri =404;
root /usr/share/;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include /etc/nginx/fastcgi_params;
location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))$ {
root /usr/share/;
location /phpMyAdmin {
rewrite ^/* /phpmyadmin last;

Reload nginx:

/etc/init.d/nginx reload

That’s it! You can now go to
or http://localhost/phpmyadmin

 some useful links for further help regarding LEMP (linux,enginx,mysql,php)

  1. http://suckup.de/linux/ubuntu/nginx-php5-fpm-auf-debianubuntu/
  2. http://www.rackspace.com/knowledge_center/article/installing-nginx-and-php-fpm-running-on-unix-file-sockets
  3. http://www.howtoforge.com/running-phpmyadmin-on-nginx-lemp-on-debian-squeeze-ubuntu-11.04

php soap client Uncaught SoapFault exception

I was receiving the following error while running a php soap client on my live server
googled but of no use

[Tue May 22 12:09:33 2012] [error] [client] PHP Fatal error:  Uncaught SoapFault exception: [HTTP] Error Fetching http headers in /var/www/html/abc/xyz.php:7\nStack trace:\n
#0 [internal function]: SoapClient->__doRequest(‘
#1 /var/www/html/abc/xyz.php(7): SoapClient->__soapCall(‘auth_method’, Array)\n
#2 /var/www/html/abc/def.php(12): soapclient(‘user’, ‘pass’)\n
#3 {main}\n  thrown in /var/www/html/abc/xyz.php on line 7, referer: http://192.168……/abc/xyz.php?msgs=%3Cdiv%20class=%27eRR%27%3EPlease%20log%20in%20to%20visit%20this%20page%3C/div%3E

Solution: There was a little bug missing “;” in my soap server – I think some one changed the file.
check the remote file /Server there may b some error in Soap Server


%d bloggers like this: