Friday, December 28, 2012

php format date string short month

As you can see in our last example there are tons of different formats that can be used in the date feature. Below is a summary of the variable used in date, and what each does.Remember they ARE CaSe sEnsItIVe:
DAYS 
d - day of the month 2 digits (01-31) 
j - day of the month (1-31) 
D - 3 letter day (Mon - Sun) 
l - full name of day (Monday - Sunday) 
N - 1=Monday, 2=Tuesday, etc (1-7) 
S - suffix for date (st, nd, rd) 
w - 0=Sunday, 1=Monday (0-6) 
z - day of the year (1=365)
WEEK 
W - week of the year (1-52)
MONTH 
F - Full name of month (January - December)
m - 2 digit month number (01-12) 
n - month number (1-12) 
M - 3 letter month (Jan - Dec) 
t - Days in the month (28-31)
YEAR
L - leap year (0 no, 1 yes)
o - ISO-8601 year number (Ex. 1979, 2006)
Y - four digit year (Ex. 1979, 2006)
y - two digit year (Ex. 79, 06)
TIME
a - am or pm
A - AM or PM
B - Swatch Internet time (000 - 999)
g - 12 hour (1-12)
G - 24 hour c (0-23)
h - 2 digit 12 hour (01-12)
H - 2 digit 24 hour (00-23)
i - 2 digit minutes (00-59)
s 0 2 digit seconds (00-59)
OTHER e - timezone (Ex: GMT, CST)
I - daylight savings (1=yes, 0=no)
O - offset GMT (Ex: 0200)
Z - offset in seconds (-43200 - 43200)
r - full RFC 2822 formatted date

Thursday, December 27, 2012

Attempting to understand handling regular expressions with php

Regular Expression, commonly known as RegEx is considered to be one of the most complex concepts. However, this is not really true. Unless you have worked with regular expressions before, when you look at a regular expression containing a sequence of special characters like /, $, ^, \, ?, *, etc., in combination with alphanumeric characters, you might think it a mess. RegEx is a kind of language and if you have learnt its symbols and understood their meaning, you would find it as the most useful tool in hand to solve many complex problems related to text searches.
Just consider how you would make a search for files on your computer. You most likely use the ? and * characters to help find the files you're looking for. The ? character matches a single character in a file name, while the * matches zero or more characters. A pattern such as 'file?.txt' would find the following files:
file1.txt
filer.txt
files.txt

Using the * character instead of the ? character expands the number of files found. 'file*.txt' matches all of the following:
file1.txt
file2.txt
file12.txt
filer.txt
filedce.txt
While this method of searching for files can certainly be useful, it is also very limited. The limited ability of the ? and * wildcard characters give you an idea of what regular expressions can do, but regular expressions are much more powerful and flexible.
Let Us Start on RegEx
A regular expression is a pattern of text that consists of ordinary characters (for example, letters a through z) and special characters, known as metacharacters. The pattern describes one or more strings to match when searching a body of text. The regular expression serves as a template for matching a character pattern to the string being searched.
The following table contains the list of some metacharacters and their behavior in the context of regular expressions:
Character Description
\ Marks the next character as either a special character, a literal, a backreference, or an octal escape. For example, 'n' matches the character "n". '\n' matches a newline character. The sequence '\\' matches "\" and "\(" matches "(".
^ Matches the position at the beginning of the input string.
$ Matches the position at the end of the input string.
* Matches the preceding subexpression zero or more times.
+ Matches the preceding subexpression one or more times.
? Matches the preceding subexpression zero or one time.
{n} Matches exactly n times, where n is a nonnegative integer.
{n,} Matches at least n times, n is a nonnegative integer.
{n,m} Matches at least n and at most m times, where m and n are nonnegative integers and n <= m.
? When this character immediately follows any of the other quantifiers (*, +, ?, {n}, {n,}, {n,m}), the matching pattern is non-greedy. A non-greedy pattern matches as little of the searched string as possible, whereas the default greedy pattern matches as much of the searched string as possible.
. Matches any single character except "\n".
x|y Matches either x or y.
[xyz] A character set. Matches any one of the enclosed characters.
[^xyz] A negative character set. Matches any character not enclosed.
[a-z] A range of characters. Matches any character in the specified range.
[^a-z] A negative range characters. Matches any character not in the specified range.
\b Matches a word boundary, that is, the position between a word and a space.
\B Matches a nonword boundary. 'er\B' matches the 'er' in "verb" but not the 'er' in "never".
\d Matches a digit character.
\D Matches a nondigit character.
\f Matches a form-feed character.
\n Matches a newline character.
\r Matches a carriage return character.
\s Matches any whitespace character including space, tab, form-feed, etc.
\S Matches any non-whitespace character.
\t Matches a tab character.
\v Matches a vertical tab character.
\w Matches any word character including underscore.
\W Matches any nonword character.
\un Matches n, where n is a Unicode character expressed as four hexadecimal digits. For example, \u00A9 matches the copyright symbol (©).

RegEx functions in PHP
PHP has functions to work on complex string manipulation using RegEx.  The following are the RegEx functions provided in PHP.

Function Description
ereg This function matches the text pattern in a string using a RegEx pattern.
eregi This function is similar to ereg(), but ignore the case sensitivity.
ereg_replace This function matches the text pattern in a string using a RegEx Pattern and replaces it with the given text.
eregi_replace This is similar to ereg_replace(), but ignores the case sensitivity.
split This function split string into array using RegEx.
Spliti This is similar to Split(), but ignores the case sensitivity.
sql_regcase This function create a RegEx from the given string to make a case insensitive match.

Finding US Zip Code
Now let us see a simple example to match a US 5 digit zip code from a string
<?
$zip_pattern = "[0-9]{5}";
$str = "Mission Viejo, CA 92692";
ereg($zip_pattern,$str,$regs);
echo $regs[0];
?>
This script would output as follows
92692
The above example can also be rewritten using Perl-compatible regular expression syntax with preg_match() function.
<?
$zip_pattern = "/\d{5}/";
$str = "Mission Viejo, CA 92692";
preg_match($zip_pattern,$str,$regs);
echo $regs[0];
?>
Note the change in the RegEx pattern in both examples. preg_match() is considered as  faster alternative for ereg().
RegEx for US Phone Numbers
Now let us try to create a RegEx pattern to match a US telephone number.  US telephone numbers are 10 digit numbers usually written with three parts like xxx xxx xxxx.  These three parts are normally used with – hyphen, () braces, and blank spaces. The most common patterns can be seen as follows:
XXX XXX XXXX
(XXX) XXX XXXX
XXX-XXX-XXXX
(XXX) XXX-XXXX
In some cases, US ISD code would be added in the first, like +1 XXX XXX XXXX.
Let us create a Perl-Compatible RegEx pattern to match the above patterns. First we would need to match the single digit ISD code (let us not restrict it to 1). But this may or may not available in the phone numbers, hence we would write it as follows:
$Phone_Pattern = “/(\d)?/”;
Here \d is equivalent to 0-9 and the succeeding ‘?’ indicates that the digit may appear one time or doesn’t appear at all.
Now what would appear next in the sequence? The possibilities are a blank space or a hyphen. So we would add the pattern “(\s|-)?” with the above RegEx. This pattern indicates that either a blank space or a hyphen may or may not appear. So our RegEx becomes:
$Phone_Pattern = “/(\d)?(\s|-)?/”;
The next sequence would be either XXX or (XXX). To match this sequence, we need to first match the braces with the pattern “(\()?”. As we use braces to enclose the patterns in RegEx, braces are metacharacters and to match these metacharacters explicitly, we need to use the escape character “\” preceding the metacharacters. Hence we use “\(“ in our RegEx pattern.  Now we need to match the three digits and a closing braces. So this can be written as “(\d){3}(\))?”. Now our RegEx is added with these patterns,
$Phone_Pattern = “/(\d)?(\s|-)?(\()?(\d){3}(\))?/”;
After the first part XXX, there should be either a blank space or a hyphen. So we add “(\s|-){1}” to the phone pattern.
$Phone_Pattern = “/(\d)?(\s|-)?(\()?(\d){3}(\))?(\s|-){1}/”;
Further construction of RegEx would be much more simpler, as we need to match either XXX-XXXX or XXX XXXX. This could be written as “(\d){3}(\s|-){1}(\d){4}”. Adding this part of pattern to our RegEx,
$Phone_Pattern = “/(\d)?(\s|-)?(\()?(\d){3}(\))?(\s|-){1}(\d){3}(\s|-){1}(\d){4}/”;
Yippee!!! We have created a RegEx to match US phone numbers.

Now we need to use this RegEx to perform some task, so that we can understand the significance of RegEx better. Now let us try to script a code to fetch the phone numbers from Google contact us page. So first we need to fetch the html content from Google’s contact us page.
$str = implode("",file("http://www.google.com/intl/en/contact/index.html"));
Then we need to search for the phone number pattern with the help of our “Just Created” RegEx. If we use the preg_match(), we can fetch only one match. So to get more than one match we would use preg_match_all().
preg_match_all($Phone_Pattern,$str,$phone);
Now putting all these pieces into a single script,
<?
$str = implode("",file("http://www.google.com/intl/en/contact/index.html"));
$Phone_Pattern = "/(\d)?(\s|-)?(\()?(\d){3}(\))?(\s|-){1}(\d){3}(\s|-){1}(\d){4}/";
preg_match_all($Phone_Pattern,$str,$phone);
for($i=0;$i<count($phone[0]);$i++)
{
echo $phone[0][$i]."<br>";
}
?>
This script will display the following output,
(650) 253-0000
(650) 253-0001
Wrap Up
Hope you had a good session with RegEx and now you would have some understanding on tackling problems related to text pattern findings using RegEx.  To become a specialist in RegEx, you need to continuously practice it and need to identify complex problems and give a try to solve them. Happy Practicing With RegEx.

Tuesday, December 25, 2012

Regular expression handler quicker learn in php

Regex quick reference
[abc]     A single character: a, b or c
[^abc]     Any single character but a, b, or c
[a-z]     Any single character in the range a-z
[a-zA-Z]     Any single character in the range a-z or A-Z
^     Start of line
$     End of line
\A     Start of string
\z     End of string
.     Any single character
\s     Any whitespace character
\S     Any non-whitespace character
\d     Any digit
\D     Any non-digit
\w     Any word character (letter, number, underscore)
\W     Any non-word character
\b     Any word boundary character
(...)     Capture everything enclosed
(a|b)     a or b
a?     Zero or one of a
a*     Zero or more of a
a+     One or more of a
a{3}     Exactly 3 of a
a{3,}     3 or more of a
a{3,6}     Between 3 and 6 of a







Monday, December 24, 2012

php email reader and notification though header parameters

down vote accepted
For the reading confirmations:
$header.= "X-Confirm-Reading-To: test@test.com\n" ;
 $header.= "Disposition-Notification-To: test@test.com\n";

You have to add the X-Confirm-Reading-To header.
X-Confirm-Reading-To: <address>
For delivery confirmations:
You have to add the Disposition-Notification-To header.

Friday, December 21, 2012

Authorize.net ARB class Automated recurring billing class

<?php

class AuthnetARBException extends Exception {}

class WP_Invoice_AuthnetARB
{
    private $login;
    private $transkey;

    private $params  = array();
    private $sucess  = false;
    private $error   = true;

    var $xml;
    var $response;
    private $resultCode;
    private $code;
    private $text;
    private $subscrId;

    public function __construct()
    {
 
        $this->url = stripslashes(get_option("wp_invoice_recurring_gateway_url"));
        $this->login = stripslashes(get_option("wp_invoice_gateway_username"));
        $this->transkey = stripslashes(get_option("wp_invoice_gateway_tran_key"));

    }

    private function process($retries = 3)
    {
        $count = 0;
        while ($count < $retries)
        {
            $ch = curl_init();
  
   //required for GoDaddy
   if(get_option('wp_invoice_using_godaddy') == 'yes') {
   curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
   curl_setopt ($ch, CURLOPT_PROXY,"http://proxy.shr.secureserver.net:3128");
   curl_setopt ($ch, CURLOPT_TIMEOUT, 120);
   }
   //required for GoDaddy

            curl_setopt($ch, CURLOPT_URL, $this->url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
            curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->xml);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            $this->response = curl_exec($ch);
            $this->parseResults();
            if ($this->resultCode === "Ok")
            {
                $this->success = true;
                $this->error   = false;
                break;
            }
            else
            {
                $this->success = false;
                $this->error   = true;
                break;
            }
            $count++;
        }
        curl_close($ch);
    }

    public function createAccount()
    {
        $this->xml = "<?xml version='1.0' encoding='utf-8'?>
                      <ARBCreateSubscriptionRequest xmlns='AnetApi/xml/v1/schema/AnetApiSchema.xsd'>
                          <merchantAuthentication>
                              <name>" . $this->login . "</name>
                              <transactionKey>" . $this->transkey . "</transactionKey>
                          </merchantAuthentication>
                          <refId>" . $this->params['refID'] ."</refId>
                          <subscription>
                              <name>". $this->params['subscrName'] ."</name>
                              <paymentSchedule>
                                  <interval>
                                      <length>". $this->params['interval_length'] ."</length>
                                      <unit>". $this->params['interval_unit'] ."</unit>
                                  </interval>
                                  <startDate>" . $this->params['startDate'] . "</startDate>
                                  <totalOccurrences>". $this->params['totalOccurrences'] . "</totalOccurrences>
                                  <trialOccurrences>". $this->params['trialOccurrences'] . "</trialOccurrences>
                              </paymentSchedule>
                              <amount>". $this->params['amount'] ."</amount>
                              <trialAmount>" . $this->params['trialAmount'] . "</trialAmount>
                              <payment>
                                  <creditCard>
                                      <cardNumber>" . $this->params['cardNumber'] . "</cardNumber>
                                      <expirationDate>" . $this->params['expirationDate'] . "</expirationDate>
                                  </creditCard>
                              </payment>
                              <order>
                                  <invoiceNumber>" . $this->params['orderInvoiceNumber'] . "</invoiceNumber>
                                  <description>" . $this->params['orderDescription'] . "</description>
                              </order>
                              <customer>
                                  <id>" . $this->params['customerId'] . "</id>
                                  <email>" . $this->params['customerEmail'] . "</email>
                                  <phoneNumber>" . $this->params['customerPhoneNumber'] . "</phoneNumber>
                                  <faxNumber>" . $this->params['customerFaxNumber'] . "</faxNumber>
                              </customer>
                              <billTo>
                                  <firstName>". $this->params['firstName'] . "</firstName>
                                  <lastName>" . $this->params['lastName'] . "</lastName>
                                  <company>" . $this->params['company'] . "</company>
                                  <address>" . $this->params['address'] . "</address>
                                  <city>" . $this->params['city'] . "</city>
                                  <state>" . $this->params['state'] . "</state>
                                  <zip>" . $this->params['zip'] . "</zip>
                              </billTo>
                              <shipTo>
                                  <firstName>". $this->params['shipFirstName'] . "</firstName>
                                  <lastName>" . $this->params['shipLastName'] . "</lastName>
                                  <company>" . $this->params['shipCompany'] . "</company>
                                  <address>" . $this->params['shipAddress'] . "</address>
                                  <city>" . $this->params['shipCity'] . "</city>
                                  <state>" . $this->params['shipState'] . "</state>
                                  <zip>" . $this->params['shipZip'] . "</zip>
                              </shipTo>
                          </subscription>
                      </ARBCreateSubscriptionRequest>";
        $this->process();
    }

    public function updateAccount()
    {
        $this->xml = "<?xml version='1.0' encoding='utf-8'?>
                      <ARBUpdateSubscriptionRequest xmlns='AnetApi/xml/v1/schema/AnetApiSchema.xsd'>
                          <merchantAuthentication>
                              <name>" . $this->url . "</name>
                              <transactionKey>" . $this->transkey . "</transactionKey>
                          </merchantAuthentication>
                          <refId>" . $this->params['refID'] ."</refId>
                          <subscriptionId>" . $this->params['subscrId'] . "</subscriptionId>
                          <subscription>
                              <name>". $this->params['subscrName'] ."</name>
                              <amount>". $this->params['amount'] ."</amount>
                              <trialAmount>" . $this->params['trialAmount'] . "</trialAmount>
                              <payment>
                                  <creditCard>
                                      <cardNumber>" . $this->params['cardNumber'] . "</cardNumber>
                                      <expirationDate>" . $this->params['expirationDate'] . "</expirationDate>
                                  </creditCard>
                              </payment>
                              <billTo>
                                  <firstName>". $this->params['firstName'] . "</firstName>
                                  <lastName>" . $this->params['lastName'] . "</lastName>
                                  <address>" . $this->params['address'] . "</address>
                                  <city>" . $this->params['city'] . "</city>
                                  <state>" . $this->params['state'] . "</state>
                                  <zip>" . $this->params['zip'] . "</zip>
                                  <country>" . $this->params['country'] . "</country>
                              </billTo>
                          </subscription>
                      </ARBUpdateSubscriptionRequest>";
        $this->process();
    }

    public function deleteAccount()
    {
        $this->xml = "<?xml version='1.0' encoding='utf-8'?>
                      <ARBCancelSubscriptionRequest xmlns='AnetApi/xml/v1/schema/AnetApiSchema.xsd'>
                          <merchantAuthentication>
                              <name>" . $this->url . "</name>
                              <transactionKey>" . $this->transkey . "</transactionKey>
                          </merchantAuthentication>
                          <refId>" . $this->params['refID'] ."</refId>
                          <subscriptionId>" . $this->params['subscrId'] . "</subscriptionId>
                      </ARBCancelSubscriptionRequest>";
        $this->process();
    }

    private function parseResults()
    {
        $this->resultCode = $this->parseXML('<resultCode>', '</resultCode>');
        $this->code       = $this->parseXML('<code>', '</code>');
        $this->text       = $this->parseXML('<text>', '</text>');
        $this->subscrId   = $this->parseXML('<subscriptionId>', '</subscriptionId>');
    }

    private function parseXML($start, $end)
    {
        return preg_replace('|^.*?'.$start.'(.*?)'.$end.'.*?$|i', '$1', substr($this->response, 334));
    }

    public function setParameter($field = "", $value = null)
    {
        $field = (is_string($field)) ? trim($field) : $field;
        $value = (is_string($value)) ? trim($value) : $value;
        if (!is_string($field))
        {
            throw new AuthnetARBException("setParameter() arg 1 must be a string or integer: " . gettype($field) . " given.");
        }
        if (!is_string($value) && !is_numeric($value) && !is_bool($value))
        {
            throw new AuthnetARBException("setParameter() arg 2 must be a string, integer, or boolean value: " . gettype($value) . " given.");
        }
        if (empty($field))
        {
            throw new AuthnetARBException("setParameter() requires a parameter field to be named.");
        }
        if ($value === "")
        {
            throw new AuthnetARBException("setParameter() requires a parameter value to be assigned: $field");
        }
        $this->params[$field] = $value;
    }

    public function isSuccessful()
    {
        return $this->success;
    }

    public function isError()
    {
        return $this->error;
    }

    public function getResponse()
    {
        return strip_tags($this->text);
    }

    public function getResponseCode()
    {
        return $this->code;
    }

    public function getSubscriberID()
    {
        return $this->subscrId;
    }
}

?>

Tuesday, December 18, 2012

php image upload class file

<?php

    class Uploader
    {
        private $destinationPath;
        private $errorMessage;
        private $extensions;
        private $allowAll;
        private $maxSize;
        private $uploadName;
        private $seqnence;
        public $name='Uploader';
        public $useTable    =false;

        function setDir($path){
            $this->destinationPath  =   $path;
            $this->allowAll =   false;
        }

        function allowAllFormats(){
            $this->allowAll =   true;
        }

        function setMaxSize($sizeMB){
            $this->maxSize  =   $sizeMB * (1024*1024);
        }

        function setExtensions($options){
            $this->extensions   =   $options;
        }

        function setSameFileName(){
            $this->sameFileName =   true;
            $this->sameName =   true;
        }
        function getExtension($string){
            $ext    =   "";
            try{
                    $parts  =   explode(".",$string);
                    $ext        =   strtolower($parts[count($parts)-1]);
            }catch(Exception $c){
                    $ext    =   "";
            }
            return $ext;
    }

        function setMessage($message){
            $this->errorMessage =   $message;
        }

        function getMessage(){
            return $this->errorMessage;
        }

        function getUploadName(){
            return $this->uploadName;
        }
        function setSequence($seq){
            $this->imageSeq =   $seq;
    }

    function getRandom(){
        return strtotime(date('Y-m-d H:i:s')).rand(1111,9999).rand(11,99).rand(111,999);
    }
    function sameName($true){
        $this->sameName =   $true;
    }
        function uploadFile($fileBrowse){
            $result =   false;
            $size   =   $_FILES[$fileBrowse]["size"];
            $name   =   $_FILES[$fileBrowse]["name"];
            $ext    =   $this->getExtension($name);
            if(!is_dir($this->destinationPath)){
                $this->setMessage("Destination folder is not a directory ");
            }else if(!is_writable($this->destinationPath)){
                $this->setMessage("Destination is not writable !");
            }else if(empty($name)){
                $this->setMessage("File not selected ");
            }else if($size>$this->maxSize){
                $this->setMessage("Too large file !");
            }else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){

        if($this->sameName==false){
                    $this->uploadName   =  $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
                }else{
            $this->uploadName=  $name;
        }
                if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
                    $result =   true;
                }else{
                    $this->setMessage("Upload failed , try later !");
                }
            }else{
                $this->setMessage("Invalid file format !");
            }
            return $result;
        }

        function deleteUploaded(){
            unlink($this->destinationPath.$this->uploadName);
        }

    }

?>
Now upload files using Uploader class. Use following code . Code block is self explanatory .

<?php

$uploader   =   new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif'));  //allowed extensions list//
$uploader->setMaxSize(.5);                          //set max file size to be allowed in MB//

if($uploader->uploadFile('txtFile')){   //txtFile is the filebrowse element name //   
    $image  =   $uploader->getUploadName(); //get uploaded file name, renames on upload//

}else{//upload failed
    $uploader->getMessage(); //get upload error message
}


?>

Thursday, December 13, 2012

array pagination using php class

<?php


  class pagination
  {
    var $page = 1; // Current Page
    var $perPage = 10; // Items on each page, defaulted to 10
    var $showFirstAndLast = false; // if you would like the first and last page options.
   
    function generate($array, $perPage = 10)
    {
      // Assign the items per page variable
      if (!empty($perPage))
        $this->perPage = $perPage;
     
      // Assign the page variable
      if (!empty($_GET['page'])) {
        $this->page = $_GET['page']; // using the get method
      } else {
        $this->page = 1; // if we don't have a page number then assume we are on the first page
      }
     
      // Take the length of the array
      $this->length = count($array);
     
      // Get the number of pages
      $this->pages = ceil($this->length / $this->perPage);
     
      // Calculate the starting point
      $this->start  = ceil(($this->page - 1) * $this->perPage);
     
      // Return the part of the array we have requested
      return array_slice($array, $this->start, $this->perPage);
    }
    function getpage($total)
    {
        $perPage=$this->perPage;
        $sratpage=$this->start;
        if($perPage>$total)
         {
                  echo "Results ".($sratpage+1)."-"; echo $total; echo " of ".$total;
         }else{
               
                if($sratpage==0)
                {
                        echo "Results ".($sratpage+1)."-"; echo $perPage; echo " of ".$total;
                }else{
                        $endpage=($sratpage+$perPage);
                        if($endpage>$total)
                        {
                         echo "Results ".$sratpage."-"; echo $total;echo " of ".$total;
                        }
                        else
                        {
               
                        echo "Results ".$sratpage."-"; echo $endpage;echo " of ".$total;
                        }
                           
               
                }
    }
   
  }
    function links()
    {
      // Initiate the links array
      $plinks = array();
      $links = array();
      $slinks = array();
     
      // Concatenate the get variables to add to the page numbering string
      if (count($_GET)) {
        $queryURL = '';
        foreach ($_GET as $key => $value) {
          if ($key != 'page') {
           // $queryURL .= '&'.$key.'='.$value;
          }
        }
      }
     
      // If we have more then one pages
      if (($this->pages) > 1)
      {
        // Assign the 'previous page' link into the array if we are not on the first page
        if ($this->page != 1) {
          if ($this->showFirstAndLast) {
            $plinks[] = ' <a href="?page=1'.$queryURL.'">&laquo;&laquo; First </a> ';
          }
          $plinks[] = ' <span class="paginationPrev"><a href="?page='.($this->page - 1).$queryURL.'">&laquo; Prev</a></span> ';
        }
       
        // Assign all the page numbers & links to the array
        echo '<span nowrap="nowrap" align="center">';
        for ($j = 1; $j < ($this->pages + 1); $j++) {
          if ($this->page == $j) {
            $links[] = ' <span class="selected1">'.$j.'</span> '; // If we are on the same page as the current item
          } else {
            $links[] = ' <a href="?page='.$j.$queryURL.'">'.$j.'</a>'; // add the link to the array
          }
        }
        echo '</span>';
        echo '<span class="paginationNext">';
        // Assign the 'next page' if we are not on the last page
        if ($this->page < $this->pages) {
          $slinks[] = ' <a href="?page='.($this->page + 1).$queryURL.'"> Next &raquo; </a> ';
          if ($this->showFirstAndLast) {
            $slinks[] = ' <a href="?page='.($this->pages).$queryURL.'"> Last &raquo;&raquo; </a> ';
          }
        }
        echo '</span>';
        // Push the array into a string using any some glue
        return implode(' ', $plinks).implode($this->implodeBy, $links).implode(' ', $slinks);
      }
      return;
    }
  }
?>

Tuesday, December 11, 2012

how to slider bar open using jquery

-----------------------------------------------------------------------------------------------
 <script type="text/javascript" src="<?php bloginfo( 'template_url' ); ?>/js/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        jQuery(".pull_feedback").toggle(function(){
                jQuery("#feedback").animate({left:"0px"});
                return false;
            },
            function(){
                jQuery("#feedback").animate({left:"-527px"});  
                return false;
            }
        ); //toggle
    }); //document.ready
    </script>
-------------------------------------------------------------------------------------------------
<script language="javascript">
function processForm(formId) {
document.getElementById('process').style.display='block';
$.ajax({
type: "GET",
url: "form_ask.php",
data: "sendmsg="+document.getElementById('user_question').value,
success: function(msg)
    {
            //alert(msg);
            document.getElementById('process').style.display='none';
            $('#message').html(msg);
            $('#user_question').val('');
            return true;
    },
    error: function(){
          
            return false;
        //alert('some error has occured...');  
    },
    start: function(){
        alert('ajax has been started...');  
    }
});
}
</script>

--------------------------------------------------------------------------------------------------
<div id="feedback">
<h2>Sikh  Counseling</h2>

<form action="" id="form1" method="post"  onsubmit="processForm('form1');return false;">
<div style="clear:both; padding-bottom: 8px;"></div>
            <div id="message"></div>
            <div id='process' style="display:none"><img src="loading.gif" ></div>
       
           
            <p>           
            <textarea id='user_question'  onfocus="if(this.value=='Type Your Sikh Counseling Question Here...') this.value='';" onblur="if(this.value=='') this.value='Type Your Sikh Counseling Question Here...';">Type Your Sikh Counseling Question Here...</textarea>           
            </p>
            <p class="txt">Sikh Counselors are Online Now</p>
            <p>
            <input type='submit' name='submit' value='submit' class="btn"/>
           
            </p>
        </form>
        <a href="#" class="pull_feedback" title="Click to leave Question">Question</a>
    </div>
------------------------------------------------------------------------------------------

Friday, December 7, 2012

javascrpt captcha

<html>
<head>
<title>Captcha</title>
   
    <script type="text/javascript">

   //Created / Generates the captcha function   
    function DrawCaptcha()
    {
       var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
       var string_length =6;
       var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
          }
      
        document.getElementById("txtCaptcha").value = randomstring
    }

    // Validate the Entered input aganist the generated security code function  
    function ValidCaptcha(){
        var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
        var str2 = removeSpaces(document.getElementById('txtInput').value);
        if (str1 == str2)
           return true;       
        else
        {
            alert("Invalid captcha value");
        return false;
        }
       
    }

    // Remove the spaces from the entered and generated code
    function removeSpaces(string)
    {
        return string.split(' ').join('');
    }
   

    </script>
   
   
   
</head>
<body onLoad="DrawCaptcha();">
<table>
<tr>
    <td>
        Welcome To Captcha<br />
    </td>
</tr>
<tr>
    <td>
        <input type="text" id="txtCaptcha" disabled="true"
            style="background-image:url(captcha_bg.jpg); text-align:center; border:none;
            font-weight:bold; font-family:Arial, Helvetica, sans-serif; font-size:16px;line-height:12px;" />
        <input type="button" id="btnrefresh" value="Refresh"  onClick="DrawCaptcha();return false;" />
    </td>
</tr>
<tr>
    <td>
        <input type="text" id="txtInput"/>   
    </td>
</tr>
<tr>
    <td>
        <input id="Button1" type="button" value="Check" onClick="alert(ValidCaptcha());"/>
    </td>
</tr>
</table>
</body>
</html>

Thursday, December 6, 2012

how to sorting multiple array object in php


sorting multiple array object using php
 function sort_arr_of_obj($array, $sortby, $direction='asc') {
    
    $sortedArr = array();
    $tmp_Array = array();
    
    foreach($array as $k => $v) {
        $tmp_Array[] = strtolower($v->$sortby);
    }
    
    if($direction=='asc'){
        asort($tmp_Array);
    }else{
        arsort($tmp_Array);
    }
    
    foreach($tmp_Array as $k=>$tmp){
        $sortedArr[] = $array[$k];
    }
    
    return $sortedArr;

}


$lowestsellerpricesort= sort_arr_of_obj($response->categories->category->items->product->offers->offer,'basePrice','asc');

how to sort multiple array in php

multiple array sorting using php 
<?php
$multiArray = Array(
    Array("id" => 1, "name" => "Defg","add"=>"adstes"),
    Array("id" => 4, "name" => "Abcd","add"=>"tes"),
    Array("id" => 3, "name" => "Bcde","add"=>"des"),
    Array("id" => 2, "name" => "Cdef","add"=>"cad"));
function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

aasort($multiArray,"id");
echo "<pre>";print_r($multiArray);

?>

multiple array sorting using php