PHP common functions

We are going to go throw some of the most used functions and code snippets.

php.mail

Using mail to send a email from our PHP code is easy.
A simple snippet

  <?php
 
     $to_email = "johndoe@hotmail.com";
     $subject  = "Hello from my website";
     $content  = "Hi John,\nNow i can send emails from my website\n\nBest regards\nJane Doe";
 
     //Send the mail
     mail($to_email,$subject,$content);
  ?>

In the last example we didn't set a sender email, so the servername would have been used.
the function mail comes with some options. That you can add.
A simple snippet

  <?php
 
     $to_email = "johndoe@hotmail.com";
     $subject  = "Hello from my website";
     $content  = "Hi John,\nNow i can send emails from my website\n\nBest regards\nJane Doe";
     $options  = "From: janedoe@hotmail.com\nContent-Type: text/plain; charset=ISO-8859-1";
 
     //Send the mail
     mail($to_email,$subject,$content,$options);
  ?>

Sometimes you need to add a attachment to your email.
Here is a bit advance example.

  <?php
 
     $to_email             = "johndoe@hotmail.com";
     $subject              = "A file from my website";
     $filename             = $_SERVER["DOCUMENT_ROOT"] . "/files/myzipfile.zip";
     $filetype             = "application/octet-stream"; 
     $options              = "From: janedoe@hotmail.com";
     $text                 = "Hi John\n\nHere is the zip file i told you about :-)";
 
     $semi_rand = md5(time()); 
     $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
 
 
    //Read the file
     $handle         = fopen($filename, 'rb');
     $filecontents   = fread($handle, filesize($filename));
     fclose($handle);
 
     //base64 encode the file
     $filecontents   = @base64_encode($filecontents);        
 
     //Write the mime message
     $options            .= "\nMIME-Version: 1.0";
     $options            .= "\nContent-Type: multipart/mixed;\n boundary=\"". $mime_boundary ."\"\n\n";
 
     $content            .= "This is a multi-part message in MIME format.\n\n";
     $content            .= "--$mime_boundary\n";
 
 
     // Adding the text
     $content          .= "Content-Type: text/html; charset=iso-8859-1\n";
     $content          .= "Content-Transfer-Encoding: 8bit\n\n";
     $content          .= $text . "\n\n";
 
     // Adding the file
     $content          .= "--". $mime_boundary . "\n";
     $content          .= "Content-Type: application/octet-stream; name=\"" . basename($filename) . "\"\n";
     $content          .= "Content-Transfer-Encoding: base64\n\n";
     $content          .= chunk_split($filecontents) . "\n\n";
     $content          .= "--". $mime_boundary . "\n";
 
 
     //Send the mail
     mail($to_email,$subject,$content,$options);
  ?>

php.array

Arrays is a collection of data in a single variable.
We are going to check arrays and working with them

Checking Arrays

  <?php
 
       $myArray[] = "John Doe";
       $myArray[] = "Jane Doe";
       $myArray[] = "James Doe";
       $myArray[] = "Donna Doe";
 
       //See if myArray is a array
       if (is_array($myArray)){
          print "Working with a array";
       } else {
          print "myArray is not a array";
       }
 
       //Check if James Doe is in the array
 
       if (in_array("James Doe",$myArray)){
          print "We found James Doe in array";
       } else {
          print "James Doe is nowhere to be found!";
       }
 
  ?>


Simple use

  <?php
       // Set array
       $myArray[] = "John Doe";
       $myArray[] = "Jane Doe";
       $myArray[] = "James Doe";
       $myArray[] = "Donna Doe";
 
       //Read how many is in the array
       $arraySize = count($myArray);
 
       //Loop throw the array (knowing the size)
       for ($i=0;$i<$arraySize;$i++){
           print "Hi " . $myArray[$i] . "<br />";
       }
 
       //Loop throw the array (not knowing the size)
       foreach($myArray as $person){
           print "Hi to $person <br />";
       }
 
       //Show what myArray looks like
       print "<pre>";
       print_r($myArray);
       print "</pre>";
 
  ?>

Arrays can be used with names, allso known as Hash values
Simple use

  <?php
       // Set array
       $myArray['name'][] = "John Doe";
       $myArray['name'][] = "Jane Doe";
       $myArray['name'][] = "James Doe";
       $myArray['name'][] = "Donna Doe";
 
       $myArray['email'][] = "John.Doe@hotmail.com";
       $myArray['email'][] = "Jane.Doe@hotmail.com";
       $myArray['email'][] = "James.Doe@hotmail.com";
       $myArray['email'][] = "Donna.Doe@hotmail.com";
 
       //Read how many is in the array
       $arraySize = count($myArray['name']);
 
       //Loop throw the array (knowing the size)
       for ($i=0;$i<$arraySize;$i++){
           print "Hi " . $myArray['name'][$i] . " with email " . $myArray['email'][$i] . "<br />";
       }
 
       //Show what myArray looks like
       print "<pre>";
       print_r($myArray);
       print "</pre>";
 
  ?>

A MYSQL resultset like Array.
Simple use

  <?php
       // Set array
       $myArray[] = array(name=>'John Doe'  ,email=>'John.Doe@hotmail.com');
       $myArray[] = array(name=>'Jame Doe'  ,email=>'Jane.Doe@hotmail.com');
       $myArray[] = array(name=>'James Doe' ,email=>'James.Doe@hotmail.com');
       $myArray[] = array(name=>'Donnae Doe',email=>'Donna.Doe@hotmail.com');
 
       //Read how many is in the array
       $arraySize = count($myArray);
 
       //Loop throw the array (knowing the size)
       for ($i=0;$i<$arraySize;$i++){
           print "Hi " . $myArray[$i]['name'] . " with email " . $myArray[$i]['email'] . "<br />";
       }
 
       //Loop throw the array (not knowing the size)
       foreach($myArray as $person){
           print "Hi to " . $person['name'] . " with email " . $person['email'] . " <br />";
       }
 
       //Show what myArray looks like
       print "<pre>";
       print_r($myArray);
       print "</pre>";
 
  ?>

Search values in multidimensional array .

<?php 
 
//In this example i'll search for values. And i'll return the key name
 
function searchArray($array,$searchitem){
   $keyname ="";
   //Loop throw array
   foreach($array as $name => $value){
      //See if value is a new array
      if (is_array($value)){
          $keyname=searchArray($value,$searchitem);
          if ($keyname != "") return $keyname;
      } else {
       // the value is not a array but just a value.
       if ($value == $searchitem) {
          return $name; 
       }
      }
   }
   return $keyname;
}
 
 // create array 
 $names  = array('Michael'=>'Developer','James'=>'Contact');
 // create array 
 $emails  = array('Michael'=>'michael@server.com','James'=>'james@server.com');
 
 // appends arrays
 $people[] = $names;
 $people[] = $emails;
 
 //Find my name by email 
 $person_name = searchArray($people,'michael@server.com');
 
  print "the email michael@server.com is owned by  $person_name" ;
 
?>

php.home.build.functions

When your writing alot of PHP code. You will sometimes find your self repeating your code.
Then insted of having the same code twice. Then i might be a code idea to write a function for it.

Basic function sample

 
  function printMyName(){
     print "I dont know your name!";
  }

Basic function that takes argument sample

 
  function printMyName($yourname){
     print "Ohh hello " . $yourname;
  }

Basic function that have optional argument sample

 
  function printMyName($yourname=""){
     if ($yourname!="")
       print "Ohh hello " . $yourname;
     else 
       print "I can't tell you your  name. Unless you tell it to me!";
  }

Basic function that takes arguments, and answers back sample

 
  function printMyName($yourname){
     return "Ohh hello " . $yourname;
  }
 
  $sayHello=printMyName("John Doe"); // Now sayHello is = Ohh hello John Doe

Making a usefull function from “Send mail attachments” example

  <?php
 
   function sendEmail($to_email,$from_email,$subject,$text,$files=""){
 
     $filetype             = "application/octet-stream"; 
     $options              = "From: " . $from_email;
 
     $semi_rand = md5(time()); 
     $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
 
     //Write the mime message
     $options            .= "\nMIME-Version: 1.0";
     $options            .= "\nContent-Type: multipart/mixed;\n boundary=\"". $mime_boundary ."\"\n\n";
 
     $content            .= "This is a multi-part message in MIME format.\n\n";
     $content            .= "--$mime_boundary\n";
 
 
     // Adding the text
     $content          .= "Content-Type: text/html; charset=iso-8859-1\n";
     $content          .= "Content-Transfer-Encoding: 8bit\n\n";
     $content          .= $text . "\n\n";
 
     // check if $files is empty
     if ($files != "") { 
        // Se if $files is a array of files
        if (is_array($files)){      
          for($i=0;$i<count($files);$i++){
            //Read the file
            $handle         = fopen($files[$i], 'rb');
            $filecontents   = fread($handle, filesize($files[$i]));
            fclose($handle);
 
            //base64 encode the file
            $filecontents   = @base64_encode($filecontents);        
 
            // Adding the file
            $content          .= "--". $mime_boundary . "\n";
            $content          .= "Content-Type: application/octet-stream; name=\"" . basename($files[$i]) . "\"\n";
            $content          .= "Content-Transfer-Encoding: base64\n\n";
            $content          .= chunk_split($filecontents) . "\n\n";
          }
        } else {
          // $files is just a single file
          //Read the file
          $handle         = fopen($files, 'rb');
          $filecontents   = fread($handle, filesize($files));
          fclose($handle);
 
          //base64 encode the file
          $filecontents   = @base64_encode($filecontents);        
 
          // Adding the file
          $content          .= "--". $mime_boundary . "\n";
          $content          .= "Content-Type: application/octet-stream; name=\"" . basename($files) . "\"\n";
          $content          .= "Content-Transfer-Encoding: base64\n\n";
          $content          .= chunk_split($filecontents) . "\n\n";
        }
          // Add last mime_boundary
          $content          .= "--". $mime_boundary . "\n";
     }
 
     //Send the mail
     mail($to_email,$subject,$content,$options);
  }
 
 
   /*
   * Now you can use the function to send email 
   * with or without files
   */
 
   // Send a email with no attachment 
   sendEmail("john.doe@hotmail.com","jane.doe@hotmail.com","Hi John","How are you doing ?\n\nIt's been a while");
 
   // Send a email with sigle attachment 
   sendEmail("john.doe@hotmail.com","jane.doe@hotmail.com","Hi John","Have you seen this picture",$_SERVER["DOCUMENT_ROOT"] . "/images/johnAndJane.jpg");
 
   // Send a email with many attachment 
 
  $images[] = $_SERVER["DOCUMENT_ROOT"] . "/images/johnAndJane.jpg";
  $images[] = $_SERVER["DOCUMENT_ROOT"] . "/images/johnAndJack.jpg";
  $images[] = $_SERVER["DOCUMENT_ROOT"] . "/images/johnAndDonna.jpg";
  $images[] = $_SERVER["DOCUMENT_ROOT"] . "/images/johnAndJames.jpg";
  $images[] = $_SERVER["DOCUMENT_ROOT"] . "/images/johnFishing.jpg";
  $images[] = $_SERVER["DOCUMENT_ROOT"] . "/images/johnPlaying.jpg";
 
  sendEmail("john.doe@hotmail.com","jane.doe@hotmail.com","Hi John","Have you seen these pictures",$images);
 
 ?>
 
php_common_functions.txt · Last modified: 2007/09/06 10:33 by michael
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki