All your web development code goes here

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` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,`title` VARCHAR( 255 ) NOT NULL ,`author` VARCHAR( 60 ) NOT NULL) ENGINE = MYISAM ;


Next, try to insert sample data, such as:

“INSERT INTO `test`.`books` (
`id` ,
`title` ,
`author`
)
VALUES (
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

include(‘adodb/adodb.inc.php’);
 $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();
else
  while (!$recordSet->EOF) {
    print $recordSet->fields[0].’ ‘.$recordSet->fields[1].’ ‘.$recordSet->fields[2].’
‘;
  $recordSet->MoveNext();     
}  
 $recordSet->Close(); # optional
             
$db->Close();
 ?>























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
array(‘return’=>’xsd:array’),
‘urn:hellowsdl’ , // namespace
‘urn:hellowsdl#hello’, // soapaction
‘rpc’, // style
‘encoded’, // use
‘Load list of book to the caller’ // documentation
);
 // configuration database
define(__databasetype__,’mysql’);
define(__server__,’localhost’);
define(__user__,’root’);
define(__password__,’admin’);
define(__database__,’test’);
  // 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],
                           ‘title’=>$recordSet->fields[1],
                                         ‘author’=>$recordSet->fields[2]
                          );
      $recordSet->MoveNext();     
    }  
     $recordSet->Close();       #optional    
    $db->Close();
  }

  // return value to client
  $obj = new soapval(‘return’,’array’,$books);
  return $obj->serialize();
 
}
  $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ”;
$server->service($HTTP_RAW_POST_DATA);
?>























































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’);
 if($client->fault)
{
  echo “FAULT: Code: (“.$client->faultcode.”)
“;
  echo “String: “.$client->faultstring;
}
else
{
  $r = $response[0];
  $count = count($r);
?>
 

   

     

     

      
      

   

        for($i=0;$i<=$count-1;$i++){
        ?>
   

     

     

     

   

            }
        ?>
 

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’);
 if($client->fault)
{
  echo “FAULT: Code: (“.$client->faultcode.”)
“;
  echo “String: “.$client->faultstring;
  die();
}
else
{
  // start using smarty
  $smarty = new Smarty;

  // assign parameters
  $smarty->assign(“title”,”Books Collection”);
  $smarty->assign(“books”,$response[0]);

  //load template
  $smarty->display(‘template.tpl’);
}
?>




























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:

{$title}

 

   

     

     

      
      

   

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

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

  {/foreach}
    

{/foreach}
 

Id Title Author
{$item}





















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’ => [ “192.168.0.27:11211” ],
    ‘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= “http://192.168.0.27/chargerequest/perlcache.php&#8221;;
        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

include(“db.php”);
$dbOBJ = new DB();
$conn = $dbOBJ->connectDB();
if ($conn){
$serviceid=$_REQUEST[‘id’];
$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”);
$perlKey=’perl_’.$serviceid;
$cache_result = array();
//$memcache->set($perlKey, $perlString, 0, 1);
$cache_result = $memcache->get($perlKey); // Memcached object
if($cache_result)
{
// Second User Request
echo “
caching
“;
$dbOBJ->print_rr($cache_result);
$demos_result=$cache_result;
}
else
{
$curser = OCIParse($conn,$qry);
OCIExecute($curser);
OCIFetchInto($curser , $values);
$demos_result[]=$values; // Results storing in array
$memcache->set($key, $demos_result, 0, 100);
$val1=$demos_result[0][0];          
$val2=$demos_result[0][1];
$val3=$demos_result[0][2];        
$val4=$demos_result[0][3];        
$val5=$demos_result[0][4];          
$val6=$demos_result[0][5];
$perlString = $val1.’,’. $val2.’,’. $val3.’,’. $val4.’,’. $val5.’,’. $val6;
$memcache->set($perlKey, $perlString, 0, 10);
}
}
else
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)
{
$this->initialize($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);
curl_close($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!
";
}
else
{
// string $rnrn found in $buffer
$this->content = substr($buffer, $pos+4);
$header = substr($buffer, 0, $pos);
$this->processHeader($header);
}
}

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

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;
}
else
{
$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
$this->getMIMEtype();
$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);
fclose($Handle);
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″?>
        <SERVICES>
          <serv1234>
                <short>1234</short>
                <isuser>0</isuser>
                <keyword>keyword</keyword>
                <table>wltable</table>
                <expiry>
                        <expiry_status>1</expiry_status>
                        <expiry_startdate>04-JUL-12</expiry_startdate>
                        <expiry_enddate>27-JUL-12</expiry_enddate>
                        <expiry_message>Expiry Message</expiry_message>
                </expiry>
             
          </serv1234>
        </SERVICES>“;


$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);
print_r($result);
curl_close($ch);

code for  receivexml.php

echo “test xml”;
if ( $_SERVER[‘REQUEST_METHOD’] === ‘POST’ ){
    $postText = file_get_contents(‘php://input’);
}
//print_r($postText);
$shortcode=”;
$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”);
$stringData=$postText;
fwrite($fh, $stringData);
fclose($fh);
?>

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:

#!/bin/bash
BIND=127.0.0.1:9000
USER=www-data
PHP_FCGI_CHILDREN=5
PHP_FCGI_MAX_REQUESTS=500

PHP_CGI=/usr/bin/php-cgi
PHP_CGI_NAME=`basename $PHP_CGI`
PHP_CGI_ARGS=”- USER=$USER PATH=/usr/bin PHP_FCGI_CHILDREN=$PHP_FCGI_CHILDREN PHP_FCGI_MAX_REQUESTS=$PHP_FCGI_MAX_REQUESTS $PHP_CGI -b $BIND”
RETVAL=0

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

case “$1” in
    start)
      start
  ;;
    stop)
      stop
  ;;
    restart)
      stop
      start
  ;;
    *)
      echo “Usage: php-fastcgi {start|stop|restart}”
      exit 1
  ;;
esac
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):

PHP_FCGI_CHILDREN=5
PHP_FCGI_MAX_REQUESTS=500

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  

http://%5BIP_ADDRESS%5D/phpinfo.php 

,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_pass   127.0.0.1:9000;
    #fastcgi_index  index.php;
    #fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #includefastcgi_params;
#}

 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_pass   127.0.0.1:9000;
    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_pass 127.0.0.1:9000;
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

http://127.0.0.1/phpmyadmin/
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 39.47.135.86] 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

nginx

Install phpMyAdmin on CentOs

while installing phpmyadmin on my local machine using vmware at Centos 5.5.

i faced some problems so thought to share the steps for other to overcome these problems.
1. Update the packages

# yum update -y

2. Install MySQL packages

# yum install mysql-server mysql mysql-devel

3. Make MySQL boot up automatically

# chkconfig mysqld on

4. Start MySQL service

# service mysqld start
# /etc/init.d/mysqld restart

5. Set the password for the root user

# /usr/bin/mysql_secure_installation (Recommended)
OR
# mysqladmin -u root password eaziweb

6. Install php and common packages

# yum install php php-gd php-imap php-mysql php-pear php-xml phpxmlrpc curl libxml2 php-mbstring php-mcrypt

7. Install phpMyAdmin
Because the version of php on CentOS 5.5 is 5.1.6, we only can install phpMyAdmin 2.x, I choose 2.11.11.3.

# cd /usr/share
# wget http://sourceforge.net/projects/phpmyadmin/files/phpMyAdmin/2.11.11.3/phpMyAdmin-2.11.11.3-english.tar.gz/download
# tar xvfz phpMyAdmin-2.11.11.3-english.tar.gz
# mv phpMyAdmin-2.11.11.3-english phpmyadmin
# rm phpMyAdmin-2.11.11.3-english.tar.gz
# cd phpmyadmin
# cp config.sample.inc.php config.inc.php

8. Edit the config.inc.php file, find the line that contain “blowfish_secret”, and modify like below.

$cfg[‘blowfish_secret’] = ‘TypeAnything_for_Secure’;

9. Restart the httpd service

# /etc/init.d/httpd restart

10. Enter the URL http://%5BIP Address]/phpMyAdmin/ on Firefox browser, we’ll can see the login web page.

http://localhost/phpMyAdmin

After inputting the root user and its password(eaziweb), we can use phpMyAdmin to manage the MySQL.
Errors
1. 404 Not Found Error
Please make sure you push your phpMyAdmin directory in your webroot. In my case it’s /var/www/html

cp -r phpMyAdmin/ /var/www/html/

2. 403 Forbidden Error
I spend good amount of time finding why access is forbidden and finally did following setting

2.1 Go to /etc/httpd/conf.d/
2.2 vi phpMyAdmin.conf
2.3 Add following lines

Order allow,deny
Options Indexes
Allow from all

Still not able to access, try disabling the SElinux
SElinux is extra security layer in Linux and sometimes it provide conflicts for apache to work

vi /etc/selinux/config

Modify SELINUX=enforcing  to SELINUX=disabled  //Discuss with your senior. Mine is test server.
Restart your machine
hit http://localhost/phpMyAdmin prompt for username/password for mysql login 
Please note all the steps executed via root credentials . You can use su command to login as root and carry the same steps.

How to Check if a Date is More or Less Than a Month Ago with PHP

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { background: transparent; border: 0; margin: 0; padding: 0; vertical-align: baseline; } body { line-height: 1; } h1, h2, h3, h4, h5, h6 { clear: both; font-weight: normal; } ol, ul { list-style: none; } blockquote { quotes: none; } blockquote:before, blockquote:after { content: ”; content: none; } del { text-decoration: line-through; } /* tables still need ‘cellspacing=”0″‘ in the markup */ table { border-collapse: collapse; border-spacing: 0; } a img { border: none; } /* =Layout ————————————————————– */ /* LAYOUT: Two columns DESCRIPTION: Two-column fixed layout with one sidebar right of content */ #container { float: left; margin: 0 -240px 0 0; width: 149%; } #content { margin: 0 280px 0 20px; } #primary, #secondary { float: right; overflow: hidden; width: 220px; } #secondary { clear: right; } #footer { clear: both; width: 100%; } /* LAYOUT: One column, no sidebar DESCRIPTION: One centered column with no sidebar */ .one-column #content { margin: 0 auto; width: 640px; } /* LAYOUT: Full width, no sidebar DESCRIPTION: Full width content with no sidebar; used for attachment pages */ .single-attachment #content { margin: 0 auto; width: 900px; } /* =Fonts ————————————————————– */ body, input, textarea, .page-title span, .pingback a.url { font-family: Raleway,’Helvetica Neue’,Helvetica,sans-serif; } h3#comments-title, h3#reply-title, #access .menu, #access div.menu ul, #cancel-comment-reply-link, .form-allowed-tags, #site-info, #site-title, #wp-calendar, .comment-meta, .comment-body tr th, .comment-body thead th, .entry-content label, .entry-content tr th, .entry-content thead th, .entry-meta, .entry-title, .entry-utility, #respond label, .navigation, .page-title, .pingback p, .reply, .widget-title, .wp-caption-text { font-family: “Helvetica Neue”, Arial, Helvetica, “Nimbus Sans L”, sans-serif; } input[type=submit] { font-family: “Helvetica Neue”, Arial, Helvetica, “Nimbus Sans L”, sans-serif; } pre { font-family: “Courier 10 Pitch”, Courier, monospace; } code { font-family: Monaco, Consolas, “Andale Mono”, “DejaVu Sans Mono”, monospace; } /* =Structure ————————————————————– */ /* The main theme structure */ #access .menu-header, div.menu, #colophon, #branding, #main, #wrapper { margin: 0 auto; /*width: 940px;*/ } #wrapper { background: none repeat scroll 0 0 #FFFFFF; border: 1px solid #CCCCCC; border-radius: 10px 10px 10px 10px; padding: 0 15px; } /* Structure the footer area */ #footer-widget-area { overflow: hidden; } #footer-widget-area .widget-area { float: left; margin-right: 20px; width: 220px; } #footer-widget-area #fourth { margin-right: 0; } #site-info { float: left; font-size: 14px; font-weight: bold; width: 700px; } #site-generator { float: right; width: 220px; } /* =Global Elements ————————————————————– */ /* Main global ‘theme’ and typographic styles */ body { background: #f1f1f1; background-attachment: fixed; } body, input, textarea { color: #666; font-size: 12px; line-height: 18px; } hr { background-color: #e7e7e7; border: 0; clear: both; height: 1px; margin-bottom: 18px; } /* Text elements */ p { margin-bottom: 18px; } ul { list-style: square; margin: 0 0 18px 1.5em; } ol { list-style: decimal; margin: 0 0 18px 1.5em; } ol ol { list-style: upper-alpha; } ol ol ol { list-style: lower-roman; } ol ol ol ol { list-style: lower-alpha; } ul ul, ol ol, ul ol, ol ul { margin-bottom: 0; } dl { margin: 0 0 24px 0; } dt { font-weight: bold; } dd { margin-bottom: 18px; } strong { font-weight: bold; } cite, em, i { font-style: italic; } big { font-size: 131.25%; } ins { background: #ffc; text-decoration: none; } blockquote { font-style: italic; padding: 0 3em; } blockquote cite, blockquote em, blockquote i { font-style: normal; } pre { background: #f7f7f7; color: #222; line-height: 18px; margin-bottom: 18px; padding: 1.5em; } abbr, acronym { border-bottom: 1px dotted #666; cursor: help; } sup, sub { height: 0; line-height: 1; position: relative; vertical-align: baseline; } sup { bottom: 1ex; } sub { top: .5ex; } input[type=”text”], textarea { background: #f9f9f9; border: 1px solid #ccc; } a:link { color: #0066cc; } a:visited { /* color: #743399; */ } a:active, a:hover { color: #ff4b33; } /* Text meant only for screen readers */ .screen-reader-text { position: absolute; left: -9000px; } /* =Header ————————————————————– */ #header { padding: 10px 0 0 0; } #site-title { float: left; font-size: 30px; line-height: 36px; margin: 0; } #site-title a { text-decoration: none; color: #000; font-size: 20px; font-weight: 100; font-family: Raleway,’Helvetica Neue’,Helvetica,sans-serif; text-transform: uppercase; } #site-description { clear: right; float: right; font-style: italic; margin: 15px 0 18px 0; font-size: 23px; font-family: Georgia, sans-serif; } /* This is the custom header image */ #branding img { border-top: 4px solid #000; border-bottom: 1px solid #000; display: block; float: left; } /* =Menu ————————————————————– */ #access { background: #000; display: block; float: left; margin: 0 auto; width: 940px; } #access .menu-header, div.menu { font-size: 13px; margin-left: 12px; width: 928px; } #access .menu-header ul, div.menu ul { list-style: none; margin: 0; } #access .menu-header li, div.menu li { float: left; position: relative; } #access a { color: #aaa; display: block; line-height: 38px; padding: 0 10px; text-decoration: none; } #access ul ul { box-shadow: 0px 3px 3px rgba(0,0,0,0.2); -moz-box-shadow: 0px 3px 3px rgba(0,0,0,0.2); -webkit-box-shadow: 0px 3px 3px rgba(0,0,0,0.2); display: none; position: absolute; top: 38px; left: 0; float: left; width: 180px; z-index: 99999; } #access ul ul li { min-width: 180px; } #access ul ul ul { left: 100%; top: 0; } #access ul ul a { background: #333; line-height: 1em; padding: 10px; width: 160px; height: auto; } #access li:hover > a, #access ul ul :hover > a { background: #333; color: #fff; } #access ul li:hover > ul { display: block; } #access ul li.current_page_item > a, #access ul li.current-menu-ancestor > a, #access ul li.current-menu-item > a, #access ul li.current-menu-parent > a { color: #fff; } * html #access ul li.current_page_item a, * html #access ul li.current-menu-ancestor a, * html #access ul li.current-menu-item a, * html #access ul li.current-menu-parent a, * html #access ul li a:hover { color: #fff; } /* =Content ————————————————————– */ #main { clear: both; overflow: hidden; /*padding: 40px 0 0 0;*/ } #content { margin-bottom: 36px; } #content, #content input, #content textarea { color: #333; font-size: 16px; line-height: 24px; } #content p, #content ul, #content ol, #content dd, #content hr { margin-bottom: 24px; font-family: Verdana,Arial,Geneva,Helvetica,sans-serif; font-size: 0.75em; } #content ul ul, #content ol ol, #content ul ol, #content ol ul { margin-bottom: 0; } #content pre, #content kbd, #content tt, #content var { font-size: 15px; line-height: 21px; } #content code { font-size: 13px; } #content dt, #content th { color: #000; } #content h1, #content h2, #content h3, #content h4, #content h5, #content h6 { color: #009BC1; line-height: 1.5em; margin: 0 0 20px 0; } #content table { border: 1px solid #e7e7e7; margin: 0 -1px 24px 0; text-align: left; width: 100%; } #content tr th, #content thead th { color: #888; font-size: 12px; font-weight: bold; line-height: 18px; padding: 9px 24px; } #content tr td { border-top: 1px solid #e7e7e7; padding: 6px 24px; } #content tr.odd td { background: #f2f7fc; } .hentry { margin: 0 0 48px 0; } .home .sticky { background: #f2f7fc; border-top: 4px solid #000; margin-left: -20px; margin-right: -20px; padding: 18px 20px; } .single .hentry { margin: 0 0 36px 0; } .page-title { color: #000; font-size: 14px; font-weight: bold; margin: 0 0 36px 0; } .page-title span { color: #333; font-size: 16px; font-style: italic; font-weight: normal; } .page-title a:link, .page-title a:visited { color: #888; text-decoration: none; } .page-title a:active, .page-title a:hover { color: #ff4b33; } #content .entry-title { color: #009BC1; font-size: 170%; font-weight: 100; margin-bottom: 0; font-family: Raleway,’Helvetica Neue’,Helvetica,sans-serif; } .entry-title a:link, .entry-title a:visited { color: #009BC1; text-decoration: none; font-family: Raleway,’Helvetica Neue’,Helvetica,sans-serif; font-size: 100%; font-weight: 100; } .entry-title a:active, .entry-title a:hover { color: #ff4b33; } .entry-meta { color: #888; font-size: 12px; } .entry-meta abbr, .entry-utility abbr { border: none; } .entry-meta abbr:hover, .entry-utility abbr:hover { border-bottom: 1px dotted #666; } .entry-content, .entry-summary { clear: both; padding: 12px 0 0 0; } #content .entry-summary p:last-child { margin-bottom: 12px; } .entry-content fieldset { border: 1px solid #e7e7e7; margin: 0 0 24px 0; padding: 24px; } .entry-content fieldset legend { background: #fff; color: #000; font-weight: bold; padding: 0 24px; } .entry-content input { margin: 0 0 24px 0; } .entry-content input.file, .entry-content input.button { margin-right: 24px; } .entry-content label { color: #888; font-size: 12px; } .entry-content select { margin: 0 0 24px 0; } .entry-content sup, .entry-content sub { font-size: 10px; } .entry-content blockquote.left { float: left; margin-left: 0; margin-right: 24px; text-align: right; width: 33%; } .entry-content blockquote.right { float: right; margin-left: 24px; margin-right: 0; text-align: left; width: 33%; } .page-link { clear: both; color: #000; font-weight: bold; margin: 0 0 22px 0; word-spacing: 0.5em; } .page-link a:link, .page-link a:visited { background: #f1f1f1; color: #333; font-weight: normal; padding: 0.5em 0.75em; text-decoration: none; } .home .sticky .page-link a { background: #d9e8f7; } .page-link a:active, .page-link a:hover { color: #ff4b33; } body.page .edit-link { clear: both; display: block; } #entry-author-info { background: #f2f7fc; border-top: 4px solid #000; clear: both; font-size: 14px; line-height: 20px; margin: 24px 0; overflow: hidden; padding: 18px 20px; } #entry-author-info #author-avatar { background: #fff; border: 1px solid #e7e7e7; float: left; height: 60px; margin: 0 -104px 0 0; padding: 11px; } #entry-author-info #author-description { float: left; margin: 0 0 0 104px; } #entry-author-info h2 { color: #000; font-size: 100%; font-weight: bold; margin-bottom: 0; } .entry-utility { clear: both; color: #888; font-size: 12px; line-height: 18px; } .entry-meta a, .entry-utility a { color: #888; } .entry-meta a:hover, .entry-utility a:hover { color: #ff4b33; } #content .video-player { padding: 0; } /* =Asides ————————————————————– */ .home #content .format-aside p, .home #content .category-asides p { font-size: 14px; line-height: 20px; margin-bottom: 10px; margin-top: 0; } .home .hentry.format-aside, .home .hentry.category-asides { padding: 0; } .home #content .format-aside .entry-content, .home #content .category-asides .entry-content { padding-top: 0; } /* =Gallery listing ————————————————————– */ .format-gallery .size-thumbnail img, .category-gallery .size-thumbnail img { border: 10px solid #f1f1f1; margin-bottom: 0; } .format-gallery .gallery-thumb, .category-gallery .gallery-thumb { float: left; margin-right: 20px; margin-top: -4px; } .home #content .format-gallery .entry-utility, .home #content .category-gallery .entry-utility { padding-top: 4px; } /* =Attachment pages ————————————————————– */ .attachment .entry-content .entry-caption { font-size: 140%; margin-top: 24px; } .attachment .entry-content .nav-previous a:before { content: ‘\21900a0’; } .attachment .entry-content .nav-next a:after { content: ‘0a0\2192’; } /* =Images ————————————————————– */ /* Resize images to fit the main content area. – Applies only to images uploaded via WordPress by targeting size-* classes. – Other images will be left alone. Use “size-auto” class to apply to other images. */ img.size-auto, img.size-full, img.size-large, img.size-medium, .attachment img { max-width: 100%; /* When images are too wide for containing element, force them to fit. */ height: auto; /* Override height to match resized width for correct aspect ratio. */ } .alignleft, img.alignleft { display: inline; float: left; margin-right: 24px; margin-top: 4px; } .alignright, img.alignright { display: inline; float: right; margin-left: 24px; margin-top: 4px; } .aligncenter, img.aligncenter { clear: both; display: block; margin-left: auto; margin-right: auto; } img.alignleft, img.alignright, img.aligncenter { margin-bottom: 12px; } .wp-caption { background: #f1f1f1; line-height: 18px; margin-bottom: 20px; max-width: 632px !important; /* prevent too-wide images from breaking layout */ padding: 4px; text-align: center; border:1px solid #ccc; -moz-border-radius: 10px; -webkit-border-radius: 10px; border-radius: 10px; } .wp-caption img { margin: 5px 5px 0; } .wp-caption p.wp-caption-text { color: #888; font-size: 12px; margin: 5px; } .wp-smiley { margin: 0; } .gallery { margin: 0 auto 18px; } .gallery .gallery-item { float: left; margin-top: 0; text-align: center; width: 33%; } .gallery-columns-2 .gallery-item { width: 50%; } .gallery-columns-4 .gallery-item { width: 25%; } .gallery img { border: 2px solid #cfcfcf; } .gallery-columns-2 .attachment-medium { max-width: 92%; height: auto; } .gallery-columns-4 .attachment-thumbnail { max-width: 84%; height: auto; } .gallery .gallery-caption { color: #888; font-size: 12px; margin: 0 0 12px; } .gallery dl { margin: 0; } .gallery img { border: 10px solid #f1f1f1; } .gallery br+br { display: none; } #content .attachment img {/* single attachment images should be centered */ display: block; margin: 0 auto; } /* =Navigation ————————————————————– */ .navigation { color: #888; font-size: 12px; line-height: 18px; overflow: hidden; } .navigation a:link, .navigation a:visited { color: #888; text-decoration: none; } .navigation a:active, .navigation a:hover { color: #ff4b33; } .nav-previous { float: left; width: 50%; } .nav-next { float: right; text-align: right; width: 50%; } #nav-above { margin: 0 0 18px 0; } #nav-above { display: none; } .paged #nav-above, .single #nav-above { display: block; } #nav-below { margin: -18px 0 0 0; } /* =Comments ————————————————————– */ #comments { clear: both; font-size: 1.25em; } #comments .navigation { padding: 0 0 18px 0; } h3#comments-title, h3#reply-title { color: #000; font-size: 20px; margin-bottom: 0; } h3#comments-title { padding: 24px 0; } .commentlist { list-style: none; margin: 0; } .commentlist li.comment { border-bottom: 1px solid #e7e7e7; line-height: 24px; margin: 0 0 24px 0; padding: 0 0 0 56px; position: relative; } .commentlist li:last-child { border-bottom: none; margin-bottom: 0; } #comments .comment-body ul, #comments .comment-body ol { margin-bottom: 18px; } #comments .comment-body p:last-child { margin-bottom: 6px; } #comments .comment-body blockquote p:last-child { margin-bottom: 24px; } .commentlist ol { list-style: decimal; } .commentlist .avatar { position: absolute; top: 4px; left: 0; } .comment-author { } .comment-author cite { color: #000; font-style: normal; font-weight: bold; } .comment-author .says { font-style: italic; } .comment-meta { font-size: 12px; margin: 0 0 18px 0; } .comment-meta a:link, .comment-meta a:visited { color: #888; text-decoration: none; } .comment-meta a:active, .comment-meta a:hover { color: #ff4b33; } .commentlist .even { } .commentlist .bypostauthor { } .reply { font-size: 12px; padding: 0 0 24px 0; } .reply a, a.comment-edit-link { color: #888; } .reply a:hover, a.comment-edit-link:hover { color: #ff4b33; } .commentlist .children { list-style: none; margin: 0; } .commentlist .children li { border: none; margin: 0; } .nopassword, .nocomments { display: none; } #comments .pingback { border-bottom: 1px solid #e7e7e7; margin-bottom: 18px; padding-bottom: 18px; } .commentlist li.comment+li.pingback { margin-top: -6px; } #comments .pingback p { color: #888; display: block; font-size: 12px; line-height: 18px; margin: 0; } #comments .pingback .url { font-size: 13px; font-style: italic; } /* Comments form */ input[type=submit] { color: #333; } #respond { border-top: 1px solid #e7e7e7; margin: 24px 0; overflow: hidden; position: relative; } #respond p { margin: 0; } #respond .comment-notes { margin-bottom: 1em; } .form-allowed-tags { line-height: 1em; } .children #respond { margin: 0 48px 0 0; } h3#reply-title { margin: 18px 0; } #comments-list #respond { margin: 0 0 18px 0; } #comments-list ul #respond { margin: 0; } #cancel-comment-reply-link { font-size: 12px; font-weight: normal; line-height: 18px; } #respond .required { color: #ff4b33; font-weight: bold; } #respond label { color: #888; font-size: 12px; } #respond input { margin: 0 0 9px; width: 98%; } #respond textarea { width: 98%; } #respond .form-allowed-tags { color: #888; font-size: 12px; line-height: 18px; } #respond .form-allowed-tags code { font-size: 11px; } #respond .form-submit { margin: 12px 0; } #respond .form-submit input { font-size: 14px; width: auto; padding:5px 10px; -moz-border-radius:5px; -webkit-border-radius:5px; border-radius: 5px; border:1px solid #bbb; } /* =Widget Areas ————————————————————– */ .widget-area { padding-top: 20px; padding-left: 20px; background-color: #eee; } .widget-area ul { list-style: none; margin-left: 0; } .widget-area ul ul { list-style: square; margin-left: 1.3em; } .widget-area select { max-width: 100%; } .widget_search #s {/* This keeps the search inputs in line */ width: 133px; } .widget_search label { display: none; } .widget-container { margin: 0 0 18px 0; } .widget-title { color: #009BC1; font-weight: 100; font-size: 17px; line-height: 20px; margin-bottom: 5px; } .widget-area a:link, .widget-area a:visited { text-decoration: none; color: #333; } .widget-area a:active, .widget-area a:hover { text-decoration: underline; } .widget-area .entry-meta { font-size: 11px; } #wp_tag_cloud div { line-height: 1.6em; } #wp-calendar { width: 100%; } #wp-calendar caption { color: #222; font-size: 14px; font-weight: bold; padding-bottom: 4px; text-align: left; } #wp-calendar thead { font-size: 11px; } #wp-calendar thead th { } #wp-calendar tbody { color: #aaa; } #wp-calendar tbody td { background: #f5f5f5; border: 1px solid #fff; padding: 3px 0 2px; text-align: center; } #wp-calendar tbody .pad { background: none; } #wp-calendar tfoot #next { text-align: right; } .widget_rss a.rsswidget { color: #000; } .widget_rss a.rsswidget:hover { color: #ff4b33; } .widget_rss .widget-title img { width: 11px; height: 11px; } /* Main sidebars */ #main .widget-area ul { margin-left: 0; padding: 0 20px 0 0; font-family: Verdana, Arial, Helvetica, sans-serif; } #main .widget-area ul ul { border: none; padding: 0; font-size: 0.95em; list-style:none; } #primary { } #secondary { } /* Footer widget areas */ #footer-widget-area { } /* =Footer ————————————————————– */ #footer { margin-bottom: 20px; } #colophon { border-top: 4px solid #000; margin-top: -4px; overflow: hidden; padding: 18px 0; } #site-info { font-weight: bold; } #site-info a { color: #000; text-decoration: none; } #site-generator { font-style: italic; position: relative; } #site-generator a { background: url(images/wordpress.png) center left no-repeat; color: #666; display: inline-block; line-height: 16px; padding-left: 20px; text-decoration: none; } #site-generator a:hover { text-decoration: underline; } img#wpstats { display: block; margin: 0 auto 10px; } /* =Mobile Safari ( iPad, iPhone and iPod Touch ) ————————————————————– */ pre { -webkit-text-size-adjust: 140%; } code { -webkit-text-size-adjust: 160%; } #access, .entry-meta, .entry-utility, .navigation, .widget-area { -webkit-text-size-adjust: 120%; } #site-description { -webkit-text-size-adjust: none; } /* =Print Style ————————————————————– */ @media print { body { background: none !important; } #wrapper { clear: both !important; display: block !important; float: none !important; position: relative !important; } #header { border-bottom: 2pt solid #000; padding-bottom: 18pt; } #colophon { border-top: 2pt solid #000; } #site-title, #site-description { float: none; line-height: 1.4em; margin: 0; padding: 0; } #site-title { font-size: 13pt; } .entry-content { font-size: 14pt; line-height: 1.6em; } .entry-title { font-size: 21pt; } #access, #branding img, #respond, .comment-edit-link, .edit-link, .navigation, .page-link, .widget-area { display: none !important; } #container, #header, #footer { margin: 0; width: 100%; } #content, .one-column #content { margin: 24pt 0 0; width: 100%; } .wp-caption p { font-size: 11pt; } #site-info, #site-generator { float: none; width: auto; } #colophon { width: auto; } img#wpstats { display: none; } #site-generator a { margin: 0; padding: 0; } #entry-author-info { border: 1px solid #e7e7e7; } #main { display: inline; } .home .sticky { border: none; } } #searchform input { border:1px solid #ccc; }

How to Check if a Date is More or Less Than a Month Ago with PHP

Let’s say we have the following problem: we have to check
whether a date is more than a month ago or less than a month ago. Many
developers go in the wrong direction by calculating the current month
and then subtracting the number of months from it. Of course, this
approach is slow and full of risks of allowing bugs. Since, two months
before January, which is the first month of the year, is actually
November, which is the eleventh month. Because of these pitfalls, this
approach is entirely wrong.

strtotime() is a lot more powerful than you think!

strtotime() is a lot more powerful than you think!

The question is whether PHP cannot help us with built-in functions to
perform these calculations for us. It is obvious, that from version
5.3.0 and later, there is an OOP section, which is great, but
unfortunately this version is still not updated everywhere. So, how to
accomplish the task?

The Wrong Approach

As I said, there are many ways to go in the wrong direction. One of
them is to subtract 30 days from current date. This is completely wrong,
because not every month has 30 days. Here, some developers will begin
to predefine arrays to indicate the number of days in each month, which
then will be used in their complicated calculations. Here is an example
of this wrong approach.

echo date('Y-m-d', strtotime(date('Y-m-d')) - 60*60*24*30);

This line is full of mistakes. First of all strtotime(date(‘Y-m-d’)) can be replaced by the more elegant strtotime(‘now’), but for this later. Another big mistake is that 60*60*24*30, which is number of seconds in 30 days can be predefined as a constant. Eventually the result is wrong, because not every month has 30 days.

The Correct Approach

A small research of the problem and the functions in versions prior
of 5.3.0 of PHP is needed. Typical case study of date formatting happen
when working with dates from a database. The following code is a
classical example.

// 2008 05 23, 2008-05-23 is stored into the DB
echo date('Y m d', strtotime('2008-05-23'));
 
// 2008 May 23
echo date('Y F d', strtotime('2008-05-23'));

The problem, perhaps, is that too often strtotime() is used like this, with exactly this type of strings. However much more interesting is that strtotime() can do much more.

strtotime() Can Do Much More

Let us first look at the documentation of this function. What parameters it accepts?

int strtotime ( string $time [, int $now = time() ] )

The function expects to be given a string containing an
English date format and will try to parse that format into a Unix
timestamp (the number of seconds since January 1 1970 00:00:00 UTC),
relative to the timestamp given in now, or the current time if now is
not supplied.

In particular we are interested in the first parameter, time.

time – A date/time string. Valid formats are explained in Date and Time Formats.

It is especially important to note what are the valid Date and Time Formats.
Here are the supported formats, but most interesting are those that are Relative.
Exactly these formats are very convenient in our case, because they
give us the ability to work with human readable strings, and here are
some examples from the documentation of strtotime().

echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";

Thus, a valid string would be “1 month ago”.

// if current date is 2011-11-04, this will return 2011-10-04
echo date('Y-m-d', strtotime('1 month ago'))

Or “-1 month”:

// the same as the example above
echo date('Y-m-d', strtotime('-1 month'));

It’s interesting that “+1 -1 month” is also a valid string.

// 2011-10-04, if today's 2011-11-04
echo date('Y-m-d', strtotime('+1 -1 month'));

In fact strtotime() can do a lot more than most of the developers
have ever imagined. Maybe its frequent use with string formatted dates
(2010-01-13) makes it a bit unknown. Here are some interesting use
cases.

// 1970-01-01, Calculations in braces are bad!
echo date('Y-m-d', strtotime('(60*60) minute'));
 
// 2 months into the future
echo date('Y-m-d', strtotime('-2 months ago'));

For instance, do you know how to get the date of the day before
yesterday? Yes 2 days before today, but here’s yet another solution.

// 1 day before yesterday
echo date('Y-m-d', strtotime('yesterday -1 day'));

Another example is the fully human readable:

// get the first monday of the current month
echo date('Y-m-d', strtotime('first monday this month'));

The Solution of the Task

Finally, what is the solution of the original task? Well, just have to check whether a date is more or less than a month ago.

// a random date
$my_date = '2011-09-23';
 
// true if my_date is more than a month ago
(strtotime($my_date) < strtotime('1 month ago'))

PHP Number and strings validations

1. to check a valid phone number for Pakistan e.g 03001234567

    $number_pattern=”/^3[0-9]{9}$/”;
    $phoneNumber=03465315155
    $numberFormat = preg_match($Msisdn_pattern , $phoneNumber);

2. Format a number for proper usage

    $phoneNumber=03465315155;
    $phoneNumber=’0092′.substr($_REQUEST[“M”],-10);

   

%d bloggers like this: