5 PHP MUST WANTED CODE SNIPPETS FOR EVERY WEB DEVELOPERS NEED

Every web developer should keep useful code snippets in a personal library for future reference.In this post we will show you some useful code snippets of PHP which will help you for your future projects.

TOP 5 PHP MUST WANTED CODE SNIPPETS FOR EVERY WEB DEVELOPERS NEED

Show Number Of People Who Liked Your Facebook Page

function fb_fan_count($facebook_name)
{
    $data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
    $likes = $data->likes;
    return $likes;
}

SyntaX

<?php
$page = "smartwebcare";
$count = fb_fan_count($page);
echo $count;
?>

Sending an Email With MANDRILL

For the below function you would have to put a file “Mandrill.php” in the same folder as the PHP file you would be using to send emails.

function send_email($to_email,$subject,$message1)
{
	require_once 'Mandrill.php';
$apikey = 'XXXXXXXXXX'; //specify your api key here
$mandrill = new Mandrill($apikey);
 
$message = new stdClass();
$message->html = $message1;
$message->text = $message1;
$message->subject = $subject;
$message->from_email = "blog@smartwebcare.com";//Sender Email
$message->from_name  = "Smart Web Care";//Sender Name
$message->to = array(array("email" => $to_email));
$message->track_opens = true;
 
$response = $mandrill->messages->send($message);
}

In the above code you would have to specify your own api key that you get from your Mandrill account.

Syntax

<?php
$to = "abc@smartwebcare.com";
$subject = "This is a test email";
$message = "Hello World!";
send_email($to,$subject,$message);
?>

Zipping a File

function create_zip($files = array(),$destination = '',$overwrite = false) {  
    //if the zip file already exists and overwrite is false, return false  
    if(file_exists($destination) && !$overwrite) { return false; }  
    //vars  
    $valid_files = array();  
    //if files were passed in...  
    if(is_array($files)) {  
        //cycle through each file  
        foreach($files as $file) {  
            //make sure the file exists  
            if(file_exists($file)) {  
                $valid_files[] = $file;  
            }  
        }  
    }  
    //if we have good files...  
    if(count($valid_files)) {  
        //create the archive  
        $zip = new ZipArchive();  
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {  
            return false;  
        }  
        //add the files  
        foreach($valid_files as $file) {  
            $zip->addFile($file,$file);  
        }  
        //debug  
        //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;  
          
        //close the zip -- done!  
        $zip->close();  
          
        //check to make sure the file exists  
        return file_exists($destination);  
    }  
    else  
    {  
        return false;  
    }  
}

Syntax

<?php
$files=array('file1.jpg', 'file2.jpg', 'file3.gif');  
create_zip($files, 'myzipfile.zip', true); 
?>

PHP Snippets For Directory Listing

Using the below PHP code snippet you would be able to list all files and folders in a directory.

function list_files($dir)
{
    if(is_dir($dir))
    {
        if($handle = opendir($dir))
        {
            while(($file = readdir($handle)) !== false)
            {
                if($file != "." &amp;&amp; $file != ".." &amp;&amp; $file != "Thumbs.db"/*pesky windows, images..*/)
                {
                    echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."n";
                }
            }
            closedir($handle);
        }
    }
}

Syntax

<?php
    list_files("images/"); //This will list all files of images folder
?>

Creating  A CSV File From PHP ARRAY

function generateCsv($data, $delimiter = ',', $enclosure = '"') {
   $handle = fopen('php://temp', 'r+');
   foreach ($data as $line) {
		   fputcsv($handle, $line, $delimiter, $enclosure);
   }
   rewind($handle);
   while (!feof($handle)) {
		   $contents .= fread($handle, 8192);
   }
   fclose($handle);
   return $contents;
}

Syntax

<?php
$data[0] = "apple";
$data[1] = "oranges";
generateCsv($data, $delimiter = ',', $enclosure = '"');
?>

 

ARRAY in PHP Beginners guide

In this article we are going to discuss ARRAY in PHP Beginners guide. Arrays are wonderful ways to organize and use data in PHP. Array is Collection of different variables under the same label to keep values organized and easily accessible for processing. Here’s a quick example of an array of types of transportation:

$transportation = array( ‘Planes’, ‘Trains’, ‘Automobiles’ );

We use $ sign to give an array name like we do for variables. after that an equal sign and then keyword ‘array’ that tells the parser that we are working with arrays and then different values within parenthesis and each value enclosed in double or single quotes separated by comma.

Printing Array Items

$Top3Sites = array ("w3schools.com","smartwebcare.com","google.com");
print_r($Top3Sites);
?>
The output of the above programme will be.
Array
(
[0] => w3schools.com
[1] => smartwebcare.com
[2] => google.com
)

Please note that we use print_r to print an array because you cannot print an array with echo or print function (both are used to display output) though you can use echo or print to display single items from the array e.g.:
echo $Top3Sites[1]; //w3code.in
Remember that the index number starts from 0 and not 1.
Each value of the array get a unique ID which is known as INDEX NUMBER.

Types Of Arrays:

There are three different types of arrays in PHP:
a) Numeric Array: An array with a numeric ID key.
b) Associative Array: An array where each ID key is associated with a value.
c) Multidimensional Array: An array containing one or more arrays.

Numeric Arrays:

Numeric arrays use integer / numbers as their index number to identify each item of the array. The example we discussed above are numeric arrays as they have integer values as index numbers for each item.

Associative Arrays:

Sometimes it’s better to use the index name instead of index number. When you submit a form using POST or GET method you get associative array on the receiving page that contains the name of each form field as array index and its value as index value. Associative Arrays are more easy to handle and to process information especially dealing with complex form submission and dynamic values from database etc.

Multidimensional Arrays:

A multidimensional array is one where the items in an array are themselves arrays. Here’s an example:

$staff = array(
0 => array(
[‘Name’] => ‘Jonney Robot’,
[‘Position’] => ‘Reader’
),
1 => array(
[‘Name’] => ‘Rahul Gambhir’,
[‘Position’] => ‘Writer’
)
);

There we have a $staff array with multiple people in it. We could do multiple foreach functions to iterate over each of those people like this:

foreach( $staff as $key => $person ) {
    echo ‘<ul>’;
        foreach( $person as $attribute => $value ) {
            echo ‘<li>’ . $attribute . ‘:’ . $value . ‘</li>’;
        }
    echo ‘</ul>’;
}

In the above example I looped through each person, and within each person I looped through their attributes and printed them. You can make up whatever variable names you wish, there’s nothing magic about the names. I tried to name mine in a way that made sense according to the contents.

Arrays are a very deep topic and it has a lot more to discuss and even I can easily write a complete book on arrays only. But the aim of this article is to give you very sound understanding of arrays and different methods to store and process information in arrays.