Wednesday, December 12, 2012

Simple Jquery Ajax and getjson call

get some Json Data through a remote API
type: "GET",
url: '',
data: { method: "get", name: "jab", format: "json" },
async: false,
dataType: "json",
beforeSend: function(x) {alert('Not Yet Sent')},
success: function(data){
alert ("AjAx Call"" "+data.responseBody.views); //further debug
$('#showdata').html("<p>item1="" item2="+data.responseBody.views+" </p>");

{method: "get", name: "jab", format: "json" },
function(data) {
//alert("JSON Data: " + json.users[3].name);
alert ("JSON Call"" "+data.responseBody.views); //further debug
$('#showdata').html("<p>item1="" item2="+data.responseBody.views+" </p>");

Tuesday, November 27, 2012

Compare two files using linux comm command

Comm Command: (to use this command file must b first sorted like cat file|sort > file1)
for Common : comm -1 -2 file1 file2
-1 Ignore File1
-2 Ignore File1
-3 Ignore common data


comm -1 -2 file1 file2 => 3,4,5

comm -1 -3 file1 file2 => 6,7

Friday, November 2, 2012

pregmatch for shell script

*     matches any string of zero or more characters
?     matches any single character
[ ]   matches any single character within the set
[! ]  matches any single character not in the set

These can be combined together to form more advanced patterns:
[Yy]* Matches any string starting with an upper or lower case y.

Use quotes or escape/back-slash the special characters if you wish to pattern match them specifically.

Monday, October 22, 2012

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';

Thursday, October 4, 2012

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("");
// $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

Friday, September 7, 2012

Simple XML parsing

Xml File

" $xml = new SimpleXMLElement($xml);
$items = $xml->xpath('/methodResponse/fault/value/struct/member/name');
                $firstArr=$this->objectsIntoArray($items[0]);//convert XML Object to Php Array

function objectsIntoArray($arrObjData, $arrSkipIndices = array())
$arrData = array();
// if input is object, convert into array
if (is_object($arrObjData)) {
$arrObjData = get_object_vars($arrObjData);

if (is_array($arrObjData)) {
foreach ($arrObjData as $index => $value) {
if (is_object($value) || is_array($value)) {
$value = objectsIntoArray($value, $arrSkipIndices); // recursive call
if (in_array($index, $arrSkipIndices)) {
$arrData[$index] = $value;
return $arrData;


Monday, July 9, 2012

Auto highlight text inside pre tags using jQuery

We use pre tags to display the embed codes and short URLs. We use pre tags because it formats the text inside the tags as we insert it, which is ideal for displaying code in particular. The thing is, people like to copy this code and they have to go to the awful bother of selecting all the text manually if they wish to copy the code or URL.

jQuery hack to auto select all the text inside the pre tags. The only complication with this appears to be a cross platform solution as each browser appears to have their own way of selecting text.

Internet Explorer uses createTextRange.
Opera and Firefox use createRange.
Safari uses DOMSelection.
So with a pre tag like (just click anywhere in the code)…

jQuery( document ).ready(function() {	
	jQuery( 'pre.code' ).click( function() {
		var refNode = $( this )[0];
		if ( $.browser.msie ) {
			var range = document.body.createTextRange();
			range.moveToElementText( refNode );;
		} else if ( $.browser.mozilla || $.browser.opera ) {
			var selection = window.getSelection();
			var range = document.createRange();
			range.selectNodeContents( refNode );
			selection.addRange( range );
		} else if ( $.browser.safari ) {
			var selection = window.getSelection();
			selection.setBaseAndExtent( refNode, 0, refNode, 1 );
	} );
 	} );

here goes the code :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="" type="text/javascript"></script>
jQuery( document ).ready(function() { jQuery( 'pre.code' ).click( function() {
var refNode = $( this )[0];
if ( $.browser.msie ) {
var range = document.body.createTextRange();
range.moveToElementText( refNode );;
} else if ( $.browser.mozilla || $.browser.opera ) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents( refNode );
selection.addRange( range );
} else if ( $.browser.safari ) {
var selection = window.getSelection();
selection.setBaseAndExtent( refNode, 0, refNode, 1 );
} );
  } );
<pre class='code'>jQuery( document ).ready(function() { jQuery( 'pre.code' ).click( function() {
var refNode = $( this )[0];
if ( $.browser.msie ) {
var range = document.body.createTextRange();
range.moveToElementText( refNode );;
} else if ( $.browser.mozilla || $.browser.opera ) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents( refNode );
selection.addRange( range );
} else if ( $.browser.safari ) {
var selection = window.getSelection();
selection.setBaseAndExtent( refNode, 0, refNode, 1 );
} );
  } );

Wednesday, July 4, 2012

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');
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.

Wednesday, June 27, 2012

how to get the return code of a command

how to get the return code of a command??

you can get the retun code of a command using $? operator.Make sure to save the returncode in a variable just after the command completed.otherwise this will hold the code of the next command executed after your desired.
have a look
ncftpput -u user-name -p P@sswORD / $filename
echo $RET

Thursday, June 21, 2012

Linux BASH - Comparison Operators

Linux BASH - Comparison Operators

 Integer Comparison Operators
-eqIs Equal Toif [ $1 -eq 200 ]
-neIs Not Equal Toif [ $1 -ne 1 ]
-gtIs Greater Thanif [ $1 -gt 15 ]
-geIs Greater Than Or Equal Toif [ $1 -ge 10 ]
-ltIs Less Thanif [ $1 -lt 5 ]
-leIs Less Than Or Equal Toif [ $1 -le 0 ]
==Is Equal Toif (( $1 == $2 )) [Note: Used within double parentheses]
!=Is Not Equal Toif (( $1 != $2 ))
<Is Less Thanif (( $1 < $2 ))
<=Is Less Than Or Equal Toif (( $1 <= $2 ))
>Is Greater Thanif (( $1 > $2 ))
>=Is Greater Than Or Equal Toif (( $1 >= $2 ))

 String Comparison Operators
= or ==Is Equal Toif [ "$1" == "$2" ]
!=Is Not Equal Toif [ "$1" != "$2" ]
>Is Greater Than (ASCII comparison)if [ "$1" > "$2" ]
>=Is Greater Than Or Equal Toif [ "$1" >= "$2" ]
<Is Less Thanif [ "$1" < "$2" ]
<=Is Less Than Or Equal Toif [ "$1" <= "$2" ]
-nIs Not Nullif [ -n "$1" ]
-zIs Null (Zero Length String)if [ -z "$1"]

Thursday, June 14, 2012

Shell Script for updating an Oracle table through a file (from a remote Server)

a simple Script for updating an Oracle table through a file (from a remote Server)
we will b using a shell script for all this
process is described step by step as
1. first Of all create a virtual directory and external table use this page
2. get file from remote server using ncftpget
3. create Oracle Procedure for data insertions
4. Oracle Procedure uses  UTL_FILE utility for logging different file events like success and failure

Serrver : server IP like
directory Object Name : DIR_3352
directory Object Path : /home/xyz/3352
External File : xtern_3352.txt
Upload File Name Format : add_20120612.csv
Upload File Format : 03007236317,09-MAR-12,C2676M0749
External Table :
create table xtern_3352 ( mobile varchar2(100),dateCol varchar2(20),id varchar2(20))
organization external (
type oracle_loader
default directory DIR_3352
access parameters (
records delimited by newline
location ('xtern_3352.txt')
reject limit unlimited;

Shell Script :
##                                              USAGE                                                                         ##
##      call it as action-parameter                                                                          ##
##      eg. source add                                                                                          ##
##      current action parameters are                                                                                  ##
##      1.add                                                                                                                     ##
##      2.delete                                                                                                                  ##
date_var=`date -d "-$day days" +%Y-%m-%d`
#backup old files
mv -f /home/xyz/3352/xtern_3352.txt /home/xyz/3352/xtern_3352_`echo $date_var`.txt
#get the file from remote Server and put in /path/to/local/dir/ directory
ncftpget -u ftp-user-name -p paSSword rem.ote.Ser.ver.IP /path/to/local/dir/ /file`echo $date_var`_sub.csv
mv -f  /home/xyz/file`echo $date_var`_sub.csv  /home/xyz/new.txt
cat /home/xyz/new.txt | cut -d ' ' -f1> /home/xyz/xtern_3352.txt
source / 3352/xtern_3352.txt
/Oracle/app/oracle/product/11.2.0/dbhome_1/bin/sqlplus /NOLOG << EOF

connect db_user/db_pwd
set serveroutput on
exec TEST_PARAMETER('`echo $action`');
echo "Now making file"

Oracle Procedure : TEST_PARAMETER

 ( action IN varchar2 )
  AS CURSOR C_CONTENT IS SELECT * from xtern_3352 ;
-- --
-- Initialization --
datecheck number;
v_message varchar2(100);
ERROR_mobile_FORMAT exception;
ERROR_mobile_VALUE exception;
ERROR_DUPLICATE_mobile exception;
ERROR_NO_mobile_FOUND  exception;
cur_date varchar2(100);
file_Name varchar2(100);
success_File_Name varchar2(100);
var_query varchar2(100);
-- --
--                        Start of Logic -- --                                                                   --

    --                       File details               --
  SELECT  to_char(sysdate, 'DDMonYYYY_HH24MISS') into cur_date from dual;
  file_Name := '' ;
  success_File_Name := '' ;
  if ( action = 'add') then
    dbms_output.put_line('add Action');
    file_Name := 'add_error_'||cur_date||'.txt' ;
    success_File_Name := 'add_success_'||cur_date||'.txt' ;
    --var_query := 'insert into WHITE_LIST_auto values('||||','||wl_DATA.dateCol||','||wl_DATA.ID||')' ;
    var_query := 'insert into WHITE_LIST_auto values(,wl_DATA.dateCol,wl_DATA.ID)' ;
  else if ( action = 'delete') then
    dbms_output.put_line('delete Action');
    file_Name := 'delete_error_'||cur_date||'.txt' ;
    success_File_Name := 'delete_success_'||cur_date||'.txt' ;
    var_query := 'delete from WHITE_LIST_auto where' ;
    dbms_output.put_line('What do u want to do ??? Please Select an action (add or delete)');
    dbms_output.put_line('else Action');
    --return 'Please Select an action (add or delete)';
  end if;
  end if;

  SELECT  to_char(sysdate, 'DDMonYYYY_HH24MISS') into cur_date from dual;
  --file_Name := 'error_'||cur_date||'.txt' ;
  dbms_output.put_line('error is '|| file_Name);
  v_file := UTL_FILE.FOPEN(location     => 'dir_3352',
                           filename     => file_Name,
                           open_mode    => 'w',
                           max_linesize => 32767);
  --success_File_Name := 'success_'||cur_date||'.txt' ;
  dbms_output.put_line('success_File_Name is '|| success_File_Name);
  s_file := UTL_FILE.FOPEN(location     => 'dir_3352',
                           filename     => success_File_Name,
                           open_mode    => 'w',
                           max_linesize => 32767);

    -- Error Validations      --
      if length( <> 11 or substr(,0,2) <> '03' then
raise ERROR_mobile_FORMAT;
      else if  ( (LENGTH(TRIM(TRANSLATE(, '+0123456789',' '))) is not null)  ) then
raise ERROR_mobile_VALUE;
      else if (is_date(wl_DATA.dateCol, 'dd-mon-yy') = 0) then
      else if (CHECK_WHITELIST( = 1 and action = 'add') then
raise ERROR_DUPLICATE_mobile;
      else if (CHECK_WHITELIST( = 0 and action = 'delete') then
raise ERROR_NO_mobile_FOUND;
 -- Dumping Valid Data      --
 if ( action = 'add') then
   insert into WHITE_LIST_auto values(,wl_DATA.dateCol,wl_DATA.ID);
 else if ( action = 'delete') then
   delete from WHITE_LIST_auto where;
   dbms_output.put_line('else Action');
   --return 'Please Select an action (add or delete)';
   end if;
   end if;
--execute immediate var_query ;
--insert into WHITE_LIST_auto values(,wl_DATA.dateCol,wl_DATA.ID);
UTL_FILE.PUT_LINE(s_file,|| ',' ||wl_DATA.dateCol|| ',' ||wl_DATA.ID);
      end if;
      end if;
      end if;
      end if;
      end if;
 -- Exception Handling      --
        when ERROR_mobile_FORMAT then
          v_message:='Mobile number Format is invalid';
 UTL_FILE.PUT_LINE(v_file,|| ',' ||wl_DATA.dateCol|| ',' ||wl_DATA.ID|| ',' ||v_message);
        when ERROR_mobile_VALUE then
          v_message:='Mobile number is invalid';
 UTL_FILE.PUT_LINE(v_file,|| ',' ||wl_DATA.dateCol|| ',' ||wl_DATA.ID|| ',' ||v_message);
          v_message:='date is invalid';
 UTL_FILE.PUT_LINE(v_file,|| ',' ||wl_DATA.dateCol|| ',' ||wl_DATA.ID|| ',' ||v_message);
        when ERROR_DUPLICATE_mobile then
          v_message:='Duplictae mobile';
 UTL_FILE.PUT_LINE(v_file,|| ',' ||wl_DATA.dateCol|| ',' ||wl_DATA.ID|| ',' ||v_message);
        when ERROR_NO_mobile_FOUND then
          v_message:='No mobile Found';
 UTL_FILE.PUT_LINE(v_file,|| ',' ||wl_DATA.dateCol|| ',' ||wl_DATA.ID|| ',' ||v_message);

-- --
-- End of Logic --
-- =============================================================

Monday, June 11, 2012

oracle procedure : number validation

if ( (LENGTH(TRIM(TRANSLATE(contentcode, ‘+0123456789′,’ ‘))) is not null) or (LENGTH(TRIM(TRANSLATE(otherfield, ‘+0123456789′,’ ‘))) is not null)) then
dbms_output.put_line(‘contentcode or otherfield is invalid’); 

Tuesday, May 29, 2012

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 precise main 
deb-src 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://[IP_ADDRESS]/). 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://[IP_ADDRESS]/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)

linux file permission simplest rule of thumb

Chmod 777 –R /var/www/html/webdir
Permission level
1.       r (read)       =  4
2.       w (write)     =  2
3.       x (execute)  =  1

For example : 
chmod 753 abc.txt thus means
assign (4+2+1)(4+1)(2+1) to abc.txt

assign (rwx)(rx)(wx) to abc.txt
assign (owner)(group)(other) to abc.txt
Another example

chmod 572 dump.txt thus means
assign (4+1)(4+2+1)(2) to 
dump .txt
assign (rw)(rwx)(w) to  dump .txt

Monday, May 28, 2012

Sending Email With Attachments From Unix / Linux Command

If you need to send an email with a text file (or binary file) as attachment using shell script or command prompt in Unix or Linux; try mutt - a terminal-based e-mail client for Unix-like systems.

mutt -s "Test mail" -a /tmp/shahzeb.tar.gz < /tmp/mailmessage.txt

  •   - is the recipient.
  • /tmp/mailmessage.txt - is the main body of the e-mail (read message from the file "mailmessage.txt").
  • -a /tmp/shahzeb.tar.gz - is an attachment.
  • -s "Test mail" - is a subject line of email Message.

If MUTT is not available???

If mutt is not installed, use the apt-get or yum or up2date commands as follows (you must login as a root user). Debian / Ubuntu Linux user type the following command to install mutt client:
# apt-get install mutt
# yum install mutt 

Some useful resources 

Tuesday, May 22, 2012

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

Friday, May 4, 2012


some helpful URLs for a starter to install and configure nginx with php and phpmyadmin on ubuntu

detailed step by step process can be found at

Thursday, April 26, 2012

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)
# 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
# cd /usr/share
# wget
# tar xvfz phpMyAdmin-
# mv phpMyAdmin- phpmyadmin
# rm phpMyAdmin-
# cd phpmyadmin
# cp
8. Edit the 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://[IP Address]/phpMyAdmin/ on Firefox browser, we’ll can see the login web page.
After inputting the root user and its password(eaziweb), we can use phpMyAdmin to manage the MySQL.
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.

Tuesday, April 24, 2012

Google Map V3 - Get Langitude and Latitude on mouseover

  • First an object representing google map properties is created with zoom level, map center and map type.
  • Then a map object is created. It takes two parameters. One is the div where the map should be displayed and the other is the object which contains various properties to initialize the google map.
  • With the above to lies the map can be displayed.
  • Next are the two event handlers which will display the lattitude and longitude when the move is moved over the google map or when the mouse is clicked on the map.
  • The event listener needs three parameters first is the map object, next is the event like onmousemove or onclick and the third parameter is the callback function to which the coordinates are passed as a parameter.
  • Each time the event handlers (callback functions) are called i am updating the lattitude and longitude.

Friday, April 20, 2012

Get Latitude and Longitude with Google Maps V3

I would like to share with you a little piece of code that I find quite useful in my applications. I do create lots of guides that require a small utility to find out the latitude and longitude of a business location from a control panel in order to display the maps appropiately on the Web. Here I will do my best to explain a step procedure on how to do that -once you know the procedure, it is easy to create plugins or whatever you wish to do.

Step 1

 First of all, lets make a reference to the new version of Google Maps. Check that we have to specify a parameter sensor=false. To find out more about this parameter please follow this link.

<script type="text/javascript" src="">script>

Step 2

Now we are going to write the HTML tags on the BODY of our document that will hold the map and the controls that will hold latitude, longitude and zoom level references. Also, see the CSS that control the size of the map holder.

div#gmap {
width: 100%;
height: 300px;
<div id="gmap">div>
lat:<span id="lat">span> lon:<span id="lon">span><br/>
zoom level: <span id="zoom_level">span>

Step 3

Now, we are going to write the function that will display the map when the document loads. The function, that we will call ‘initialize’ has different parts that we will describe now:

Part 1

Setting the map zoom level and its position in the world:

var myLatlng = new google.maps.LatLng(38.971154274048345,1.415863037109375); // IBIZA" alt=":)" class="wp-smiley">
var myOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
map = new google.maps.Map(document.getElementById("gmap"), myOptions);

Part 2

Placing a marker on the map specifying its center position (please refer to above code for LatLon location).

// marker refers to a global variable
marker = new google.maps.Marker({
position: myLatlng,
map: map

Part 3

Now, the events that will take control of the marker center re-positioning and placing the information on the correspondent document objects (lat, lon, and zoom level).
// if center changed then update lat and lon document objects                          
google.maps.event.addListener(map, 'center_changed', function() {                      
var location = map.getCenter();                                                        
document.getElementById("lat").innerHTML =;                             
document.getElementById("lon").innerHTML = location.lng();                             
// call function to reposition marker location                                         
// if zoom changed, then update document object with new info                          
google.maps.event.addListener(map, 'zoom_changed', function() {                        
zoomLevel = map.getZoom();                                                             
document.getElementById("zoom_level").innerHTML = zoomLevel;                           
// double click on the marker changes zoom level                                       
google.maps.event.addListener(marker, 'dblclick', function() {                         
zoomLevel = map.getZoom()+1;                                                           
if (zoomLevel == 20) {                                                                 
zoomLevel = 10;                                                                        
document.getElementById("zoom_level").innerHTML = zoomLevel;                           

Part 4

Initialize the document objects with default information
document.getElementById("zoom_level").innerHTML = 16;
document.getElementById("lat").innerHTML = 38.971154274048345;
document.getElementById("lon").innerHTML = 1.415863037109375;

Step 4

Finally, we have to write the function that will reposition the marker on ‘zoom_changed’ map event and call the ‘initialize’ function on window load event.

function placeMarker(location) {
var clickedLocation = new google.maps.LatLng(location);
window.onload = function(){initialize()};
And that’s it, we have a great utility to plug onto our projects in order to find out the latitude and longitude of an address.

Finally! The Live Demo

lat: lon:

zoom level:

All code in single File

<title>Get Lat Lon Finder</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

<style type="text/css">
body {
    margin: 0;
    padding: 0;
    font-family: "Gill sans", sans-serif;
    background-color: #fff;
    color: #000;
div#bd {
    position: relative;
div#gmap {
    width: 100%;
    height: 500px;
<script type="text/javascript" src=""></script>
<script type="text/javascript">
var map;
var marker=false;
function initialize() {
  var myLatlng = new google.maps.LatLng(38.909017951243754,1.4319777488708496);
  var myLatlng = new google.maps.LatLng(34.49648586452719,73.35619300603867); //for my home
  var myOptions = {
    zoom: 19,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  map = new google.maps.Map(document.getElementById("gmap"), myOptions);
  marker = new google.maps.Marker({
          position: myLatlng,
          map: map
  google.maps.event.addListener(map, 'center_changed', function() {
      var location = map.getCenter();
    document.getElementById("lat").innerHTML =;
    document.getElementById("lon").innerHTML = location.lng();
  google.maps.event.addListener(map, 'zoom_changed', function() {
      zoomLevel = map.getZoom();
    document.getElementById("zoom_level").innerHTML = zoomLevel;
  google.maps.event.addListener(marker, 'dblclick', function() {
    zoomLevel = map.getZoom()+1;
    if (zoomLevel == 20) {
     zoomLevel = 10;
    document.getElementById("zoom_level").innerHTML = zoomLevel;
  document.getElementById("zoom_level").innerHTML = 14;
  document.getElementById("lat").innerHTML = 38.909017951243754;
  document.getElementById("lon").innerHTML = 1.4319777488708496;
function placeMarker(location) {
  var clickedLocation = new google.maps.LatLng(location);
window.onload = function(){initialize();};

    <div id="bd">
        <div id="gmap"></div>
        lat:<span id="lat"></span> lon:<span id="lon"></span><br/>
        zoom level: <span id="zoom_level"></span>

Special Thanx to for code conversion