Php most important and all Interview question and answers:


What is PHP?
PHP is a web language based on scripts that allows developers to dynamically create generated web pages. PHP is a widely-used, open source scripting language.
What is session_set_save_handler in PHP? session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.
what is garbage collection? default time ? refresh time? Garbage Collection is an automated part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any session files that have not been accessed in a certain amount of time and physically deletes them. arbage Collection process only runs in the default session save directory, which is /tmp. If you opt to save your sessions in a different directory, the Garbage Collection process will ignore it. the Garbage Collection process does not differentiate between which sessions belong to whom when run. This is especially important note on shared web servers. If the process is run, it deletes ALL files that have not been accessed in the directory.
There are 3 PHP.ini variables, which deal with the garbage collector: PHP ini  value
name                                          default
session.gc_maxlifetime     1440 seconds or 24 minutes
session.gc_probability      1
session.gc_divisor              100
PHP how to know user has read the email? Using Disposition-Notification-To: in mailheader we can get read receipt.
Add the possibility to define a read receipt when sending an email.
It’s quite straightforward, just edit email.php, and add this at vars definitions:
var $readReceipt = null;
And then, at ‘createHeader’ function add:
if (!empty($this->readReceipt)) { $this->__header .= ‘Disposition-Notification-To: ‘ . $this->__formatAddress($this->readReceipt) . $this->_newLine; }
Runtime library loading ? without default mysql support, how to run mysql with php?
dl — Loads a PHP extension at runtime int dl ( string $library )
Loads the PHP extension given by the parameter library .
Use extension_loaded() to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or dl()).
bool extension_loaded ( string $name ) — Find out whether an extension is loaded
Warning :This function has been removed from some SAPI’s in PHP 5.3.
what is XML-RPC ? XML-RPC is a remote procedure call protocol which uses XML to encode its calls and HTTP as a transport mechanism. An XML-RPC message is an HTTP-POST request. The body of the request is in XML. A procedure executes on the server and the value it returns is also formatted in XML.
default session time ? default session time in PHP is 1440 seconds or 24 minutes.
default session save path ? Default session save path id temporary folder /tmp
What is the difference between htmlentities() and htmlspecialchars()?
htmlspecialchars() – Convert some special characters to HTML entities (Only the most widely used) htmlentities() – Convert ALL special characters to HTML entities
how to do session using DB?
bool session_set_save_handler ( callback $open , callback $close , callback $read , callback $write , callback $destroy , callback $gc ) using this function we can store sessions in DB.
PHP has a built-in ability to override its default session handling. The function session_set_save_handler() lets the programmer specify which functions should actually be called when it is time to read or write session information. by overriding the default functions using session_set_save_handler handle we can store session in Db like below example
class SessionManager {
var $life_time;
function SessionManager() {
// Read the maxlifetime setting from PHP $this->life_time = get_cfg_var(“session.gc_maxlifetime”);
// Register this object as the session handler session_set_save_handler( array( &$this, “open” ), array( &$this, “close” ), array( &$this, “read” ), array( &$this, “write”), array( &$this, “destroy”), array( &$this, “gc” ) );
}
function open( $save_path, $session_name ) {
global $sess_save_path;
$sess_save_path = $save_path;
// Don’t need to do anything. Just return TRUE.
return true;
}
function close() {
return true;
}
function read( $id ) {
// Set empty result $data = ”;
// Fetch session data from the selected database
$time = time();
$newid = mysql_real_escape_string($id); $sql = “SELECT `session_data` FROM `sessions` WHERE `session_id` = ‘$newid’ AND `expires` > $time”;
$rs = db_query($sql); $a = db_num_rows($rs);
if($a > 0) { $row = db_fetch_assoc($rs); $data = $row['session_data'];
}
return $data;
}
function write( $id, $data ) {
// Build query $time = time() + $this->life_time;
$newid = mysql_real_escape_string($id); $newdata = mysql_real_escape_string($data);
$sql = “REPLACE `sessions` (`session_id`,`session_data`,`expires`) VALUES(‘$newid’, ‘$newdata’, $time)”;
$rs = db_query($sql);
return TRUE;
}
function destroy( $id ) {
// Build query $newid = mysql_real_escape_string($id); $sql = “DELETE FROM `sessions` WHERE `session_id` = ‘$newid’”;
db_query($sql);
return TRUE;
}
function gc() {
// Garbage Collection
// Build DELETE query. Delete all records who have passed the expiration time $sql = ‘DELETE FROM `sessions` WHERE `expires` < UNIX_TIMESTAMP();’;
db_query($sql);
// Always return TRUE return true;
}
}
how to track user logged out or not? when user is idle ? By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes.
The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server.

What will you use to initialize a string ? ie with single quotes or double quotes ?
Unlike the double-quoted syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var}had not been printed.
The most important feature of double-quoted strings is the fact that variable names will be expanded.

You have a string “hi all, I said hello” . You want to replace the occourence of hi with hello and hello with hi . What will you do ?
$rawstring= "hi all, I said hello";
$placeholders = array('hi', 'hello'')
$malevals = array('hello', hi');
$malestr = str_replace($placeholders, $malevals, $rawstring);
echo  $malestr ;

SORRY this wrong answer that give problem in output because we replace first hello to hi then we find two times hi so, it's create problem..

True answer..
Replace With unique identifiers..
$replace = array(
'hi' => '^',
'hello' => '*',
'^' => 'hello',
'*' => 'hi'
);

echo str_replace(array_keys($replace), array_values($replace), $rawstring);
---
ereg() - Regular expression match
eregi() - Case insensitive regular expression match
eregi_replace() - Replace regular expression case insensitive
str_replace() - Replace all occurrences of the search string with the replacement string
preg_match() - Perform a regular expression match

What’s the difference between PHP4 and PHP5 ?

The new OOP features in PHP5 is probably the one thing that everyone knows for sure about. Out of all the new features, these are the ones that are talked about most!

1. Passed by Reference
2.  Visibility[public, protected, private]
3. Unified Constructors and Destructors
4. The __autoload Function

What’s all added in PHP 5.3 ?
Ans:
PHP 5.3.0 offers a wide range of new features:
Support for namespaces has been added.
Support for Late Static Bindings has been added.
Support for jump labels (limited goto) has been added.
Support for native Closures (Lambda/Anonymous functions) has been added.
There are two new magic methods, __callStatic and __invoke.
Nowdoc syntax is now supported, similar to Heredoc syntax, but with single quotes.
It is now possible to use Heredocs to initialize static variables and class properties/constants.
Heredocs may now be declared using double quotes, complementing the Nowdoc syntax.
Constants can now be declared outside a class using the const keyword.
The ternary operator now has a shorthand form: ?:.
The HTTP stream wrapper now considers all status codes from 200 to 399 to be successful.
Dynamic access to static methods is now possible.
Exceptions can now be nested.
A garbage collector for circular references has been added, and is enabled by default.
The mail() function now supports logging of sent email.

What’s Name spacing ?
Ans:
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:
Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.
PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants.

What are the types of inheritance PHP supports ?
Ans:
Similar to Java, PHP supports single inheritance. There is no multiple inheritance in php. Single inheritance means a class can extend only one parent class.

PHP also has interfaces which can be implemented if bunch of classes need to have similar functionality. An interface can be created containing methods with empty body. Implementing classes then must provide body to those methods.

When a class implements an interface, it is signing up a contract that it will provide implementation to methods declared in that interface.

What do you mean by an Abstract class and Interface ?
Ans:
Depending on the context, an interface class is either a class of the interface layer or a class whose purpose is to create a contract between a caller and an implementation (usually by providing only purely virtual functions).
An abstract class is a class that has at least one purely virtual function. Abstract classes can contain abstract and concrete methods. Abstract classes cannot be instantiated directly i.e. we cannot call the constructor of an abstract class directly nor we can create an instance of an abstract class
A static class is a class that has only static member variables and static member functions.
When a file is uploaded to the sever how can you check whether its uploaded or not ?
Ans:

(PHP 4 >= 4.0.3, PHP 5)
is_uploaded_file — Tells whether the file was uploaded via HTTP POST.
is_uploaded_file($_FILES['userfile']['tmp_name']);
Returns TRUE on success or FALSE on failure.

How will you move the uploaded file to another location of server ?
Ans:
move_uploaded_file — Moves an uploaded file to a new location.

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). 
If the file is valid, it will be moved to the filename given by destination.


What are the differences between GET and POST methods in form submitting, give the case where we can use get and we can use post methods?
On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.

On the browser side, the difference is that data submitted by the GET method will be displayed in the browser's address field. Data submitted by the POST method will not be displayed anywhere on the browser.

GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data.
Who is the father of php and explain the changes in php versions?
Rasmus Lerdorf for version changes go to http://php.net/ Marco Tabini is the founder and publisher of php|architect.
How can we submit from without a submit button?
We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form.
How many ways we can retrieve the date in result set of mysql Using php?
As individual objects so single record or as a set or arrays.
What is the difference between $message and $$message?
They are both variables. But $message is a variable with a fixed name. $$message is a variable who's name is stored in $message. For example, if $message contains "var", $$message is the same as $var.
What are the differences between require and include, include_once?
File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc.
How can I execute a php script using command line?
Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, "php myScript.php", assuming "php" is the command to invoke the CLI program.

Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.
What is meant by nl2br()?
Nl2br Inserts HTML line breaks before all newlines in a string string nl2br (string); For example: echo nl2br("god bless you")

will output "god bless you" to your browser.
What are the current versions of apache, php, and mysql?
PHP: php 5.3
MySQL: MySQL 5.5
Apache: Apache 2.2
What are the reasons for selecting lamp (Linux, apache, mysql, php) instead of combination of other software programs, servers and operating systems?
All of those are open source resource. Security of linux is very very more than windows. Apache is a better server that IIS both in functionality and security. Mysql is world most popular open source database. PHP is more faster that asp or any other scripting language.
How can we encrypt the username and password using php?
You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD("Password"); We can encode data using base64_encode($string) and can decode using base64_decode($string);
What are the different types of errors 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

What is the functionality of the function htmlentities?
Answer: htmlentities Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.


What is meant by urlencode and urldocode?

Urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode("10.00%") will return "10%2E00%25?. URL encoded strings are safe to be used as part of URLs.
urldecode() returns the URL decoded version of the given string.
How can we register the variables into a session?
We can use the session_register ($ur_session_var) function.
How can we get the properties (size, type, width, height) of an image using php image functions?
To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function
What is the maximum size of a file that can be uploaded using php and how can we change this?
You can change maximum size of a file set upload_max_filesize variable in php.ini file.
How can we increase the execution time of a php script?
Set max_execution_time variable in php.ini file to your desired time in second.
How can we take a backup of a mysql table and how can we restore it.?
Create a full backup of your database: shell> mysqldump tab=/path/to/some/diropt db_name Or: shell> mysqlhotcopy db_name /path/to/some/dir The full backup file is just a set of SQL statements, so restoring it is very easy:

shell> mysql "."Executed";
mysql_close($link2);
How many ways can we get the value of current session id?
session_id() function returns the session id for the current session.

How can we destroy the session, how can we unset the variable of a session?
session_destroy
session_unset
How can we destroy the cookie?
Set same the cookie in past
What is the difference between ereg_replace() and eregi_replace()?
eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.
How can we know the count/number of elements of an array?
2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)
interestingly if u just pass a simple var instead of a an array it will return 1. .
What is mean by LAMP?
LAMP means combination of Linux, Apache, MySQL and PHP.
How do you get the user's ip address in PHP?
Using the server variable: $_SERVER['REMOTE_ADDR']
How do you make one way encryption for your passwords in PHP?
Using md5 function or sha1 function
What is the difference between echo and print statement?
Echo() can take multiple expressions,Print cannot take multiple expressions.

Print return true or false based on success or failure whereas echo just does what its told without letting you know whether or not it worked properly.
What are the features and advantages of OBJECT ORIENTED PROGRAMMING?
One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns.

For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system.

how to track no of user logged in ? whenever a user logs in track the IP, userID etc..and store it in a DB with a active flag while log out or sesion expire make it inactive. At any time by counting the no: of active records we can get the no: of visitors.
in PHP for pdf which library used?
The PDF functions in PHP can create PDF files using the PDFlib library With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. There is also the » Panda module.
FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs.
FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5.
for image work which library?
You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.
what is oops? encapsulation? abstract class? interface?
Object oriented programming language allows concepts such as modularity, encapsulation, polymorphism and inheritance.
Encapsulation passes the message without revealing the exact functional details of the class. It allows only the relevant information to the user without revealing the functional mechanism through which a particular class had functioned.
Abstract class is a template class that contains such things as variable declarations and methods, but cannot contain code for creating new instances. A class that contains one or more methods that are declared but not implemented and defined as abstract. Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.
Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class.
what is design pattern? singleton pattern?
A design pattern is a general reusable solution to a commonly occurring problem in software design.
The Singleton design pattern allows many parts of a program to share a single resource without having to work out the details of the sharing themselves.
what are magic methods?
Magic methods are the members functions that is available to all the instance of class Magic methods always starts with “__”. Eg. __construct All magic methods needs to be declared as public To use magic method they should be defined within the class or program scope Various Magic Methods used in PHP 5 are: __construct() __destruct() __set() __get() __call() __toString() __sleep() __wakeup() __isset() __unset() __autoload() __clone()
what is magic quotes? Magic Quotes is a process that automagically escapes incoming data to the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.
diff b/w php4 & php5 ? In PHP5 1 Implementation of exceptions and exception handling
2. Type hinting which allows you to force the type of a specific argument as object, array or NULL
3. Overloading of methods through the __call function
4. Full constructors and destructors etc through a __constuctor and __destructor function
5. __autoload function for dynamically including certain include files depending on the class you are trying to create.
6 Finality : 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.
7 Interfaces & Abstract Classes
8 Passed by Reference : In PHP4, everything was passed by value, including objects. This has changed in PHP5 — all objects are now passed by reference.
9 An __clone method if you really want to duplicate an object
in php4 can you define a class? how to call class in php4? can you create object in php4?
yes you can define class and can call class by creating object of that class. but the diff b/w php4 & php5 is that in php4 everything was passed by value where as in php5 its by reference. And also any value change in reference object changes the actucal value of object also. And one more thing in introduction of __clone object in PHP5 for copying the object.
types of error? how to set error settings at run time?
here are three basic types of runtime errors in PHP:
Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although you can change this default behaviour.
Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.
Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP?s default behaviour is to display them to the user when they take place.
by using ini_set function.
what is cross site scripting? SQL injection?
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts.
SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed
what is outerjoin? inner join?
OUTER JOIN in SQL allows us to retrieve all values in a certain table regardless of whether these values are present in other tables
An inner join requires each record in the two joined tables to have a matching record. An inner join essentially combines the records from two tables (A and B) based on a given join-predicate.
what is URL rewriting?
Using URL rewriting we can convert dynamic URl to static URL Static URLs are known to be better than Dynamic URLs because of a number of reasons 1. Static URLs typically Rank better in Search Engines. 2. Search Engines are known to index the content of dynamic pages a lot slower compared to static pages. 3. Static URLs are always more friendlier looking to the End Users.
along with this we can use URL rewriting in adding variables [cookies] to the URL to handle the sessions.
what is the major php security hole? how to avoid?
Never include, require, or otherwise open a file with a filename based on user input, without thoroughly checking it first. 2. Be careful with eval() Placing user-inputted values into the eval() function can be extremely dangerous. You essentially give the malicious user the ability to execute any command he or she wishes! 3. Be careful when using register_globals = ON It was originally designed to make programming in PHP easier (and that it did), but misuse of it often led to security holes 4. Never run unescaped queries 5. For protected areas, use sessions or validate the login every time. 6. If you don’t want the file contents to be seen, give the file a .php extension.
whether PHP supports Microsoft SQL server ? The SQL Server Driver for PHP v1.0 is designed to enable reliable, scalable integration with SQL Server for PHP applications deployed on the Windows platform. The Driver for PHP is a PHP 5 extension that allows the reading and writing of SQL Server data from within PHP scripts. using MSSQL or ODBC modules we can access Microsoft SQL server.
what is MVC? why its been used? Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model.
WHY ITS NEEDED IS 1 Modular separation of function 2 Easier to maintain 3 View-Controller separation means:
A — Tweaking design (HTML) without altering code B — Web design staff can modify UI without understanding code
what is framework? how it works? what is advantage?
In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something useful. Advantages : Consistent Programming Model Direct Support for Security Simplified Development Efforts Easy Application Deployment and Maintenance
what is CURL?
CURL means Client URL Library
curl is a command line tool for transferring files with URL syntax, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos…), file transfer resume, proxy tunneling and a busload of other useful tricks.
CURL 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.
HOW we can transfer files from one server to another server without web forms?
using CURL we can transfer files from one server to another server. ex:
Uploading file
<?php
/* http://localhost/upload.php: print_r($_POST); print_r($_FILES); */
$ch = curl_init();
$data = array(‘name’ => ‘Foo’, ‘file’ => ‘@/home/user/test.png’);
curl_setopt($ch, CURLOPT_URL, ‘http://localhost/upload.php&#8217;);
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch); ?>
output:
Array ( [name] => Foo ) Array ( [file] => Array ( [name] => test.png
[type] => image/png [tmp_name] => /tmp/phpcpjNeQ [error] => 0 [size] => 279 )   ) 

using CSS can we have a scroll to table?
No table won't support scrolling of its data. but we can do another workaround like placing a table
in a DIV  layer and setting the DIV css property to overflow:auto will do the trick. 

how to increase session time in PHP ?
In php.ini by setting session.gc_maxlifetime and session.cookie_lifetime values
we can change the session time in PHP.  

what is UI? What are the five primary user-interface components? 
A user interface is a means for human beings to interact with computer-based "tools" and"messages".
One presumed goal is to make the user's experience productive, efficient, pleasing, and humane.
The primary components of UIs are  a) metaphors (fundamental concepts communicated
through words, images, sounds, etc.)
b) mental models (structure of data, functions, tasks, roles, jobs, and people in organizations of work
and/or play)
c) navigation (the process of moving through the mental models)
d) interaction (all input-output sequences and means for conveying feedback)
e) and appearance (visual, verbal, acoustic, etc.).
How can I set a cron and how can I execute it in Unix, Linux, and windows?
Cron is very simply a Linux module that allows you to run commands at predetermined times or intervals.
In Windows, it’s called Scheduled Tasks. The name Cron is in fact derived from the same word from which we get the word chronology, which means order of time.
The easiest way to use crontab is via the crontab command. # crontab This command ‘edits’ the crontab.
Upon employing this command, you will be able to enter the commands that you wish to run.
My version of Linux uses the text editor vi. You can find information on using vi here.
The syntax of this file is very important – if you get it wrong, your crontab will not function properly.
The syntax of the file should be as follows: minutes hours day_of_month month day_of_week command All the variables, with the exception of the command itself, are numerical constants.
In addition to an asterisk (*), which is a wildcard that allows any value, the ranges permitted for each field are as follows: Minutes: 0-59 Hours: 0-23 Day_of_month: 1-31 Month: 1-12 Weekday: 0-6 We can also include multiple values for each entry, simply by separating each value with a comma.
command can be any shell command and, as we will see momentarily, can also be used to execute a Web document such as a PHP file. So, if we want to run a script every Tuesday morning at 8:15 AM, our mycronjob file will contain the following content on a single line: 15 8 * * 2 /path/to/scriptname This all seems simple enough, right? Not so fast! If you try to run a PHP script in this manner, nothing will happen (barring very special configurations that have PHP compiled as an executable, as opposed to an Apache module).
The reason is that, in order for PHP to be parsed, it needs to be passed through Apache. In other words, the page needs to be called via a browser or other means of retrieving Web content.
For our purposes, I’ll assume that your server configuration includes wget, as is the case with most default configurations. To test your configuration, log in to shell.
If you’re using an RPM-based system (e.g. Redhat or Mandrake), type the following: # wget help If you are greeted with a wget package identification, it is installed in your system.
We saved it in our document root, so it should be accessible via the Internet. Remember that we wanted it to run at 4PM Eastern time, and send you your precious closing bell report? Since I’m located in the Eastern timezone, we can go ahead and set up our crontab to use 4:00, but if you live elsewhere, you might have to compensate for the time difference when setting this value.
Difference b/w OOPS concept in php4 and PHP5 ?
version 4’s object-oriented functionality was rather hobbled. Although the very basic premises of objectoriented programming (OOP) were offered in version 4, several deficiencies existed, including: • An unorthodox object-referencing methodology • No means for setting the scope (public, private, protected, abstract) of fields and methods • No standard convention for naming constructors • Absence of object destructors • Lack of an object-cloning feature • Lack of support for interfaces
how to set session tiem out at run time or how to extend the session timeout at runtime?
Ans:
Sometimes it is necessary to set the default timeout period for PHP. To find out what the default (file-based-sessions) session timeout value on the server is you can view it through a ini_get command:
// Get the current Session Timeout Value
$currentTimeoutInSecs = ini_get(’session.gc_maxlifetime’);
Change the Session Timeout Value
// Change the session timeout value to 30 minutes
ini_set(’session.gc_maxlifetime’, 30*60);
If you have changed the sessions to be placed inside a Database occasionally implementations will specify the expiry manually. You may need to check through the session management class and see if it is getting the session timeout value from the ini configuration or through a method parameter (with default). It may require a little hunting about.

What is the value of $b in the following code?
    $a="5 USD";
    $b=10+$a;
    echo $b;
?>

Ans:15
What are the differences between Get and post methods in form submitting, give the case where we can use get and we can use post methods?
  In the get method the data made available to the action page ( where data is received ) by the URL so data can be seen in the address bar. Not advisable if you are sending login info like password etc.

In the post method the data will be available as data blocks and not as query string.
What is GPC?
G – Get
P – Post
C – Cookies
What are super global arrays?
All variables that come into PHP arrive inside one of several special arrays known collectively as the superglobals. They're called superglobal because they are available everywhere in your script, even inside classes and functions.
Give some example for super global arrays?
$GLOBALS
$_GET
$_POST
$_SESSION
$_COOKIE
$_REQUEST
$_ENV
$_SERVER
What's the difference between COPY OF A FILE & MOVE_UPLOAD_FILE in file uploading?

MOVE_UPLOAD_FILE :   This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.
If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
Copy :Makes a copy of a file. Returns TRUE if the copy succeeded, FALSE otherwise.
When I do the following, the output is printed in the wrong order:
function myfunc($argument) {
        echo $argument + 10;
      }
      $variable = 10;
echo "myfunc($variable) = " . myfunc($variable);

What's going on?
To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return the
value, not echo it.
What are the Formatting and Printing Strings available in PHP?
     
Function                     Description
printf()    :                 Displays a formatted string
sprintf()   :                 Saves a formatted string in a variable
fprintf()   :                 Prints a formatted string to a file
number_format()  :   Formats numbers as strings
9:Explain the types of string comparision function in PHP.
    
      Function              Descriptions
strcmp()             :Compares two strings (case sensitive)
strcasecmp()      :Compares two strings (not case sensitive)
strnatcmp(str1, str2) :Compares two strings in ASCII order, but
                                    any numbers are compared numerically
strnatcasecmp(str1, str2):Compares two strings in ASCII order,
                                          case insensitive, numbers as numbers
strncasecomp()  : Compares two strings (not case sensitive)
                            and allows you to specify how many characters
                             to compare
strspn()             : Compares a string against characters represented
                             by a mask
strcspn()           : Compares a string that contains characters not in
                            the mask
Explain soundex() and metaphone().
      soundex()
The soundex() function calculates the soundex key of a string. A soundex key is a four character long alphanumeric string that represent English pronunciation of a word. he soundex() function can be used for spelling applications.
$str = "hello";
echo soundex($str);
?>
metaphone()
The metaphone() function calculates the metaphone key of a string. A metaphone key represents how a string sounds if said by an English speaking person. The metaphone() function can be used for spelling applications.
echo metaphone("world");
?>
What do you mean range()?
      Starting from a low value and going to a high value, the range() function creates an array of consecutive integer or character values. It takes up to three arguments: a starting value, an ending value, and an increment value. If only two arguments are given, the increment value defaults to 1.
Example :
echo range(1,10); // Returns 1,2,3,4,5,6,7,8,9,10
?>
12:How to read and display a HTML source from the website url?
      $filename="http://www.kaptivate.in/";
$fh=fopen("$filename", "r");
while( !feof($fh) ){
$contents=htmlspecialchars(fgets($fh, 1024));
print "
$contents
";
}
fclose($fh);
?>
 What is properties of class?
Class member variables are called "properties". We may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
14:How to use HTTP Headers inside PHP? Write the statement through which it can be added?
                HTTP headers can be used in PHP by redirection which is written as:
The headers can be added to HTTP response in PHP using the header(). The response headers are sent before any actual response being sent. The HTTP headers have to be sent before taking the output of any data. The statement above gets included at the top of the script.
Why we used PHP?
Because of several main reason we have to use PHP. These are:
1.PHP runs on many different platforms like that Unix,Linux and Windows etc.
2.It codes and software are free and easy to download.
3.It is secure because user can only aware about output doesn't know how that comes.
4.It is fast,flexible and reliable.
5.It supports many servers like: Apache,IIS etc.
16:Arrays  in PHP?
 Create array in PHP to solved out the problem of writing same variable name many time.In this we create a array of variable name and enter the similar variables in terms of element.Each element in array has a unique key.Using that key we can easily access the wanted element.Arrays are essential for storing, managing and operating on sets of variables effectively. Array are of three types:
1.Numeric array
2.Associative array
3.Multidimensional array
 Numeric array is used to create an array with a unique key.Associative array is used to create an array where each unique key is associated with their value.Multidimensional array is used when we declare multiple arrays in an array.
What is foreach loop in  php?
foreach :Uses, When When we want execute a block of code for each element in an array.
Syntax:
foreach (array as value)
{
    code will be executed;
}
eg:
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
  echo "Value: " . $value . "
";
}
?>
How we used $_get and $_post variable in PHP?
   We know that when we use $_GET variable all data_values are display on our URL.So,using this we don't have to send secret data (Like:password, account code).But using we can bookmarked the importpage.
 We use $_POST variable when we want to send data_values without display on URL.And their is no limit to send particular amount of character.
Using this we can not bookmarked the page.
19:Why we use $_REQUEST variable?
We use $_REQUEST variable in PHP to collect the data_values from $_GET,$_POST and $_COOKIE variable.
Example:
R4R Welcomes You .

You are years old!
How we handle errors in PHP?Explain it?
In PHP we can handle errors easily.Because when error comes it gives error line with their respective line and send error message to the web browser.
When we creating any web application and scripts. We should handle errors wisely.Because when this not handle properly it can make bg hole in security.
In PHP we handle errors by using these methods:
1.Simple "die()" statements
2.Custom errors and error triggers
3.Error reporting
How we use Custom errors and error triggers error handling method in PHP?
In Custom errors and error triggers,we handle errors by
using self made functions.
1.Custom error s : By using this can handle the multiple
errors that gives multiple message.
Syntax:
set_error_handler(\\\"Custom_Error\\\");
In this syntax if we want that our error handle, handle
only one error than we write only one argument otherwise
for handle multiple errors we can write multiple arguments.

Example:
//function made to handle errorfunction
custom_Error($errorno, $errorstr) 
{  
   echo \\\"Error: [$errorno] $errorstr\\\";  }
//set error handler like that
set_error_handler(\\\"custom_Error\\\");
//trigger to that error
echo($verify);?>

2.error trigger : In PHP we use error trigger to handle
those kind of error when user enter some input data.If
data has an error than handle by error trigger function.
Syntax:

$i=0;if ($i<=1)
{
trigger_error(\\\"I should be greater than 1 \\\");
}
?>
In this trigger_error function generate error when i is
less than or greater than 1.
22:What do you understand about Exception Handling in PHP?
In PHP 5 we introduce a Exception handle to handle run time exception.It is used to change the normal flow of the code execution if a specified error condition occurs.
An exception can be thrown, and caught("catched") within PHP. Write code in try block,Each try must have at least one catch block. Multiple catch blocks can be used to catch different classes of exceptions.
Some error handler methods given below:
1.Basic use of Exceptions
2.Creating a custom exception handler
3.Multiple exceptions
4.Re-throwing an exception
5.Setting a top level exception handler
23: What is the difference b/n 'action' and 'target' in form tag?
Action:
    Action attribute specifies where to send the form-data when
a form is submitted.
    Syntax:
    Example:
action="formValidation.php">
Target:
    The target attribute specifies where to open the action URL.
     Syntax:
        Value:
         _blank – open in new window
        _self- Open in the same frame as it was clicked
        _parent- Open in the parent frameset
        _top- Open in the full body of the window
        Framename- Open in a named frame24:What do you understand about PHP accelerator ?
Basically PHP accelerator is used to boost up the performance of PHP programing language.We use PHP accelerator to reduce the server load and also use to enhance the performance of PHP code near about 2-10 times.In one word we can say that PHP accelertator is code optimization technique.
26:How we use ceil() and floor() function in PHP?
ceil() is use to find nearest maximum values of passing value.
Example:
$var=6.5;
$ans_var=ceil($var);
echo $ans_var;
Output:
7
floor() is use to find nearest minimum values of passing value.
Example:
$var=6.5
$ans_var=floor($var);
echo $ans_var; 
Output:
6
27:What is the answer of following code
echo 1< 2 and echo 1 >2 ?

Output of the given code are given below:
echo 1<2
output: 1
echo 1>2
output: no output
28: What is the difference b/w isset and empty?
The main difference b/w isset and empty are given below:
isset: This variable is used to handle functions and checked a variable is set even through it is empty.
empty: This variable is used to handle functions and checked either variable has a value or it is an empty string,zero0 or not set at all.


Top 100 PHP Interview Questions & Answers
What is PHP?
PHP is a web language based on scripts that allows developers to dynamically create generated web pages.
What does the initials of PHP stand for?
PHP means PHP: Hypertext Preprocessor.
Which programming language does PHP resemble to?
PHP syntax resembles Perl and C
What does PEAR stands for?
PEAR means “PHP Extension and Application Repository”. it extends PHP and provides a higher level of programming for web developers.
What is the actually used PHP version?
Version 5 is the actually used version of PHP.
How do you execute a PHP script from the command line?
Just use the PHP command line interface (CLI) and specify the file name of the script to be executed as follows:
[php]
php script.php
[/php]
How to run the interactive PHP shell from the command line interface?
Just use the PHP CLI program with the option -a as follows:
[php]
php -a
[/php]
8 What are the correct and the most two common way to start and finish a PHP block of code?
The two most  common ways to start and finish a PHP script are: <?php [   ---  PHP code---- ] ?> and <? [---  PHP code  ---] ?>
How can we display the output directly to the browser?
To be able to display the output directly to the browser, we have to use the special tags <?= and ?>.
What is the main difference between PHP 4 and PHP 5?
PHP 5 presents many additional OOP (Object Oriented Programming) features.
Is multiple inheritance supported in PHP?
PHP includes only single inheritance, it means that a class can be extended from only one single class using the keyword ‘extended’.
What is the meaning of a final class and a final method?
‘final’ is introduced in PHP5. Final class means that this class cannot be extended and a final method cannot be overrided.
How comparison of objects is done in PHP5?
We use the operator ‘==’ to test is two object are instanced from the same class and have same attributes and equal values. We can test if two object are refering to the same instance of the same class by the use of the identity operator ‘===’.
How can PHP and HTML interact?
It is possible to generate HTML through PHP scripts, and it is possible to pass informations from HTML to PHP.
What type of operation is needed when passing values through a form or an URL?
If we would like to pass values througn a form or an URL then we need to encode and to decode them using htmlspecialchars() and urlencode().
How can PHP and Javascript interact?
PHP and Javascript cannot directly interacts since PHP is a server side language and Javascript is a client side language. However we can exchange variables since PHP is able to generate Javascript code to be executed by the browser and it is possible to pass specific variables back to PHP via the URL.
What is needed to be able to use image function?
GD library is needed to be able execute image functions.
What is the use of the function ‘imagetypes()’?
imagetypes() gives the image format and types supported by the current version of GD-PHP.
What are the functions to be used to get the image’s properties (size, width and height)?
The functions are getimagesize() for size, imagesx() for width and imagesy() for height.
How failures in execution are handled with include() and require() functions?
If the function require() cannot access to the file then it ends with a fatal error. However, the include() function gives a warning and the PHP script continues to execute.
What is the main difference between require() and require_once()?
require() and require_once() perform the same task except that the second function checks if the PHP script is already included or not before executing it.
(same for include_once() and include())
How can I display text with a PHP script?
Two methods are possible:
[php]
<!–?php echo “Method 1″; print “Method 2″; ?–>
[/php]
How can we display information of a variable and readable by human with PHP?
To be able to display a human-readable result we use print_r().
How is it possible to set an infinite execution time for PHP script?
The set_time_limit(0) added at the beginning of a script sets to infinite the time of execution to not have the PHP error ‘maximum execution time exceeded’.It is also possible to specify this in the php.ini file.
What does the PHP error ‘Parse error in PHP – unexpected T_variable at line x’ means?
This is a PHP syntax error expressing that a mistake at the line x stops parsing and executing the program.
What should we do to be able to export data into an Excel file?
The most common and used way is to get data into a format supported by Excel. For example, it is possible to write a .csv file, to choose for example comma as separator between fields and then to open the file with Excel.
What is the function file_get_contents() usefull for?
file_get_contents() lets reading a file and storing it in a string variable.
How can we connect to a MySQL database from a PHP script?
To be able to connect to a MySQL database, we must use mysql_connect() function as follows:
[php]
<!–?php $database = mysql_connect(“HOST”, “USER_NAME”, “PASSWORD”); mysql_select_db(“DATABASE_NAME”,$database); ?–>
[/php]
What is the function mysql_pconnect() usefull for?
mysql_pconnect() ensure a persistent connection to the database, it means that the connection do not close when the the PHP script ends.
How the result set of Mysql be handled in PHP?
The result set can be handled using mysql_fetch_array, mysql_fetch_assoc, mysql_fetch_object or mysql_fetch_row.
How is it possible to know the number of rows returned in result set?
The function mysql_num_rows() returns the number of rows in a result set.
Which function gives us the number of affected entries by a query?
mysql_affected_rows() return the number of entries affected by an SQL query.
What is the difference between mysql_fetch_object() and mysql_fetch_array()?
The mysql_fetch_object() function collects the first single matching record where mysql_fetch_array() collects all matching records from the table in an array.
How can we access the data sent through the URL with the GET method?
In order to access the data sent via the GET method, we you use $_GET array like this:
www.url.com?var=value
$variable = $_GET["var"]; this will now contain ‘value’
How can we access the data sent through the URL with the POST method?
To access the data sent this way, you use the $_POST array.
Imagine you have a form field called ‘var’ on the form, when the user clicks submit to the post form, you can then access the value like this:
$_POST["var"];
How can we check the value of a given variable is a number?
It is possible to use the dedicated function, is_numeric() to check whether it is a number or not.
How can we check the value of a given variable is alphanumeric?
It is possible to use the dedicated function, ctype_alnum to check whether it is an alphanumeric value or not.
How do I check if a given variable is empty?
If we want to check whether a variable has a value or not, it is possible to use the empty() function.
What does the unlink() function means?
The unlink() function is dedicated for file system handling. It simply deletes the file given as entry.
What does the unset() function means?
The unlink() function is dedicated for variable management. It will make a variable undefined.
How do I escape data before storing it into the database?
addslashes function enables us to escape data before storage into the database.
How is it possible to remove escape characters from a string?
The stripslashes function enables us to remove the escape characters before apostrophes in a string.
How can we automatically escape incoming data?
We have to enable the Magic quotes entry in the configuration file of PHP.
What does the function get_magic_quotes_gpc() means?
The function get_magic_quotes_gpc() tells us whether the magic quotes is switched on or no.
Is it possible to remove the HTML tags from data?
The strip_tags() function enables us to clean a string from the HTML tags.
what is the static variable in function useful for?
A static variable is defined within a function only the first time and its value can be modified during function calls as follows:
[php]
<!–?php function testFunction() { static $testVariable = 1; echo $testVariable; $testVariable++; } testFunction();        //1 testFunction();        //2 testFunction();        //3 ?–>
[/php]
How can we define a variable accessible in functions of a PHP script?
This feature is possible using the global keyword.
How is it possible to return a value from a function?
A function returns a value using the instruction ‘return $value;’.
What is the most convenient hashing method to be used to hash passwords?
It is preferable to use crypt() which natively supports several hashing algorithms or the function hash() which supports more variants than crypt() rather than using the common hashing algorithms such as md5, sha1 or sha256 because they are conceived to be fast. hence, hashing passwords with these algorithms can vulnerability.
Which cryptographic extension provide generation and verification of digital signatures?
The PHP-openssl extension provides several cryptographic operations including generation and verification of digital signatures.
How a constant is defined in a PHP script?
The define() directive lets us defining a constant as follows:
define (“ACONSTANT”, 123);
How can you pass a variable by reference?
To be able to pass a variable by reference, we use an ampersand in front of it, as follows $var1 = &$var2
Will a comparison of an integer 12 and a string “13″ work in PHP?
“13″ and 12 can be compared in PHP since it casts everything to the integer type.
How is it possible to cast types in PHP?
The name of the output type have to be specified in parentheses before the variable which is to be cast as follows:
(int), (integer) – cast to integer
(bool), (boolean) – cast to boolean
(float), (double), (real) – cast to float
(string) – cast to string
(array) – cast to array
(object) – cast to object
When a conditional statement is ended with an endif?
When the original if was followed by : and then the code block without braces.
How is the ternary conditional operator used in PHP?
It is composed of three expressions: a condition, and two operands describing what instruction should be performed when the specified condition is true or false as follows:
Expression_1 ? Expression_2 : Expression_3;
What is the function func_num_args() used for?
The function func_num_args() is used to give the number of parameters passed into a function.
If the variable $var1 is set to 10 and the $var2 is set to the character var1, what’s the value of $$var2?
$$var2 contains the value 10.
What does accessing a class via :: means?
:: is used to access static methods that do not require object initialization.
In PHP, objects are they passed by value or by reference?
In PHP, objects passed by value.
Are Parent constructors called implicitly inside a class constructor?
No, a parent constructor have to be called explicitly as follows:
parent::constructor($value)
What’s the difference between __sleep and __wakeup?
__sleep returns the array of all the variables that need to be saved, while __wakeup retrieves them.
What is faster?
Combining two variables as follows:
$variable1 = ‘Hello ‘;
$variable2 = ‘World’;
$variable3 = $variable1.$variable2;
Or
$variable3 = “$variable1$variable2″;
$variable3 will contain “Hello World”. The first code is faster than the second code especially for large large sets of data.
what is the definition of a session?
A session is a logical object enabling us to preserve temporary data across multiple PHP pages.
How to initiate a session in PHP?
The use of the function session_start() lets us activating a session.
How is it possible to propagate a session id?
It is possible to propagate a session id via cookies or URL parameters.
What is the meaning of a Persistent Cookie?
A persistent cookie is permanently stored in a cookie file on the browser’s computer. By default, cookies are temporary and are erased if we close the browser.
When sessions ends?
Sessions automatically ends when the PHP script finishs executing, but can be manually ended using the session_write_close().
What is the difference between session_unregister() and session_unset()?
The session_unregister() function unregister a global variable from the current session and the session_unset() function free all session variables.
What does $GLOBALS means?
$GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.
What does $_SERVER means?
$_SERVER is an array including information created by the web server such as paths, headers, and script locations.
What does $_FILES means?
$_FILES is an associative array composed of items sent to the current script via the HTTP POST method.
What is the difference between $_FILES['userfile']['name'] and $_FILES['userfile']['tmp_name']?
$_FILES['userfile']['name'] represents the original name of the file on the client machine,
$_FILES['userfile']['tmp_name'] represents the temporary filename of the file stored on the server.
How can we get the error when there is a problem to upload a file?
$_FILES['userfile']['error'] contains the error code associated with the uploaded file.
How can we change the maximum size of the files to be uploaded?
We can change the maximum size of files to be uploaded by changing upload_max_filesize in php.ini.
What does $_ENV means?
$_ENV is an associative array of variables sent to the current PHP script via the environment method.
What does $_COOKIE means?
$_COOKIE is an associative array of variables sent to the current PHP script using the HTTP Cookies.
What does the scope of variables means?
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.
what the difference between the ‘BITWISE AND’ operator and the ‘LOGICAL AND’ operator?
$a and $b:    TRUE if both $a and $b are TRUE.
$a & $b:        Bits that are set in both $a and $b are set.
What are the two main string operators?
The first is the concatenation operator (‘.’), which returns the concatenation of its right and left arguments. The second is (‘.=’), which appends the argument on the right to the argument on the left.
What does the array operator ‘===’ means?
$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
What is the differences between $a != $b and $a !== $b?
!= means inequality (TRUE if $a is not equal to $b) and !== means non-identity (TRUE if $a is not identical to $b).
How can we determine whether a PHP variable is an instantiated object of a certain class?
To be able to verify whether a PHP variable is an instantiated object of a certain class we use instanceof.
What is the goto statement useful for?
The goto statement can be placed to enable jumping inside the PHP program. The target is pointed by a label followed by a colon, and the instruction is specified as a goto statement followed by the desired target label.
what is the difference between  Exception::getMessage and Exception::getLine ?
Exception::getMessage lets us getting the Exception message and Exception::getLine lets us getting the line in which the exception occurred.
What does the expression Exception::__toString means?
Exception::__toString gives the String representation of the exception.
How is it possible to parse a configuration file?
The function parse_ini_file() enables us to load in the ini file specified in filename, and returns the settings in it in an associative array.
How can we determine whether a variable is set?
The boolean function isset determines if a variable is set and is not NULL.
What is the difference between the functions strstr() and stristr()?
The string function strstr(string allString, string occ) returns part of allString from the first occurrence of occ to the end of allString. This function is case-sensitive. stristr() is identical to strstr() except that it is case insensitive.
what is the difference between for and foreach?
for is expressed as follows:
for (expr1; expr2; expr3)
statement
The first expression is executed once at the beginning. In each iteration, expr2 is evaluated. If it is TRUE, the loop continues and the statements inside for are executed. If it evaluates to FALSE, the execution of the loop ends. expr3 is tested at the end of each iteration.
However, foreach provides an easy way to iterate over arrays and it is only used with arrays and objects.
Is it possible to submit a form with a dedicated button?
It is possible to use the document.form.submit() function to submit the form. For example: <input type=button value=”SUBMIT” onClick=”document.form.submit()”>
What is the difference between ereg_replace() and eregi_replace()?
The function eregi_replace() is identical to the function ereg_replace() except that it ignores case distinction when matching alphabetic characters.
Is it possible to protect special characters in a query string?
Yes, we use the urlencode() function to be able to protect special characters.
What are the three classes of errors that can occur in PHP?
The three basic classes of errors are notices (non-critical), warnings (serious errors) and fatal errors (critical errors).
What is the difference between characters 34 and x34?
34 is octal 34 and x34 is hex 34.
How can we pass the variable through the navigation between the pages?
It is possible to pass the variables between the PHP pages using sessions, cookies or hidden form fields.
Is it possible to extend the execution time of a php script?
The use of the set_time_limit(int seconds) enables us to extend the execution time of a php script. The default limit is 30 seconds.
Is it possible to destroy a cookie?
Yes, it is possible by setting the cookie with a past expiration time.
What is the default session time in php?
The default session time in php is until closing of browser
Is it possible to use COM component in PHP?
Yes, it’s possible to integrate (Distributed) Component Object Model components ((D)COM) in PHP scripts which is provided as a framework.


Comments