Saturday, 4 August 2012

Demo/About/Documentation geolocation API , IP address based Geolocation


Demo/About/Documentation geolocation API

The geolocation-feature implements the navigator.geolocation API. The following methods are available:

    navigator.getCurrentPosition: successCallback, errorCallback and options ({timeout: number}) are supported
    navigator.watchPosition: in shim identical to getCurrentPosition, except it returns an useless ID
    navigator.clearWatch: is noop in shim

The shim uses the geolocation information provided by http://freegeoip.net and/or googles API-Loader
Options for geolocation

    confirmText (string): confirm text for requesting access to geo data.

$.webshims.setOptions('geolocation', { confirmText: '{location} wants to know your position. It is Ok to press Ok.' }); navigator.geolocation.getCurrentPosition(function(pos){ alert("Thx, you are @ latitude: "+ pos.coords.latitude +"/longitude: " + pos.coords.longitude); });

The following code extracts illustrate how to obtain basic location information:

Example of a "one-shot" position request.

    function showMap(position) {
      // Show a map centered at (position.coords.latitude, position.coords.longitude).
    }

    // One-shot position request.
    navigator.geolocation.getCurrentPosition(showMap);
   

Example of requesting repeated position updates.

    function scrollMap(position) {
      // Scrolls the map so that it is centered at (position.coords.latitude, position.coords.longitude).
    }

    // Request repeated updates.
    var watchId = navigator.geolocation.watchPosition(scrollMap);

    function buttonClickHandler() {
      // Cancel the updates when the user clicks a button.
      navigator.geolocation.clearWatch(watchId);
    }
   

Example of requesting repeated position updates and handling errors.

    function scrollMap(position) {
      // Scrolls the map so that it is centered at (position.coords.latitude, position.coords.longitude).
    }

    function handleError(error) {
      // Update a div element with error.message.
    }

    // Request repeated updates.
    var watchId = navigator.geolocation.watchPosition(scrollMap, handleError);

    function buttonClickHandler() {
      // Cancel the updates when the user clicks a button.
      navigator.geolocation.clearWatch(watchId);
    }
   

Example of requesting a potentially cached position.

    // Request a position. We accept positions whose age is not
    // greater than 10 minutes. If the user agent does not have a
    // fresh enough cached position object, it will automatically
    // acquire a new one.
    navigator.geolocation.getCurrentPosition(successCallback,
                                             errorCallback,
                                             {maximumAge:600000});

    function successCallback(position) {
      // By using the 'maximumAge' option above, the position
      // object is guaranteed to be at most 10 minutes old.
    }

    function errorCallback(error) {
      // Update a div element with error.message.
    }

   

Forcing the user agent to return a fresh cached position.

    // Request a position. We only accept cached positions whose age is not
    // greater than 10 minutes. If the user agent does not have a fresh
    // enough cached position object, it will immediately invoke the error
    // callback.
    navigator.geolocation.getCurrentPosition(successCallback,
                                             errorCallback,
                                             {maximumAge:600000, timeout:0});

    function successCallback(position) {
      // By using the 'maximumAge' option above, the position
      // object is guaranteed to be at most 10 minutes old.
      // By using a 'timeout' of 0 milliseconds, if there is
      // no suitable cached position available, the user agent
      // will asynchronously invoke the error callback with code
      // TIMEOUT and will not initiate a new position
      // acquisition process.
    }

    function errorCallback(error) {
      switch(error.code) {
        case error.TIMEOUT:
          // Quick fallback when no suitable cached position exists.
          doFallback();
          // Acquire a new position object.
          navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
          break;
        case ... // treat the other error cases.
      };
    }

    function doFallback() {
      // No fresh enough cached position available.
      // Fallback to a default position.
    }
   

Forcing the user agent to return any available cached position.

    // Request a position. We only accept cached positions, no matter what
    // their age is. If the user agent does not have a cached position at
    // all, it will immediately invoke the error callback.
    navigator.geolocation.getCurrentPosition(successCallback,
                                             errorCallback,
                                             {maximumAge:Infinity, timeout:0});

    function successCallback(position) {
      // By setting the 'maximumAge' to Infinity, the position
      // object is guaranteed to be a cached one.
      // By using a 'timeout' of 0 milliseconds, if there is
      // no cached position available at all, the user agent
      // will immediately invoke the error callback with code
      // TIMEOUT and will not initiate a new position
      // acquisition process.
      if (position.timestamp < freshness_threshold &&
          position.coords.accuracy < accuracy_threshold) {
        // The position is relatively fresh and accurate.
      } else {
        // The position is quite old and/or inaccurate.
      }
    }

    function errorCallback(error) {
      switch(error.code) {
        case error.TIMEOUT:
          // Quick fallback when no cached position exists at all.
          doFallback();
          // Acquire a new position object.
          navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
          break;
        case ... // treat the other error cases.
      };
    }

    function doFallback() {
      // No cached position available at all.
      // Fallback to a default position.
    }
   
IP address based Geolocation

So now the obvious question is what about those browsers that don’t support geolocation at all? The answer is that we must use an external geolocation service. These services do their best to map the IP address of a device to geographic locations using large geolocation databases. Usually they do a good job, but at times they may suffer from the following issues:

    IP addresses may be associated with the wrong location (e.g., the wrong postal code, city or suburb within a metropolitan area).
    Addresses may be associated only with a very broad geographic area (e.g., a large city, or a state). Many addresses are associated only with a city, not with a street address or latitude/longitude location.
    Some addresses will not appear in the database and therefore cannot be mapped (often true for IP numbers not commonly used on the Internet).

The important thing to remember is that when an external geolocation service is used, the accuracy is not as good as geolocation native to the device, and in some scenarios it may be completely off. Additionally, such services do not provide any information regarding the altitude, speed or heading of the device. Regardless, when GPS or triangulation are not available, they are a good fallback.

YQL Geo Library is a dedicated and lightweight library that lets you perform geolocation using good old Yahoo services. This library can do other things which I’ll leave to you to discover, but for now let’s look at how we should modify our code to successfully detect the location on both supporting and non-supporting browsers:
view plaincopy to clipboardprint?

    <!DOCTYPE html>
    <html>
     
      <head>
      <script src="js/jquery-1.4.2.min.js"></script>
      <script src="js/yqlgeo.js"></script>
      <script>
        jQuery(window).ready(function(){
            jQuery("#btnInit").click(initiate_geolocation);
        })
     
        function initiate_geolocation() {
            if (navigator.geolocation)
            {
                navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
            }
            else
            {
                yqlgeo.get('visitor', normalize_yql_response);
            }
        }
     
        function handle_errors(error)
        {
            switch(error.code)
            {
                case error.PERMISSION_DENIED: alert("user did not share geolocation data");
                break;
     
                case error.POSITION_UNAVAILABLE: alert("could not detect current position");
                break;
     
                case error.TIMEOUT: alert("retrieving position timedout");
                break;
     
                default: alert("unknown error");
                break;
            }
        }
     
        function normalize_yql_response(response)
        {
            if (response.error)
            {
                var error = { code : 0 };
                handle_error(error);
                return;
            }
     
            var position = {
                coords :
                {
                    latitude: response.place.centroid.latitude,
                    longitude: response.place.centroid.longitude
                },
                address :
                {
                    city: response.place.locality2.content,
                    region: response.place.admin1.content,
                    country: response.place.country.content
                }
            };
     
            handle_geolocation_query(position);
        }
     
        function handle_geolocation_query(position){
            alert('Lat: ' + position.coords.latitude + ' ' +
                  'Lon: ' + position.coords.longitude);
            }
        </script>
     
      </head>
      <body>
        <div>
          <button id="btnInit" >Find my location</button>
        </div>
     
      </body>
    </html>

Tuesday, 31 July 2012

simple pagination code in php and mysql


<?php
/*
Place code to connect to your DB here.
*/
// include your code to connect to DB.

$tbl_name=""; //your table name
// How many adjacent pages should be shown on each side?
$adjacents = 3;

/*
  First get total number of rows in data table.
  If you have a WHERE clause in your query, make sure you mirror it here.
*/
$query = "SELECT COUNT(*) as num FROM $tbl_name";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];

/* Setup vars for query. */
$targetpage = "yourfilename.php"; //your file name  (the name of this file)
$limit = 2; //how many items to show per page
$page = $_GET['page'];
if($page)
$start = ($page - 1) * $limit; //first item to display on this page
else
$start = 0; //if no page var is given, set start to 0

/* Get data. */
$sql = "SELECT column_name FROM $tbl_name LIMIT $start, $limit";
$result = mysql_query($sql);

/* Setup page vars for display. */
if ($page == 0) $page = 1; //if no page var is given, default to 1.
$prev = $page - 1; //previous page is page - 1
$next = $page + 1; //next page is page + 1
$lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up.
$lpm1 = $lastpage - 1; //last page minus 1

/*
Now we apply our rules and draw the pagination object.
We're actually saving the code to a variable in case we want to draw it more than once.
*/
$pagination = "";
if($lastpage > 1)
{
$pagination .= "<div class=\"pagination\">";
//previous button
if ($page > 1)
$pagination.= "<a href=\"$targetpage?page=$prev\">« previous</a>";
else
$pagination.= "<span class=\"disabled\">« previous</span>";

//pages
if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
}
}
elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
if($page < 1 + ($adjacents * 2))
{
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
}
$pagination.= "...";
$pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
$pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";
}
//in middle; hide some front and some back
elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
{
$pagination.= "<a href=\"$targetpage?page=1\">1</a>";
$pagination.= "<a href=\"$targetpage?page=2\">2</a>";
$pagination.= "...";
for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
}
$pagination.= "...";
$pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
$pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";
}
//close to end; only hide early pages
else
{
$pagination.= "<a href=\"$targetpage?page=1\">1</a>";
$pagination.= "<a href=\"$targetpage?page=2\">2</a>";
$pagination.= "...";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
}
}
}

//next button
if ($page < $counter - 1)
$pagination.= "<a href=\"$targetpage?page=$next\">next »</a>";
else
$pagination.= "<span class=\"disabled\">next »</span>";
$pagination.= "</div>\n";
}
?>

<?php
while($row = mysql_fetch_array($result))
{

// Your while loop here

}
?>

<?php echo $pagination;?>

send php mail with submit form data and file attachment

careers.html

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 


<title>Untitled Document</title> 
</head> 

<body style="padding:3px; margin:0px;" bgcolor="#FFFFFF"> 
<table cellpadding="0" cellspacing="0" border="0" width="440"> 
    
    <tr><td style="height:10px"></td></tr> 
    <tr> 
      <td colspan="2" style="text-align:justify; line-height:15px;" class="body"> 
        
      <form name="frm" method="POST" action="careersuccess.php" enctype="multipart/form-data"> 
      <table cellpadding="0" cellspacing="0" border="0" width="100%"> 
          <tr> 
            <td width="23%" class="body"> Name</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><input type="text" name="strname" class="textfield"></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> Address</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><textarea cols="16" name="straddress"></textarea></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> City</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><input type="text" name="strcity" class="textfield"></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> State</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><input type="text" name="strstate" class="textfield"></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> Contact No</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><input type="text" name="strno" class="textfield"></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> Email</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><input type="text" name="stremail" class="textfield"></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> Comments</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><textarea cols="16" name="strcomments"></textarea></td> 
        </tr> 
        <tr><td style="height:3px"></td></tr> 
        <tr> 
            <td width="23%" class="body"> Resume</td> 
            <td width="3%" class="body">:</td> 
            <td width="74%"><input type="file" name="strresume"></td> 
        </tr> 
        <tr><td style="height:10px"></td></tr> 
        <tr> 
            <td colspan="3" align="center"> 
                <input type="submit" value="Send" name="submit" onClick="return validate();"> <input type="reset" value="Reset" name="reset"> 
            </td> 
        </tr> 
        
      </table>    
     </form> 

</td> 
    </tr> 
    <tr> 
      <td colspan="2" align="center"> </td> 
  </tr> 
    </table> 
</body> 
</html>




careersuccess.php

<?php 
      
                      
       $strname
=ucfirst($_REQUEST["strname"]); 
    
$straddress=ucfirst($_REQUEST["straddress"]); 
    
$strcity=ucfirst($_REQUEST["strcity"]); 
    
$strstate=ucfirst($_REQUEST["strstate"]);        
        
       
$phone=$_REQUEST["strno"]; 
       if(
$phone != ""){ $strno=$phone; } else { $strno="-"; }    
        
    
$stremail=$_REQUEST["stremail"];    
    
$strcomments=ucfirst($_REQUEST["strcomments"]); 

    
    
$filename=$_FILES["strresume"]["name"]; 
    
$filetype=$_FILES["strresume"]["type"]; 
    
$filesize=$_FILES["strresume"]["size"]; 
    
$filetemp=$_FILES["strresume"]["tmp_name"]; 


        
    if(
$filetype=="application/octet-stream" or $filetype=="text/plain" or $filetype=="application/msword") 
    { 
    
        
$message= ' 
    
    
            <table cellspacing="0" cellpadding="8" border="0" width="400"> 
            <tr> 
                <td colspan="2"></td> 
            </tr> 
            <tr bgcolor="#eeeeee"> 
                <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>Name</strong></td> 
                <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$strname.'</td> 
            </tr> 
            <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
            <tr bgcolor="#eeeeee"> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>Address</strong></td> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$straddress.'</td> 
              </tr> 
            <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
            <tr bgcolor="#eeeeee"> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>City</strong></td> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$strcity.'</td> 
              </tr> 
              <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
            <tr bgcolor="#eeeeee"> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>State</strong></td> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$strstate.'</td> 
              </tr> 
              <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
            <tr bgcolor="#eeeeee"> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>Contact No.</strong></td> 
              <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$strno.'</td> 
              </tr> 
            <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
            <tr bgcolor="#eeeeee"> 
                <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>Email</strong></td> 
                <td style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$stremail.'</td> 
            </tr> 
            <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
            
            <tr bgcolor="#eeeeee"> 
                <td colspan="2" style="font-family:Verdana, Arial; font-size:11px; color:#333333;"><strong>Comments</strong></td> 
            </tr>                
            <tr bgcolor="#eeeeee"> 
                <td colspan="2" style="font-family:Verdana, Arial; font-size:11px; color:#333333;">'
.$strcomments.'</td> 
            </tr>                
                                    
            <tr><td colspan="2" style="padding:0px;"><img src="images/whitespace.gif" alt="" width="100%" height="1" /></td></tr> 
         </table> 


            

'
; 

    
// MAIL SUBJECT 

    
$subject = "Mail with doc file attachment"; 
    
    
// TO MAIL ADDRESS 
    
    
    
$to="to@mail.com"; 
/* 
    // MAIL HEADERS 
                        
    $headers  = "MIME-Version: 1.0\n"; 
    $headers .= "Content-type: text/html; charset=iso-8859-1\n"; 
    $headers .= "From: Name <name@name.com>\n"; 

*/ 
  


    // MAIL HEADERS with attachment 

    
$fp = fopen($strresume, "rb"); 
    
$file = fread($fp, $strresume_size); 

    
$file = chunk_split(base64_encode($file)); 
    
$num = md5(time()); 
    
        
//Normal headers 

    
$headers  = "From: Name<name@name.com>\r\n"; 
       
$headers  .= "MIME-Version: 1.0\r\n"; 
       
$headers  .= "Content-Type: multipart/mixed; "; 
       
$headers  .= "boundary=".$num."\r\n"; 
       
$headers  .= "--$num\r\n"; 

        
// This two steps to help avoid spam    

    
$headers .= "Message-ID: <".$now." TheSystem@".$_SERVER['SERVER_NAME'].">\r\n"; 
    
$headers .= "X-Mailer: PHP v".phpversion()."\r\n";          

        
// With message 
        
    
$headers .= "Content-Type: text/html; charset=iso-8859-1\r\n"; 
       
$headers .= "Content-Transfer-Encoding: 8bit\r\n"; 
       
$headers .= "".$message."\n"; 
       
$headers .= "--".$num."\n";  

        
// Attachment headers 

    
$headers  .= "Content-Type:".$strresume_type." "; 
       
$headers  .= "name=\"".$strresume_name."\"r\n"; 
       
$headers  .= "Content-Transfer-Encoding: base64\r\n"; 
       
$headers  .= "Content-Disposition: attachment; "; 
       
$headers  .= "filename=\"".$strresume_name."\"\r\n\n"; 
       
$headers  .= "".$file."\r\n"; 
       
$headers  .= "--".$num."--"; 

    
    
    
// SEND MAIL 
        
       
@mail($to, $subject, $message, $headers); 
    

     
fclose($fp); 

    echo 
'<font style="font-family:Verdana, Arial; font-size:11px; color:#333333; font-weight:bold">Attachment has been sent Successfully.<br /></font>'; 
} 
else 
    { 
        echo 
'<font style="font-family:Verdana, Arial; font-size:11px; color:#F3363F; font-weight:bold">Wrong file format. Mail was not sent.</font>'; 
        
//echo "<script>window.location.href='careers.html';</script>"; 
    
} 
?>

How to Use a PHP Session ,assign form values to session variable


A session is a way to store information (in the form of variables) to be used across multiple pages. Unlike a cookie, specific variable information is not stored on the users computer. It is also unlike other variables in the sense that we are not passing them individually to each new page, but instead retrieving them from the session we open at beginning of each page.

Call this code mypage.php

 <?php
 // this starts the session
 session_start();

 // this sets variables in the session
 $_SESSION['color']='red';
 $_SESSION['size']='small';
 $_SESSION['shape']='round';
 print "Done";
 ?>

The first thing we do with this code, is open the session using session_start(). We then set our first session variables (color, size and shape) to be red, small and round respectively.

Just like with our cookies, the session_start() code must be in the header and you can not send anything to the browser before it. It's best to just put it directly after the <?php to avoid potential problems.

So how will it know it's me? Most sessions set a cookie on your computer to uses as a key... it will look something like this: 350401be75bbb0fafd3d912a1a1d5e54. Then when a session is opened on another page, it scans your computer for a key. If there is a match, it accesses that session, if not it starts a new session for you.

Now we are going to make a second page. We again will start with session_start() (we need this on every page) - and we will access the session information we set on our first page. Notice we aren't passing any variables, they are all stored in the session.

Call this code mypage2.php

 <?php
 // this starts the session
 session_start();

 // echo variable from the session, we set this on our other page
 echo "Our color value is ".$_SESSION['color'];
 echo "Our size value is ".$_SESSION['size'];
 echo "Our shape value is ".$_SESSION['shape'];
 ?>

All of the values are stored in the $_SESSION array, which we access here. Another way to show this is to simply run this code:

 <?php
 session_start();
 Print_r ($_SESSION);
 ?>

You can also store an array within the session array. Let's go back to our mypage.php file and edit it slightly to do this:

 <?php
 session_start();

 // makes an array
 $colors=array('red', 'yellow', 'blue');
 // adds it to our session
 $_SESSION['color']=$colors;
 $_SESSION['size']='small';
 $_SESSION['shape']='round';
 print "Done";
 ?>

Now let's run this on mypage2.php to show our new information:

 <?php
 session_start();
 Print_r ($_SESSION);
 echo "<p>";

 //echo a single entry from the array
 echo $_SESSION['color'][2];
 ?>

 <?php
 // you have to open the session to be able to modify or remove it
 session_start();

 // to change a variable, just overwrite it
 $_SESSION['size']='large';

 //you can remove a single variable in the session
 unset($_SESSION['shape']);

 // or this would remove all the variables in the session, but not the session itself
 session_unset();

 // this would destroy the session variables
 session_destroy();
 ?>

Sunday, 29 July 2012

why use php for web development


 Open source: PHP is a server side open source language which means it is available for free. It can be used on different platforms such as UNIX, Linux & Windows and considered the suitable language to develop dynamic sites.

Dynamic language: PHP is used in close correlation with HTML for displaying dynamic data and other elements on a web page. The code available within the delimiters is parsed and all other information is ignored by PHP and sent directly to output.

Less use of resources: PHP and the related procedures do not require too much from system resources. The processes and functions load as well as execute quickly since PHP makes use of Apache modules developed in C coding language.

Dynamic CMS: Development using PHP has made management of content on a web site very simple as entire content on the web site is kept in a database server and fetched by developers as and when required.

1. Ease of use

As stated above, this language has proven to many, to be very easy to learn, very straight-forward. The language rules are not as strict as many common languages of now days, such as C++, Java etc. Any newcomer to the world of PHP will get the hang of this language very quickly on my opninion.

2. Integrates with HTML, CSS, javascript, ajax, jquery very well.

When speaking of web development, there is no need to create workarounds to be able to display an HTML page when using PHP. All you have to do is place the HTML, CSS, js, etc… within the file and you are good to go.

3. Well documented

Nothing is complete if it lacks documentation. This language contains their full manual online, and accessible to everyone in need of it. You need to learn something you have never done before? Just google it and you will definately find some crazy person that already went through the hassle for you, and is willing to help you out at the same time.

4. Great community

Our communities are huge! The people have supported this language from the very start. Versed in every aspect, you can see how people strive to get more out of this simple language (yet powerful). This being open source, has the advantage that everyone can take a glance at it. That being said, with more exposure, the more opportunity this has of growing. Believe me, this has grown since the beggining, and it will keep growing.

5. Updated regularly (security etc, solid platform).

Great technology needs to be updated constantly. The team at PHP.net have done a tremendous job in keeping their language up to date with all the bugs that have been found so far. Also, adding new features every once in a while to make our lives as programmers a bit much easier.

6. Database communication is excellent

PHP is known to have a variety of database support. It has enough flavors to satisfy most individual needs. Here I found a list of supported databases so far. I’m not sure how accurate it is, but its good enough.

http://phplens.com/adodb/supported.databases.html

7. Trend, a lot of people use it (widely used, for open source projects like WP, Joomla, PHPBB, etc.)

This language has become very trendy. A lot of web developers prefer using PHP. (Note: I said a lot prefer, not all.) If you decide to start a new career path using PHP, then you will most certainly have a place to go. The job market is stacking with PHP developer roles, and PHP leads, etc. This is an actual fact, due to the reports from craigslist, stating that the job growth for PHP web developer has increased within the past year. Also, there are a lot of open source projects like WordPress, Joomla, Drupal to mention a few, and companies are using these more and more each day.

8. Usability

One of the best things is that applications done within PHP are cross platform. They are indipendently ran on a server, and doesn’t matter what type of Operating system you are using, it is likely to run. In some cases you will just need to add a few conditions and manipulate the design a little bit, but having to create a new one from scratch, just because there is no compatibility, negatory!

9. Best of all, its free!

You definately can’t go wrong with FREE! You know the old saying, “If it’s free, it’s for me!”. Some people prefer to pay for some web server, that will cost thousands of dollars to maintain up to date. Not with PHP though, you can install a free operating system (linux, unix), that is also very well documented, and have PHP installed in it, configured, and maintainable for much lower cost than any other type of OS.

Some other features of PHP development include:

    Easy access to coding libraries
    Open source programming
    Availability of server interfaces
    Use of different databases such as Oracle, MySQL, PostgreSQL, etc
    Similarity to Java and C
    Platform compatibility

Friday, 27 July 2012

most useful array function in php



Function
Explanation
Example
sizeof($arr)
This function returns the number of elements in an array.
Use this function to find out how many elements an array contains; this information is most commonly used to initialize a loop counter when processing the array.
Code:
$data = array("red", "green", "blue");

echo "Array has " . sizeof($data) . " elements";
?>

Output:
Array has 3 elements
array_values($arr)
This function accepts a PHP array and returns a new array containing only its values (not its keys). Its counterpart is the array_keys() function.
Use this function to retrieve all the values from an associative array.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_values($data));
?>

Output:
Array
(
[0] => Holmes
[1] => Moriarty
)
array_keys($arr)
This function accepts a PHP array and returns a new array containing only its keys (not its values). Its counterpart is the array_values() function.
Use this function to retrieve all the keys from an associative array.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_keys($data));
?>

Output:
Array
(
[0] => hero
[1] => villain
)
array_pop($arr)
This function removes an element from the end of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_pop($data);
print_r($data);
?>

Output:
Array
(
[0] => Donald
[1] => Jim
)
array_push($arr, $val)
This function adds an element to the end of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_push($data, "Harry");
print_r($data);
?>

Output:
Array
(
[0] => Donald
[1] => Jim
[2] => Tom
[3] => Harry
)
array_shift($arr)
This function removes an element from the beginning of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_shift($data);
print_r($data);
?>

Output:
Array
(
[0] => Jim
[1] => Tom
)
array_unshift($arr, $val)
This function adds an element to the beginning of an array.
Code:
$data = array("Donald", "Jim", "Tom");
array_unshift($data, "Sarah");
print_r($data);
?>

Output:
Array
(
[0] => Sarah
[1] => Donald
[2] => Jim
[3] => Tom
)
each($arr)
This function is most often used to iteratively traverse an array. Each time each() is called, it returns the current key-value pair and moves the array cursor forward one element. This makes it most suitable for use in a loop.
Code:
$data = array("hero" => "Holmes", "villain" => "Moriarty");
while (list($key, $value) = each($data)) {
echo "$key: $value \n";
}
?>

Output:
hero: Holmes
villain: Moriarty
sort($arr)
This function sorts the elements of an array in ascending order. String values will be arranged in ascending alphabetical order.
Note: Other sorting functions include asort(), arsort(), ksort(), krsort() and rsort().
Code:
$data = array("g", "t", "a", "s");
sort($data);
print_r($data);
?>

Output:
Array
(
[0] => a
[1] => g
[2] => s
[3] => t
)
array_flip($arr)
The function exchanges the keys and values of a PHP associative array.
Use this function if you have a tabular (rows and columns) structure in an array, and you want to interchange the rows and columns.
Code:
$data = array("a" => "apple", "b" => "ball");
print_r(array_flip($data));
?>

Output:
Array
(
[apple] => a
[ball] => b
)
array_reverse($arr)
The function reverses the order of elements in an array.
Use this function to re-order a sorted list of values in reverse for easier processing—for example, when you're trying to begin with the minimum or maximum of a set of ordered values.
Code:
$data = array(10, 20, 25, 60);
print_r(array_reverse($data));
?>

Output:
Array
(
[0] => 60
[1] => 25
[2] => 20
[3] => 10
)
array_merge($arr)
This function merges two or more arrays to create a single composite array. Key collisions are resolved in favor of the latest entry.
Use this function when you need to combine data from two or more arrays into a single structure—for example, records from two different SQL queries.
Code:
$data1 = array("cat", "goat");
$data2 = array("dog", "cow");
print_r(array_merge($data1, $data2));
?>

Output:
Array
(
[0] => cat
[1] => goat
[2] => dog
[3] => cow
)
array_rand($arr)
This function selects one or more random elements from an array.
Use this function when you need to randomly select from a collection of discrete values—for example, picking a random color from a list.
Code:
$data = array("white", "black", "red");
echo "Today's color is " . $data[array_rand($data)];
?>

Output:
Today's color is red
array_search($search, $arr)
This function searches the values in an array for a match to the search term, and returns the corresponding key if found. If more than one match exists, the key of the first matching value is returned.
Use this function to scan a set of index-value pairs for matches, and return the matching index.
Code:
$data = array("blue" => "#0000cc", "black" => "#000000", "green" => "#00ff00");
echo "Found " . array_search("#0000cc", $data);
?>

Output:
Found blue
array_slice($arr, $offset, $length)
This function is useful to extract a subset of the elements of an array, as another array. Extracting begins from array offset $offset and continues until the array slice is $length elements long.
Use this function to break a larger array into smaller ones—for example, when segmenting an array by size ("chunking") or type of data.
Code:
$data = array("vanilla", "strawberry", "mango", "peaches");
print_r(array_slice($data, 1, 2));
?>

Output:
Array
(
[0] => strawberry
[1] => mango
)
array_unique($data)
This function strips an array of duplicate values.
Use this function when you need to remove non-unique elements from an array—for example, when creating an array to hold values for a table's primary key.
Code:
$data = array(1,1,4,6,7,4);
print_r(array_unique($data));
?>

Output:
Array
(
[0] => 1
[3] => 6
[4] => 7
[5] => 4
)
array_walk($arr, $func)
This function "walks" through an array, applying a user-defined function to every element. It returns the changed array.
Use this function if you need to perform custom processing on every element of an array—for example, reducing a number series by 10%.
Code:
function reduceBy10(&$val, $key) {
$val -= $val * 0.1;
}

$data = array(10,20,30,40);
array_walk($data, 'reduceBy10');
print_r($data);
?>

Output:
Array
(
[0] => 9
[1] => 18
[2] => 27
[3] => 36
)