Wednesday, 20 April 2011

PHP – Take advantage of language constructs



  • Fastest things in PHP are the language constructs.




  • They are highly optimized in the interpreter




  • Don’t require calling external libraries




  • Don’t call a function if there is a language construct. As an example, using a casting operator like (int) $total is much more efficient than using the function intval($foo)




  • Function calling generate considerably amount of overhead. Using a language construct avoid




  • isset() and unset() are both language constructs, even though they mostly act like functions. However calling them does not generate the function overhead.




Some common language constructs are:





  1. echo()




  2. empty()




  3. isset()




  4. unset()




  5. eval()




  6. exit()




  7. die()




  8. include()




  9. include_once()




  10. require()




  11. require_once()




  12. return



What is Web Service?

Web Services is a generic umbrella that describes how disparate systems can integrate with each other over the web.
Most major sites offer some form of web services:
– Amazon
FedEx
eBay
– PayPl
– del.icio.us

Why use Web Services?

  • Someone else has data you need

  • Easier than scraping pages also more reliable

  • Automate processes

  • Provide additional information to your clients


REST

REST Request

http://library.example.com/api.php?devkey=123&action=search&type=book&keyword=style

After the request, we will get the answer or response as an XML file. we can simple parse them using PHP’s SimpleXMLElement (SAX API) or DOM API to retrieve data

Zend Framework for developing Web Application using PHP

There are many frameworks for developing web applications using PHP. CodeIgniter, CakePHP, Symphony and more.. I’ve not much experience in all the frameworks. I’ve a good experience in using CodeIgniter and some small MVC frameworks.

Recently I am Working on Zend Framework .  I noticed Zend Framework is a nice framework to develop web application. Zend finally give special notice to develop a very good framework. And I hope very soon, Zend Framework will lead among all. I found this framework is very essential and powerful.

Recently,

What is Zend Framework?

  1. Zend Framework is a simple, straightforward, open-source software framework for PHP 5 designed to eliminate the tedious details of coding and let you focus on the big picture.

  2. It follows Model-View-Controller (MVC)

  3. ZF follows good coding-convention.


Documentation:
Documentation is really rich. Its not take much time to grasp a basic concept of this framework to develop application. Because there is quick start, api documentation, component based documentation. Overall I rate 10 out of 10 grade in documentation.

Goals of Zend Framework Components:


  1. Zend_Acl


    Zend_Acl provides lightweight and flexible access control list (ACL) functionality and privileges management.


  2. Zend_Auth


    Zend_Auth provides an API for authentication and includes concrete authentication adapters for common use case scenarios, as well as “Identity 2.0″ adapters such as OpenID and Microsoft InfoCard.


  3. Zend_Cache


    Zend_Cache provides a flexible approach toward caching data, including support for tagging, manipulating, iterating, and removing subsets.


  4. Zend_Config


    Zend_Config simplifies the use of configuration data for web applications.


  5. Zend_Controller and Zend_View


    These components provide the infrastructure for a Model-View-Controller (MVC) website.


  6. Zend_Date


    Zend_Date offers a detailed but simple API for manipulating dates and times.


  7. Zend_Db


    This is a lightweight database access layer, providing an interface to PDO and other database extensions in PHP. It includes adapters for each database driver, a query profiler, and an API to construct most SELECT statements.


  8. Zend_Db_Table


    The Zend_Db_Table component is a lightweight solution for object-oriented programming with databases.


  9. Zend_Feed


    This component provides a very simple way to work with live syndicated feeds.


  10. Zend_Filter and Zend_Validate


    These components encourage the development of secure websites by providing the basic tools necessary for input filtering and validation.


  11. Zend_Filter_Input


    This is a configurable solution for declaring and enforcing filtering and validation rules. This component serves as a “cage” for input data, so they are available to your application only after being validated.


  12. Zend_Form


    This component provides an object-oriented interface for building forms, complete with input filtering and rendering capabilities.


  13. Zend_Gdata (Zend Google Data Client)


    The Google Data APIs provide read/write access to such services hosted at google.com as Spreadsheets, Calendar, Blogger, and CodeSearch.


  14. Zend_Http_Client


    This component provides a client for the HTTP protocol, without requiring any PHP extensions. It drives our web services components.


  15. Zend_Json


    Easily convert PHP structures into JSON and vice-versa for use in AJAX-enabled applications.


  16. Zend_Layout


    Easily provide sitewide layouts for your MVC applications.


  17. Zend_Loader


    Load files, classes, and resources dynamically in your PHP application.


  18. Zend_Locale


    Zend_Locale is the Framework’s answer to the question, “How can the same application be used around the whole world?” This component is the foundation of Zend_Date, Zend_Translate, and others.


  19. Zend_Log


    Log data to the console, flat files, or a database. Its no-frills, simple, procedural API reduces the hassle of logging to one line of code and is perfect for cron jobs and error logs.


  20. Zend_Mail and Zend_Mime


    Almost every Internet application needs to send email. Zend_Mail, assisted by Zend_Mime, creates email messages and sends them.


  21. Zend_Measure


    Using Zend_Measure, you can convert measurements into different units of the same type. They can be added, subtracted, and compared against each other.


  22. Zend_Memory


    Zend_Memory offers an API for managing data in a limited memory mode. A PHP developer can create a Zend_Memory object to store and access large amounts of data, which would exceed the memory usage limits imposed by some PHP environments.


  23. Zend_Pdf


    Portable Document Format (PDF) from Adobe is the de facto standard for cross-platform rich documents. Now, PHP applications can create or read PDF documents on the fly, without the need to call utilities from the shell, depend on PHP extensions, or pay licensing fees. Zend_Pdf can even modify existing PDF documents.


  24. Zend_Registry


    The registry is a container for storing objects and values in the application space. By storing an object or value in the registry, the same object or value is always available throughout your application for the lifetime of the request. This mechanism is often an acceptable alternative to using global variables.


  25. Zend_Rest_Client and Zend_Rest_Server


    REST Web Services use service-specific XML formats. These ad-hoc standards mean that the manner for accessing a REST web service is different for each service. REST web services typically use URL parameters (GET data) or path information for requesting data and POST data for sending data.


  26. Zend_Search_Lucene


    The Apache Lucene engine is a powerful, feature-rich Java search engine that is flexible about document storage and supports many complex query types. Zend_Search_Lucene is a port of this engine written entirely in PHP 5.


  27. Zend_Service: Akismet, Amazon, Audioscrobbler, Delicious, Flickr, Nirvanix, Simpy, StrikeIron and Yahoo!


    Web services are important to the PHP developer creating the next generation of mashups and composite applications. The Zend Framework provides wrappers for service APIs from major providers to make it as simple as possible to use those web services from your PHP application.


  28. Zend_Session


    Zend_Session helps manage and preserve session data across multiple page requests by the same client.


  29. Zend_Translate


    The Zend_Translate component provides the Zend Framework with message translation functionality.


  30. Zend_Uri


    Zend_Uri is a component that aids in manipulating and validating Uniform Resource Identifiers (URIs). Zend_Uri exists primarily to service other components such as Zend_Http_Client but is also useful as a standalone utility.


  31. Zend_XmlRpc


    Zend_XmlRpc makes it easy to communicate with and create XML-RPC services from PHP.

Easy way to data filter and validate in php

Before php 5.2.0 when we have to validate or filter user data, we normally use regex and some php functions. Some of those regex are difficult to understand. So normally most of the coders search in google to collect the correct regex to validate data and also use some php functions to filter data.


In php 5.2.0 a new extension is provided named filter to make these filter tasks much easy.  You can install it in your linux distro by simply typing in shell  pecl install filter


Before proceeding next at first check the available filters in your system:


echo'<pre>';


print_r(filter_list());


echo'</pre>';


Output in my system:


Array


(


    [0] => int


    [1] => boolean


    [2] => float


    [3] => validate_regexp


    [4] => validate_url


    [5] => validate_email


    [6] => validate_ip


    [7] => string


    [8] => stripped


    [9] => encoded


    [10] => special_chars


    [11] => unsafe_raw


    [12] => email


    [13] => url


    [14] => number_int


    [15] => number_float


    [16] => magic_quotes


    [17] => callback


)


filter_list() is a method that returns a list of all supported filters.



Validate Email address


Normally we validate email address like this way


$email= "viral.solani@gmail.com";


if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {


  echo"Valid email address.";


}


else{


  echo"Invalid email address.";


}


But using php’s filter functions you can easily verify that


$email  = "viral.solani@gmail.com";


 if(filter_var($email, FILTER_VALIDATE_EMAIL)){


      echo" $email is valid email address <br />";


 }


 $email= "viral.solani@gmail.com"; 


if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){


      echo" $email is not a valid email address <br />";


 }


Output


viral.solani@gmail.com is valid email address


viral.solani@gmail,com is not a valid email address


So using filter_var() and its parameters you can easily validate email, url, ip address and more.


Check this link to learn what type of data you can validate via filter functions. Normally FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_INT,FILTER_VALIDATE_URL, FILTER_VALIDATE_IP are mostly used.



Data Sanitization


Data sensitization is very important. As a coder never trust user’s input. User may push SQL injection code or javascript code. So always validate or sanitize data before use. To sanitize data you can use the same filter functions but you have to only provide sanitize filters as second parameter. Some commonly used sanitize filters are:



FILTER_SANITIZE_EMAIL
FILTER_SANITIZE_NUMBER_FLOAT
FILTER_SANITIZE_NUMBER_INT
FILTER_SANITIZE_SPECIAL_CHARS
FILTER_SANITIZE_STRING
FILTER_SANITIZE_URL
FILTER_SANITIZE_ENCODED

You’ll see detail list and description from here. For example to get valid string from user input


$userData= array(


               '<b>bold</b>',


               "<script>javascript alert('hi');</script>",


               'P*}i@893746%%%p*.i.*}}|.dw<?php echo "echo works!!";?>'


           );


   $myinputs= filter_var_array($userData, FILTER_SANITIZE_STRING);


   echo'<pre>';


   print_r($myinputs);


   echo'</pre>';


output


Array


(


    [0] => bold


    [1] => javascript alert('hi');


    [2] => P*}i@893746%%%p*.i.*}}|.dw


)


filter_var_array() is used to get multiple variables and optionally filters them. And this function is very useful for retrieving many values without repetitively callingfilter_var().

Friday, 4 March 2011

Automatically refresh the web page every 5 seconds, with PHP

Redict the web page with PHP

you can easily redirect to the different web page using simple php script.By using PHP header() function you can easily redirect to new page without having new extra clicks.

the following PHP script redirect the user to bugphp.com











1<?php










2header( 'Location: http://www.bugphp.com/' ) ;










3?>




make sure,it will not work if you sent any data to the browser before this function.if you write echo or print or any HTML statements or functions before the redirection you will get an error,to avoid this use PHP output buffering as follows











1<?php










2ob_start();










3echo 'header test';










4header( 'Location: http://www.bugphp.com/' ) ;










5ob_flush();










6?>




Automatically refresh the web page every 5 seconds, with PHP









1<?php










2$url=$_SERVER['REQUEST_URI'];










3header("Refresh: 5; URL=\"" . $url . "\""); // redirect in 5 seconds









4?>