Bulk Rename Files in a Folder - PHP

$dir = "img1";
$fileType = "jpg";
$charsToTrim = 4;
if($handle = opendir($dir))
{
    $count = 1;
    while (false !== ($file = readdir($handle))) 
   {
    if(is_file($dir."\\".$file))
    {
        $extension = substr(strrchr($file,"."),1);
        if(strcasecmp($fileType,$extension) == 0)
        {
           // $newName = substr($file,$count); 
      $newName = $count;
            $success = rename($dir."\\".$file, $dir."\\".$newName.'.'.$extension); 
            if($success)
            {
                echo $file." renamed to ".$newName;
                echo "
"; $count++; } else { echo "Cannot rename ".$file. " to ".$newName."
"; echo "
"; } } } } echo $count." files renamed"; } closedir($handle);

Creating Dynamic Image Thumbnails Depending Upon Height Using PHP

function createthumb($name, $newname, $new_height, $border=false, $transparency=true, $base64=false) {
 
  if(file_exists($newname))
        @unlink($newname);
    if(!file_exists($name))
        return false;
    $arr = explode(".",$name);
    $ext = $arr[count($arr)-1];

    if($ext=="jpeg" || $ext=="jpg" || $ext=="JPEG" || $ext=="JPG"){
        $img = @imagecreatefromjpeg($name);
  
    } elseif($ext=="png"){
        $img = @imagecreatefrompng($name);
    } elseif($ext=="gif") {
        $img = @imagecreatefromgif($name);
    }
    if(!$img)
        return false;
    $old_x = imageSX($img);
    $old_y = imageSY($img);

 $avg = $old_y/$old_x;

    $new_h = $new_height;

 $new_w = floor($new_h/$avg);

 if($old_x < $new_w && $old_y < $new_h) 
 {
        $thumb_w = $old_x;
        $thumb_h = $old_y;
    }elseif($old_x < $old_y)
 {
    echo $thumb_w= floor($new_height*$zing);
  $thumb_h=$new_height;
    
 }else
 {
  $thumb_w = $new_w;
        $thumb_h = $new_h;
 }

    $thumb_w = ($thumb_w<1) ? 1 : $thumb_w;
    $thumb_h = ($thumb_h<1) ? 1 : $thumb_h;
    $new_img = ImageCreateTrueColor($thumb_w, $thumb_h);
   
    if($transparency) {
        if($ext=="png") {
            imagealphablending($new_img, false);
            $colorTransparent = imagecolorallocatealpha($new_img, 0, 0, 0, 127);
            imagefill($new_img, 0, 0, $colorTransparent);
            imagesavealpha($new_img, true);
        } elseif($ext=="gif") {
            $trnprt_indx = imagecolortransparent($img);
            if ($trnprt_indx >= 0) {
                $trnprt_color = imagecolorsforindex($img, $trnprt_indx);
                $trnprt_indx = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                imagefill($new_img, 0, 0, $trnprt_indx);
                imagecolortransparent($new_img, $trnprt_indx);
            }
        }
    } else {
        Imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255));
    }
   
    imagecopyresampled($new_img, $img, 0,0,0,0, $thumb_w, $thumb_h, $old_x, $old_y);
    if($border) {
        $black = imagecolorallocate($new_img, 0, 0, 0);
        imagerectangle($new_img,0,0, $thumb_w, $thumb_h, $black);
    }
    if($base64) {
        ob_start();
        imagepng($new_img);
        $img = ob_get_contents();
        ob_end_clean();
        $return = base64_encode($img);
    } else {
        if($ext=="jpeg" || $ext=="jpg" || $ext=="JPEG" || $ext=="JPG"){
            imagejpeg($new_img, $newname);
            $return = true;
        } elseif($ext=="png"){
            imagepng($new_img, $newname);
            $return = true;
        } elseif($ext=="gif") {
            imagegif($new_img, $newname);
            $return = true;
        }
    }
    imagedestroy($new_img);
    imagedestroy($img);
    return $return;
}

createthumb($src, $dest,$height,false, true, false);

Creating Dynamic Image Thumbnails Using PHP

function createthumb($name, $newname, $new_w, $new_height, $border=false, $transparency=true, $base64=false) {
 
  if(file_exists($newname))
        @unlink($newname);
    if(!file_exists($name))
        return false;
    $arr = explode(".",$name);
    $ext = $arr[count($arr)-1];

    if($ext=="jpeg" || $ext=="jpg" || $ext=="JPEG" || $ext=="JPG"){
        $img = @imagecreatefromjpeg($name);
  
    } elseif($ext=="png"){
        $img = @imagecreatefrompng($name);
    } elseif($ext=="gif") {
        $img = @imagecreatefromgif($name);
    }
    if(!$img)
        return false;
    $old_x = imageSX($img);
    $old_y = imageSY($img);
 
 $agv = $old_x/$old_y;
 
  $new_w = $new_w;
  $new_h = floor($new_w/$agv);

 if($old_x < $new_w && $old_y < $new_h) 
 {
        $thumb_w = $old_x;
        $thumb_h = $old_y;
    }elseif($old_x < $old_y)
 {
    echo $thumb_w= floor($new_height*$zing);
  $thumb_h=$new_height;
    
 }else
 {
  $thumb_w = $new_w;
        $thumb_h = $new_h;
 }

    $thumb_w = ($thumb_w<1) ? 1 : $thumb_w;
    $thumb_h = ($thumb_h<1) ? 1 : $thumb_h;
    $new_img = ImageCreateTrueColor($thumb_w, $thumb_h);
   
    if($transparency) {
        if($ext=="png") {
            imagealphablending($new_img, false);
            $colorTransparent = imagecolorallocatealpha($new_img, 0, 0, 0, 127);
            imagefill($new_img, 0, 0, $colorTransparent);
            imagesavealpha($new_img, true);
        } elseif($ext=="gif") {
            $trnprt_indx = imagecolortransparent($img);
            if ($trnprt_indx >= 0) {
                //its transparent
                $trnprt_color = imagecolorsforindex($img, $trnprt_indx);
                $trnprt_indx = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                imagefill($new_img, 0, 0, $trnprt_indx);
                imagecolortransparent($new_img, $trnprt_indx);
            }
        }
    } else {
        Imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255));
    }
   
    imagecopyresampled($new_img, $img, 0,0,0,0, $thumb_w, $thumb_h, $old_x, $old_y);
    if($border) {
        $black = imagecolorallocate($new_img, 0, 0, 0);
        imagerectangle($new_img,0,0, $thumb_w, $thumb_h, $black);
    }
    if($base64) {
        ob_start();
        imagepng($new_img);
        $img = ob_get_contents();
        ob_end_clean();
        $return = base64_encode($img);
    } else {
        if($ext=="jpeg" || $ext=="jpg" || $ext=="JPEG" || $ext=="JPG"){
            imagejpeg($new_img, $newname);
            $return = true;
        } elseif($ext=="png"){
            imagepng($new_img, $newname);
            $return = true;
        } elseif($ext=="gif") {
            imagegif($new_img, $newname);
            $return = true;
        }
    }
    imagedestroy($new_img);
    imagedestroy($img);
    return $return;
}

createthumb($src, $dest, $width,$height,false, true, false);

PHP Mail Form With Multiple Attachments

";

   // generate a random string to be used as the boundary marker
   $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

   // now we'll build the message headers
   $headers = "From: $from\r\n" .
   "MIME-Version: 1.0\r\n" .
      "Content-Type: multipart/mixed;\r\n" .
      " boundary=\"{$mime_boundary}\"";

   // here, we'll start the message body.
   // this is the text that will be displayed
   // in the e-mail
   $message="This is an example";

   // next, we'll build the invisible portion of the message body
   // note that we insert two dashes in front of the MIME boundary 
   // when we use it
   $message = "This is a multi-part message in MIME format.\n\n" .
      "--{$mime_boundary}\n" .
      "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
      "Content-Transfer-Encoding: 7bit\n\n" .
   $message . "\n\n";

   // now we'll process our uploaded files
   foreach($_FILES as $userfile){
      // store the file information to variables for easier access
      $tmp_name = $userfile['tmp_name'];
      $type = $userfile['type'];
      $name = $userfile['name'];
      $size = $userfile['size'];

      // if the upload succeded, the file will exist
      if (file_exists($tmp_name)){

         // check to make sure that it is an uploaded file and not a system file
         if(is_uploaded_file($tmp_name)){
 	
            // open the file for a binary read
            $file = fopen($tmp_name,'rb');
 	
            // read the file content into a variable
            $data = fread($file,filesize($tmp_name));

            // close the file
            fclose($file);
 	
            // now we encode it and split it into acceptable length lines
            $data = chunk_split(base64_encode($data));
         }
 	
         // now we'll insert a boundary to indicate we're starting the attachment
         // we have to specify the content type, file name, and disposition as
         // an attachment, then add the file content.
         // NOTE: we don't set another boundary to indicate that the end of the 
         // file has been reached here. we only want one boundary between each file
         // we'll add the final one after the loop finishes.
         $message .= "--{$mime_boundary}\n" .
            "Content-Type: {$type};\n" .
            " name=\"{$name}\"\n" .
            "Content-Disposition: attachment;\n" .
            " filename=\"{$fileatt_name}\"\n" .
            "Content-Transfer-Encoding: base64\n\n" .
         $data . "\n\n";
      }
   }
   // here's our closing mime boundary that indicates the last of the message
   $message.="--{$mime_boundary}--\n";
   // now we just send the message
   if (@mail($to, $subject, $message, $headers))
      echo "Message Sent";
   else
      echo "Failed to send";
} else {
?>

Your e-mail:

File:

File:


Download files using ftp and php

I want to download files from a ftp server using a php script with ftp_get(). Is it possible to download files from a server using a script with ftp_get. I mean are the files saved on the users computer or on the webserver? I want to use this script on computers that are behind a firewall that only alows access to the internet on port 80 and the http protocol.

How to get a web page using CURL

function get_web_page( $url )
{
 $options = array(
  CURLOPT_RETURNTRANSFER => true,     // return web page
  CURLOPT_HEADER         => false,    // don't return headers
  CURLOPT_FOLLOWLOCATION => true,     // follow redirects
  CURLOPT_ENCODING       => "",       // handle compressed
  CURLOPT_USERAGENT      => "spider", // who am i
  CURLOPT_AUTOREFERER    => true,     // set referer on redirect
  CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
  CURLOPT_TIMEOUT        => 120,      // timeout on response
  CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
 );

 $ch      = curl_init( $url );
 curl_setopt_array( $ch, $options );
 $content = curl_exec( $ch );
 $err     = curl_errno( $ch );
 $errmsg  = curl_error( $ch );
 $header  = curl_getinfo( $ch );
 curl_close( $ch );

 $header['errno']   = $err;
 $header['errmsg']  = $errmsg;
 $header['content'] = $content;
 return $header;
}


Easy Ajax with jQuery

$.ajax({
  type: "POST",
  url: "sample.php",
  data: "name=ramesh" ,
  success: function(msg){
 $('#message').html(msg);
 
  }
});

If you’ve developed Ajax applications before without jQuery, you’ll immediately see the value here. jQuery has put all of the properties of Ajax into one simple API. You can control everything including the url, cache, success function, data type, and even synchronization, all from one neat declaration. It’s nothing short of beautiful.

Easy PHP Pagination

I’ve had a few pagination scripts over the years but I thought i’d share the one that i’m currently using as it’s a useful script to have in your website. As a developer you’ll soon find a need to paginate data when displaying contents from the database, and rather than use JavaScript which could require all the data to be loaded into the page on load, we can use PHP to ensure that we’re only requesting the data that we need from the database. For those who have no clue what i’m talking about. Pagination is a way of splitting up data into manageable chunks to display to a user, if you’ve spent more than two minutes on the internet chances are you’ve come into contact with some form of pagination. as a simple example you can checkout my website and allows you to split data up with it being paginated across however many pages dynamically.
 1)
	{	
	

	
	
		$pagination .= "";		
	
	
}
 echo $total_pages.' Results';
 // pagination
 echo $pagination;
?>

    '.$row['country'].' '; } ?>
Here’s the css to style you pagination

Jquery infinite scroll - with div

This code has been tested and verified as working. When you scroll your div, the code checks if the scroller reached to the bottom by comparing the scroller height against the scroller position. If so, it calls to a method that gets more content and append it to the div.

    
        Test 
        
        
    
        
            

This is the div content

This is the div content

This is the div content

This is the div content

This is the div content

This is the div content

Scroll Height:
Scroll position:

Simple AJAX - PHP and Javascript

this tutorial I will show you the most basic way to get a response from a PHP script.and we will start with the base object you need: a XMLHTTP Javascript object. With this object you call a server-side script and get the response back. Most browsers use the same Javascript object, but of course Microsoft has to be different, so they require their own. The following function will return the correct object:
function Inint_AJAX() {

   try { return new ActiveXObject("Msxml2.XMLHTTP");  } catch(e) {} //IE

   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE

   try { return new XMLHttpRequest();          } catch(e) {} //Native Javascript

   alert("XMLHttpRequest not supported");

   return null;

};
This code will, again, return an XMLHTTP object to use in our Javascript. What is going to happen is that we are going to use this object to make an HTTP request through Javascript. When we get a response back, we will simply place it in the page, nothing fancy. In order to make the request we use the following code:
function ajaxfun(src)

{

     var req = Inint_AJAX();

     req.onreadystatechange = function () { 

          if (req.readyState==4 && req.status==200) {

                  document.getElementById('divid').innerHTML=req.responseText; //retuen value
          }

     };

     req.open("GET", "demo.php?src="+src); //make connection

     req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header

     req.send(null); //send value

   

}

How to create stdClass (Object)

function myFunction($stdObj){
 echo $stdObj->name."";
}

$a= new stdClass;
$a->name = "Ramesh Song";
$a->email = "ilovephp@gmail.com";
$a->web = "phpbuddy.blogsport.com";

myFunction($a); // output : Ramesh Song

/********  Other Way ********/

$b = array(
   "name" => "Ramesh song",
   "email" => "ilovephp@gmail.com",
   "web" => "phpbuddy.blogsport.com");

$b = (object) $b;

myFunction($b); // output : Ramesh Song

How to use array_map() with class method?

class MyClass {
 public function __construct(){}

 protected function convertToObject($array){
  return (object) $array;
 }

 public function convertMyArray($array){
  $obj = array_map(array('MyClass','convertToObject'),$array);
  return $obj;
 }
}

$array = array(
 array('Country' => 'US'),
 array('Country' => 'KOREA'),
 array('Country' => 'JAPAN'),
 array('Country' => 'INDIA'),
 array('Country' => 'CANADA')
);

$cls = new MyClass();
$obj = $cls->convertMyArray($array);
echo $obj[0]->Country; // OUTPUT : US

How to use PHP temporary file ?

$temp = tmpfile();
fwrite($temp,'Line #1'.chr(13).chr(10));
fwrite($temp,'Line #2'.chr(13).chr(10));
fwrite($temp,'Line #3'.chr(13).chr(10));
fseek($temp,0); //move file pointer

// char(13) = \r
// char(10) = \n

while($row = fgets($temp,1024)){
 echo $row ."
";
}

fclose($temp); // remove temporary fileand no space!

Output ::
Line #1
Line #2
Line #3

Access parent’s parent variable and Access interface constant variable

// Access parent's parent variable
class Parent1 {
 const PARENT_NAME = "ramesh Song";
 const PARENT_AGE = "31";
 const PARENT_EMAIL = "ilovephp@gmail.com";
 protected $_normal_val = "HeHeHeHe";
}

class Parent2 extends Parent1 {
 public function __construct(){}
}

class Child extends Parent2 {
 public function __construct(){}

 public function getParentName(){
  return parent::PARENT_NAME;
 }

 public function getNormalVal(){
  return $this->_normal_val;
 }
}

$c = new Child();
echo $c->getParentName();
echo "br";
echo $c->getNormalVal();

/*
Output :
 ramesh Song
 HeHeHeHe
*/

// Access interface constant variable

interface Parent3 {
 const PARENT_NAME = "ramesh Song";
 const PARENT_AGE = "31";
 const PARENT_EMAIL = "ilovephp@gmail.com";
 //protected $_normal_val = "HeHeHeHe"; Error : Interfaces may not include member variables
}

class Parent4 implements Parent3 {
 public function __construct(){}

 public function getParentName(){
  //return parent::PARENT_NAME;  Error : current class scope has no parent
  return self::PARENT_NAME;
 }
}

class Child2 extends Parent4 {
 public function __construct(){}

 public function getParentName(){
  return parent::PARENT_NAME;

 }
 public function getParentAge(){
  return parent::PARENT_AGE;
 }
}

$d = new Parent4();
echo $d -> getParentName();
echo "br";
$e = new Child2();
echo $e->getParentName();
echo "br";
echo $e->getParentAge();

/*
Output :
 ramesh Song
 ramesh Song
 31
*/

Serialize with Jquery and Unserialize with PHP

//JS (Jquery)

var form = document.getElememtById('myForm');

var serializedData = $(form).serialize();

$.post(
 'getSerializedData.php',
 {data:serializedData},
 function(data){
 }
)

// PHP

$serializedData = $_POST['data'];
$unserializedData = array();

parse_str($unserializedData,$serializedData);

print_r($unserializedData);

Get Browser Information Using PHP

function getBrowser(){
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";

    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }

    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }

    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?' . join('|', $known) .
    ')[/ ]+(?[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }

    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){             $version= $matches['version'][0];         }         else {             $version= $matches['version'][1];         }     }     else {         $version= $matches['version'][0];     }     // check if we have a number     if ($version==null || $version=="") {$version="?";}     return array(         'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
}

Add and Remove HTML elements using javascript





How to count no of Files in a Folder?

if (file_exists("images/"))
{
 $dh = opendir("images/");
 $filecount = 0;
 while (($file = readdir($dh)) !== false) 
 {
  if(is_file("images/".$file))
   $filecount++;
 }
 echo 'No fo Files is: '.$filecount;
}

$directory = "../images/team/harry/";
if (glob($directory . "*.jpg") != false)
{
 $filecount = count(glob($directory . "*.jpg"));
 echo $filecount;
}
else
{
 echo 0;
}

Installing ionCube Loader for Xampp


Installing ionCube Loader In Linux:

1. Download the program using wget or FTP.
http://www.ioncube.com/loader_download.php

2. Unpack it
tar -zxvf ioncube_loaders.tar.gz

3. cd ioncube (if you are using xampp, copy the extracted folder into C:\xampp\apache)

4. copy the following php files into the default document root

ioncube-loader-helper.php
ioncube-encoded-file.php

Then open it as http://localhost/ioncube-loader-helper.php

The output should be something similar to:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
php.ini Installation Instructions
**********************************
Analysis
**********
Analysis of your system configuration shows:

PHP Version 5.2.9
Operating System Linux
Threaded PHP No
php.ini file C:\xampp\apache\bin\php.ini
Required Loader ioncube_loader_win_5.2.dll

Instructions
To install the Loader in your php.ini file, edit or create the file C:\xampp\apache\bin\php.ini and add the following line before any other zend_extension lines:

zend_extension = //ioncube_loader_win_5.2.dll

where // is where you’ve installed the loader, e.g. C:\xampp\apache\ioncube\

If there are no zend_extension lines already, you can put the line at any point in the file.

Finally, stop and restart your web server software for the changes to take effect.

Installing the Loader for run-time loading

To install for runtime loading, create a directory called ioncube at or above the top level of your encoded files, and ensure that the directory contains the ioncube_loader_win_5.2.dll loader. If run-time install of the Loader is possible on your system then encoded files should automatically install the loader when needed.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

5. Now lets move the iconcube directory to a permanent location:
cd ..
mv ioncube C:\xampp\apache\

6. Now that you know the location of php.ini you need to edit it.
vi C:\xampp\apache\bin\php.ini

Now find where other zend extentions are in the file.
search for “zend_extension”

Paste in your new line for ioncube loader
zend_extension = C:\xampp\apache\ioncube\ioncube_loader_win_5.2.dll

7. Save the changes

8. Restart the web server to take effect.
/etc/init.d/httpd restart

Success! You should now see a section in your PHP Info page that says:

Additional Modules
Module Name ionCube Loader

You may also use the following URL to verify the installation
http://localhost/ioncube-encoded-file.php

It will show something like:
~~~~~~~~~~~~~~~~~~~~~
This file has been successfully decoded. ionCube Loaders are correctly installed.


Installing ionCube Loader In Windows:

1. Download the Zip File.
http://www.ioncube.com/loader_download.php

2. UnZip it

3. if you are using xampp, copy the extracted folder into C:\xampp\php

4. copy the following php files into the default document root

ioncube-loader-helper.php
ioncube-encoded-file.php

Then open it as http://localhost/ioncube-loader-helper.php

The output should be something similar to:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
php.ini Installation Instructions
**********************************
Analysis
**********
Analysis of your system configuration shows:

PHP Version 5.2.9
Operating System Windows
Threaded PHP No
php.ini file C:\xampp\php\php.ini
Required Loader ioncube_loader_win_5.2.dll

Instructions
To install the Loader in your php.ini file, edit or create the file C:\xampp\php\php.ini and add the following line before any other zend_extension lines:

zend_extension = //ioncube_loader_win_5.2.dll

where // is where you’ve installed the loader, e.g. C:\xampp\php\ioncube\

If there are no zend_extension lines already, you can put the line at any point in the file.

Finally, stop and restart your web server software for the changes to take effect.

Installing the Loader for run-time loading

To install for runtime loading, create a directory called ioncube at or above the top level of your encoded files, and ensure that the directory contains the ioncube_loader_win_5.2.dll loader. If run-time install of the Loader is possible on your system then encoded files should automatically install the loader when needed.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

5. Now lets move the iconcube directory to a permanent location:
  ioncube C:\xampp\php\

6. Now that you know the location of php.ini you need to edit it.
 C:\xampp\php\php.ini

Now find where other zend extentions are in the file.
search for “zend_extension”

Paste in your new line for ioncube loader
zend_extension = C:\xampp\php\ioncube\ioncube_loader_win_5.2.dll

7. Save the changes

8. Restart the web server to take effect.

Success! You should now see a section in your PHP Info page that says:

Additional Modules
Module Name ionCube Loader

You may also use the following URL to verify the installation
http://localhost/ioncube-encoded-file.php

It will show something like:
~~~~~~~~~~~~~~~~~~~~~
This file has been successfully decoded. ionCube Loaders are correctly installed.

Email Validation in javascript

Email Validation in javascript
function isValidEmail(content)
{

valid = false;


var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;


if (filter.test(content)) {
valid=true;
}

return valid;
}

Phone Validate in js

Phone Validate in js
function validatephone(xxxxx) {
  var maintainplus = '';
  var numval = xxxxx.value
  if ( numval.charAt(0)=='+' ){ var maintainplus = '+';}
  curphonevar = numval.replace(/[\\A-Za-z!"£$%^&*+_={};:'@#~,¦\/<>?|`¬\]\[]/g,'');
  xxxxx.value = maintainplus + curphonevar;
  var maintainplus = '';
  xxxxx.focus;
}

Disable the drag-to-expand feature for textarea

In css
textarea {
  resize: none;
}
You could also set this programmatically by using jQuery:
// CSS
textarea.no-expand {
  resize: none;
}

// jQuery
$('#my-text-area').addClass('no-expand');

Refresh uploading image in preview




PHP Application Debugging


One of the best places to look for errors is in the server logs, if you have access to them. That depends on your host.

For PHP you can insert the following code at the beginning of your file:

error_reporting(E_ALL);

ini_set('display_errors','on');

Everything that goes to the server log will also show up on your web page. Be sure to remove this ASAP as it could be annoying to general readers and it could give away key information.


Another good trick is to use echo/alert statements in key parts of your code to give you an idea of what is going on. (You could also create a log file on your server, but that's getting pretty elaborate). Again, remove ASAP.

A word of caution with the use of echo in PHP. Some PHP processing is messed up when there's anything sent to the browser before it finished. Doing things with headers, for instance. That goes south with any output.

Sending HTML Email with PHP

this simple code lines will help you sending html email.

//change this to your email.
$to="name@domain.com";

$subject='Hello! This is Sending   HTML email';  
$message="

  
    
I am reciving HTML email......
Thanks Ramesh!


Now you Can send HTML Email
Regards
Ramesh Thanneeru "; $headers = "From: info@domain.com\r\n"; //options to send to cc+bcc $headers .= "Cc: email@domain.com"; $headers .= "Bcc: email@domain.com"; $headers .= "Reply-To: email@domain.com\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; mail($to, $subject, $message, $headers);

Increase Memory size in php

Increase Memory size in php
ini_set('memory_limit', '512M');

Authorize.Net Integrating IN PHP

Authorize.Net is my favorite payment mode for using in web development. It is simple, easy and secure payment connection.

If you are using PayPal Payments Pro, then you will need to provide your  company with the following details.
• API Login ID
• Transaction Key
SIM Implementation

// the parameters for the payment can be configured here
// the API Login ID and Transaction Key must be replaced with valid values
$loginID  = "API_LOGIN_ID";
$transactionKey = "TRANSACTION_KEY";
$amount   = "19.99";
$description  = "Sample Transaction";
$label    = "Submit Payment"; // The is the label on the 'submit' button
$testMode  = "false";
// By default, this sample code is designed to post to our test server for
// developer accounts: https://test.authorize.net/gateway/transact.dll
// for real accounts (even in test mode), please make sure that you are
// posting to: https://secure.authorize.net/gateway/transact.dll
$url   = "https://test.authorize.net/gateway/transact.dll";

// If an amount or description were posted to this page, the defaults are overidden
if (array_key_exists("amount",$_REQUEST))
 { $amount = $_REQUEST["amount"]; }
if (array_key_exists("amount",$_REQUEST))
 { $description = $_REQUEST["description"]; }

// an invoice is generated using the date and time
$invoice = date(YmdHis);
// a sequence number is randomly generated
$sequence = rand(1, 1000);
// a timestamp is generated
$timeStamp = time();

// The following lines generate the SIM fingerprint.  PHP versions 5.1.2 and
// newer have the necessary hmac function built in.  For older versions, it
// will try to use the mhash library.
if( phpversion() >= '5.1.2' )
 { $fingerprint = hash_hmac("md5", $loginID . "^" . $sequence . "^" . $timeStamp . "^" . $amount . "^", $transactionKey); }
else 
 { $fingerprint = bin2hex(mhash(MHASH_MD5, $loginID . "^" . $sequence . "^" . $timeStamp . "^" . $amount . "^", $transactionKey)); }
?>


Amount:  

Description:  




AIM Implementation

"API_LOGIN_ID",
 "x_tran_key"  => "TRANSACTION_KEY",

 "x_version"   => "3.1",
 "x_delim_data"  => "TRUE",
 "x_delim_char"  => "|",
 "x_relay_response" => "FALSE",

 "x_type"   => "AUTH_CAPTURE",
 "x_method"   => "CC",
 "x_card_num"  => "4111111111111111",
 "x_exp_date"  => "0115",

 "x_amount"   => "19.99",
 "x_description"  => "Sample Transaction",

 "x_first_name"  => "John",
 "x_last_name"  => "Doe",
 "x_address"   => "1234 Street",
 "x_state"   => "WA",
 "x_zip"    => "98004"
              
 // Additional fields can be added here as outlined in the AIM integration
 // guide at: http://developer.authorize.net


);

// This section takes the input fields and converts them to the proper format
// for an http post.  For example: "x_login=username&x_tran_key=a1B2c3D4"
$post_string = "";
foreach( $post_values as $key => $value )
 { $post_string .= "$key=" . urlencode( $value ) . "&"; }
$post_string = rtrim( $post_string, "& " );

// This sample code uses the CURL library for php to establish a connection,
// submit the post, and record the response.
// If you receive an error, you may want to ensure that you have the curl
// library enabled in your php configuration
$request = curl_init($post_url); // initiate curl object
 curl_setopt($request, CURLOPT_HEADER, 1); // set to 0 to eliminate header info from response
 curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
 curl_setopt($request, CURLOPT_POSTFIELDS, $post_string); // use HTTP POST to send form data
 curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
 $post_response = curl_exec($request); // execute curl post and store results in $post_response
 // additional options may be required depending upon your server configuration
 // you can find documentation on curl options at http://www.php.net/curl_setopt
curl_close ($request); // close curl object
// This line takes the response and breaks it into an array using the specified delimiting character
$response_array = explode($post_values["x_delim_char"],$post_response);

// individual elements of the array could be accessed to read certain response
// fields.  For example, response_array[0] would return the Response Code,
// response_array[2] would return the Response Reason Code.
// for a list of response fields, please review the AIM Implementation Guide
    $message=$response_array[3];
   $Trans_id=$response_array[5];
if($response_array[1]==1 && $response_array[2]==1)
{
 // payment is successful. Do your action here
}
else 
{
  // payment failed
}


?>

PayPal Pro Payment Integration in PHP

 If you are using PayPal Payments Pro, then you will need to provide your web design company with the following details.
• API username
• signature
• password
Please note that this is different to your PayPal account details. The details you use to login to Paypal’s website to access your accounts is separate to the API details you need to provide your web designer. Please do not email or provide your account details to your web design company as the information is confidential.
Contrary to what some may think, the API details are not provided by PayPal to start with. Instead, the PayPal account holder is required to generate this information by logging on to their account on PayPal’s website.
Following are the instructions on how to obtain API details as per their user guide:

Creating API Signature for PayPal Pro Website Payments

An API signature consists of an API username along with an associated API password and signature, all of which are assigned by PayPal. This information needs to be supplied with all transaction requests made by your website.
You must have a PayPal Business account to create a signature.
To create an API signature:
1. Log into PayPal, then click Profile under My Account.
2. Click API Access.
3. Click Request API Credentials.
4. Check Request API signature and click Agree and Submit.


$value) {
  $tmpAr = explode("=", $value);
  if(sizeof($tmpAr) > 1) {
   $httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
  }
 }

 if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
  exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
 }

 return $httpParsedResponseAr;
}

// Set request-specific fields.
$paymentType = urlencode('Authorization');    // or 'Sale'
$firstName = urlencode('customer_first_name');
$lastName = urlencode('customer_last_name');
$creditCardType = urlencode('customer_credit_card_type');
$creditCardNumber = urlencode('customer_credit_card_number');
$expDateMonth = 'cc_expiration_month';
// Month must be padded with leading zero
$padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));

$expDateYear = urlencode('cc_expiration_year');
$cvv2Number = urlencode('cc_cvv2_number');
$address1 = urlencode('customer_address1');
$address2 = urlencode('customer_address2');
$city = urlencode('customer_city');
$state = urlencode('customer_state');
$zip = urlencode('customer_zip');
$country = urlencode('customer_country');    // US or other valid country code
$amount = urlencode('example_payment_amuont');
$currencyID = urlencode('USD');       // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')

// Add request-specific fields to the request string.
$nvpStr = "&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
   "&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName".
   "&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyID";

// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr);

if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
 exit('Direct Payment Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else  {
 exit('DoDirectPayment failed: ' . print_r($httpParsedResponseAr, true));
}

?>




Simple PayPal


Online payment method and PayPal is the most secure payment gateway. If you have a very basic knowledge of PHP, you can easily implement the simple PayPal gateway in your site.

There are 3 main parts to the PayPal IPN system.

A webpage that initiates a request to PayPal to make a payment.
A PHP page on your webserver that PayPal calls to notify you that payment has been made.
A webpage that confirms the above payment and continues on to the next phase of your web application, such as a ‘Thank You’ page.

Parts 1 and 3 are accessible by customers on your website. Part 2 is only visible to PayPal. The diagram below illustrates the interaction between your customer, PayPal and your website.

// YOUR PAYPAL EMAIL ID // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD') // Sets the locale (language) of the PayPal login page