Pages

Monday, July 14, 2014

150+ PHP Interview Questions & Answers

       1. What is PHP?
      Answer 1:
PHP: Hypertext Preprocessor is open source server-side scripting language that is widely used for web development. PHP scripts are executed on the server. PHP allows writing dynamically generated web pages efficiently and quickly. The syntax is mostly borrowed from C, Java and Perl. PHP is free to download and use.
Answer 2: PHP (Hypertext Preprocessor) is a scripting language commonly used for web applications. PHP can be easily embedded in HTML. PHP generally runs on a web server. It is available for free and can be used across a variety of servers, operating systems and platforms.
Answer 3: The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.

2. What is PEAR in php?
Answer l:
PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organized OOP library.  PEAR also provides a command-line interface that can be used to automatically install “packages".
Answer2:
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-sourced code for PHP users
A system for code distribution and package maintenance
A standard style for code written in PHP,
The PHP Foundation Classes (PFC),
The PHP Extension Community Library (PECL),
A web site, mailing lists and download mirrors to support the PHP/PEAR community
PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then.
Answer 3: PEAR (PHP Extension and Application Repository) is a framework and repository for reusable PHP components. PEAR is a code repository containing all kinds of php code snippets and libraries.
PEAR also offers a command-line interface that can be used to automatically install "packages".

3. Explain how to submit form without a submit button?
Answer 1: We can achieve the above task by using JavaScript code linked to an event trigger of any form field and call the document.form.submit() function in JavaScript code.
A form data can be posted or submitted without the button in the following ways:
1. On OnClick event of a label in the form, a JavaScript function can be called to submit the form e.g. document.form_name.submit ()
2. Using a Hyperlink: On clicking the link, JavaScript function can be called e.g
A form can be submitted in various ways without using submit button.
Submitting a form by clicking a link
Submitting a form by selecting an option from drop down box with the invocation of onChangeEvent
Using java script: document.form.submit ();
Using header (“location:page.php”);
Answer 2: If you don't want to use the Submit button to submit a form, you can use normal hyperlinks to submit a form. But you need to use some JavaScript code in the URL of the link. For example:
Answer 3: 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. For example:
Answer 4: Trigger the JavaScript code on any event (like onSelect of drop-down list box, on focus, etc.)  document.myform.submit (); this will submit the form.

4. Echo vs. print statement?
echo() and print() are language constructs in PHP, both are used to output strings. The speed of both statements is almost the same.
echo() can take multiple expressions whereas print cannot take multiple expressions.
Print return true or false based on success or failure whereas echo doesn't return true or false.

      5. $message vs. $$message in PHP?
Answer 1:
$message is a simple variable whereas $$message is a reference variable.
Example: $user = 'bob' is equivalent to
$holder = 'user",
$$holder = 'bob";
Anwser2: 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.
Answer 3: $message is a variable with a fixed name. $$message is a variable whose name is stored in $message. If $message contains "var", $$message is the same as $var.

       6. Explain the different types of errors in PHP.
Answer 1: Notices, Warnings, and Fatal errors are the types of errors in PHP
Notices: Notices represents non-critical errors, i.e. accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all but whenever required, you can change this default behavior.
Warnings: Warnings are more serious errors but they do not result in script termination. i.e calling include() a file which does not exist. By default, these errors are displayed to the user.
Fatal errors: Fatal errors are critical errors i.e. calling a non-existent function or class. These errors cause the immediate termination of the script.
Different types of errors are:
·          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
Answer 2: Here are three basic types of runtime errors in PHP:
1. 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 behavior.
2.  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.
3.  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 behavior is to display them to the user when they take place.
Internally, these variations are represented by twelve different error types

       7. Explain the importance of the function htmlentities.
Answer 1: The htmlentities() function converts characters to HTML entities.
Answer 2: 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

       8. What is MIME?
Answer1: MIME - Multi-purpose Internet Mail Extensions.
MIME types represents a standard way of classifying file types over Internet.
Web servers and browsers have a list of MIME types, which facilitates files transfer of the same type in the same way, irrespective of operating system they are working in.
A MIME type has two parts: a type and a subtype. They are separated by a slash (/).
MIME type for Microsoft Word files is application and the subtype is msword, i.e. application/msword.
Answer 2:
MIME is Multipurpose Internet Mail Extensions is an Internet standard for the format of e-mail.  However browsers also uses MIME standard to transmit files. MIME has a header which is added to a beginning of the data. When browser sees such a header it shows the data as it would be a file (for example image)
Some examples of MIME types:
audio/x-ms-wmp
image/png
application/x-shockwave-flash
Answer 3:
Multipurpose Internet Mail Extensions.
WWW's ability to recognize and handle files of different types is largely dependent on the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard provides for a system of registration of file types with information about the applications needed to process them. This information is incorporated into Web server and browser software, and enables the automatic recognition and display of registered file types.

      9. What is a Session in PHP?
Answer 1: A PHP session is no different from a normal session. It can be used to store information on the server for future use. However this storage is temporary and is flushed out when the site is closed. Sessions can start by first creating a session id (unique) for each user.
Syntax: session_start()
E.g. storing a customer’s information.
Sessions allow data to be transferred from one page to another. Session information is temporary and information is valid until the user is using the website. A session assigns a unique ID, UID, to each visitor.
A PHP session starts using:
PHP Session Variables:
A PHP session variable is used to hold values of the current session. A session needs to be started first.
session_start();
// store session data
$_SESSION['sample']=1;?>
They can be used to hold information about a single user that is applicable to all web pages.
$message is used to store variable data. $$message can be used to store variable of a variable. Data stored in $message is fixed while data stored in $$message can be changed dynamically.
E.g. $var1 = ‘Variable 1’
$$var1= ‘variable2’
This can be interpreted as $ Variable 1=‘variable2’;
For me to print value of both variables, I will write
$var1 $($var1)
Answer2: A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.
There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.                                                                                                                   
Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

      10. How to set cookies in PHP?
Answer 1: A cookie is used for identification purposes. It is more commonly used to identify a user in a session. It is a small file the application inserts on the user’s computer. With PHP one can create and retrieve the cookie.
·          Setting cookie in php:
Cookies in PHP can be set using the setcookie() function. This must appear before the HTML tag.
Syntax: Setcookie(name, value, expire, path, domain);
Example: here, the cookie name sample is assigned a value jim. The cookie expires after an hour.
Setcookie(“sample”, “jim”, time()+3600);
·          Retrieving cookie value:
The cookie that is set can be retrieved as shown below:
echo $_cookie[“user”];
isset() function can be used to find if the cookie is set.
Answer 2: Setcookie(‘variable','value','time');
Variable - name of the cookie variable
Value - value of the cookie variable
Time - expiry time
Example:  setcookie('Test',$i,time()+3600);
Test - cookie variable name
$i - value of the variable ‘Test’
Time()+3600 - denotes that the cookie will expire after an one hour.
      
       11. What is a Persistent Cookie?
Answer 1: Cookies are used to remember the users. Content of a Persistent cookie remains unchanged even when the browser is closed. ‘Remember me’ generally used for login is the best example for Persistent Cookie.
Answer 2: A persistent cookie is a cookie which is stored in a cookie file permanently   on the browser’s computer. By default, cookies are created as temporary cookies which stored only in the browser’s memory.  When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
·          Temporary cookies cannot be used for tracking long-term information.
·          Persistent cookies can be used for tracking long-term information.
·          Temporary cookies are safer b/c no programs other than the browser can access them.
Persistent cookies are less secure b/c users can open cookie files see the cookie values.

      12. How to reset/destroy a cookie?
Answer 1: Cookies can be deleted either by the client or by the server. Clients can easily delete the cookies by locating the Cookies folder on their system and deleting them. The Server can delete the cookies in two ways:
·          Reset a cookie by specifying expiry time
·          Reset a cookie by specifying its name only
The function setcookie() is used to define a cookie that is to be sent along with HTTP headers. The cookie must be sent prior to any output from the script as is the protocol restriction. After setting the cookies, they can be used when the next page is loaded by using $_COOKIE or $HTTP_COOKIE_VARS arrays.
Answer 2: Reset a cookie by specifying expire time in the past:
Example:  setcookie('Test',$i,time()-3600);    //already  expired  time
Reset a cookie by specifying its name only
Example:  setcookie('Test');

      13. Explain the differences between require and include, include_once?
Answer 1: include() will include the file specified.
include_once() will include the file only once even if the code of the file has been included before.
require() and include() are the same with respect to handling failures. However, require() results in a fatal error and does not allow the processing of the page. i.e. include will allow the script to continue.
Answer 2:
require_once()  and include_ once()  are both the functions to include and evaluate the specified  file only once. If the specified file is included previous to the present call occurrence, it will not be done again.
But require() and include() will do it as many times they are asked to do.
Answer 3:
The include_once() statement includes and evaluates the specified file during the execution  of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included,  it will not be included  again.  The major difference between include() and require() is that in failure include() produces a warning message whereas require() produces  a fatal errors.
Answer 4:
All three are used to an include file into the current page.
If the file is not present, require(),  calls a fatal error, while  in include()  does not-
the include_ once() statement  includes and evaluates the specified  file during the execution of the script. This is a behavior similar to the inc1ude() statement, with the only difference being, that if the code from a file has already been included, it will not be included  again, It does not call a fatal error if file not exists. require_once() does the same as include _once(), but it calls a fatal error if file not exists.
Note: 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.

       14. What is the difference between include and require in PHP?
Answer 1: include () and require () are almost similar except the way they handle failures. include () produces a warning and require() produces a fatal error. To halt processing of the page, use require (). The same operation will not halt by using include (). It should be ensured that the include_path settings are proper. Both are used for inserting the file content into PHP file prior to its execution by the server.
Answer 2: It’s how they handle failures. If the file is not found by require (), it will cause a fatal error and halt the execution of the script. If the file is not found by include (), a warning will be issued, but execution will continue.

      15. What is urlencode and urldecode?
Answer 1: Urlencode can be used to encode a string that can be used in a URL. It encodes the same way posted data from web page is encoded. It returns the encoded string.
Syntax: urlencode (string $str)
Urldecode can be used to decode a string. Decodes any %## encoding in the given string (Inserted by urlencode)
Syntax: urldecode (string $str)
Answer 2: 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("l0.00%") will return “10%2E00%25 ''. URL encoded strings are safe to be used as part of URLs. urldecodeO returns  the URL decoded version of the given string.
Answer 3:
string urlencode(str) - Returns the URL encoded version of the input string. String values to be used in URL query string need to be URL encoded. In the URL encoded version:
Alphanumeric characters are maintained as is. Space characters are converted to "+" characters.
Other non-alphanumeric characters are converted “%” followed by two hex digits representing the converted character.
string urldecode(str) - Returns the original string of the input URL encoded string.
For example:
$discount ="10.00%";
$url = "http://domain.com/submit.php?disc=".urlencode($discount);
echo $url;
You will get ''http://domain.com/submit.php?disc=10%2E00%25''.

      16. What are the functions for IMAP?
IMAP is used for communicate with mail servers. It has a number of functions. Few of them are listed below:
·          Imap_alerts – Returns all the imap errors occurred
·          Imap_body – Reads the message body
·          Imap_check – Reads the current mail box
·          Imap_clearflag_full – Clears all flags
·          Imap_close – close and IMAP stream
·          Imap_delete – Delete message from current mailbox
·          Imap_delete_mailbox – Deletes a mailbox
·          Imap_fetchbody – Fetches body of message
·          Imap_fetchheader – Fetches header of message
·          Imap_headers – Returns headers for ALL messages
·          Imap_mail : send a mail
·          Imap_sort- Sorts IMAP messages
·          imap_open: To open an IMAP stream to a mail box
·          imap_open: To open an IMAP stream to a mail box
·          imap_expunge: Delete all emails marked for deletion.

      17. How can we increase the execution time of a php script?
Answer 1: Default time allowed for the PHP scripts to execute is 30s defined in the php.ini file. The function used is set_time_limit(int seconds). If the value passed is ‘0’, it takes unlimited time. It should be noted that if the default timer is set to 30 sec and 20 sec is specified in set_time_limit(), the script will run for 45 secs.   
The script execution time can be increased by
- Using sleep() function in PHP script
- Using set_time_limit() function
- The default limit is 30 seconds. The time limit can be set to zero to impose no time limit to pause.
Answer 2: By the use of void set_time_limit(int seconds)
Set the number of seconds a script is allowed to run.  If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.
When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

      18. What is Type juggle in php?
Type Juggling means dealing with a variable type. In PHP a variables type is determined by the context in which it is used. If an integer value is assigned to a variable, it becomes an integer.
E.g. $var3= $var1 + $var2
Here, if $var1 is an integer. $var2 and $var3 will also be treated as integers.

      19. What is the difference between mysql_fetch_object and mysql_fetch_array?
Answer 1: Ways to retrieve the data in the result set of MySQL using PHP
1. mysql_fetch_row($result):- where $result is the result resource returned from a successful query executed using the mysql_query() function.
Example:
$result = mysql_query(“SELECT * from students);
while($row = mysql_fetch_row($result))
{
      Some statement;
}
2. mysql_fetch_array($result):- Return the current row with both associative and numeric indexes where each column can either be accessed by 0, 1, 2, etc., or the column name.
Example:
$row = mysql_fetch_array($result)
3. mysql_fetch_assoc($result): Return the current row as an associative array, where the name of each column is a key in the array.
Example:
$row = mysql_fetch_assoc($result)
$row[‘column_name’]
4.mysql_fetch_object: Results are objects returned from database. Fields are accessible like
$result->name, $result->cust_name, where $result is the result object and name, cust_name are the fields.
mysql_fetch_array : Results are arrays returned from database. Fields are accessible like $result[name], $result[cust_name].
Answer 2: MySQL fetch object will collect first single matching record where mysql_ fetch _array will collect all matching records from the table in an array.
Answer 3: mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular array. mysql_fetch_object() -> Fetch a result row as an object.
mysql_fetch_row() -> Fetch a result set as a regular array().
Answer 4: The difference between mysql_fetch_row() and mysql_fetch_array() is that the first returns the results in a numeric array ($row[0], $row[1], etc.), while the latter returns the results an array containing both numeric  and associative keys ($row['name'], $row['email'], etc)
mysql_fetch_object() returns an object ($row->name,$row->email,   etc.).

      20. What is the difference between the functions unlink and unset?
Answer 1: Unlink is a function for file system handling which deletes a file. Unset is used to destroy a variable.  
The function unlink() is to remove a file, whereas unset() is used for destroying a variable that was declared earlier. unset() empties a variable or contents of file.
Answer 2: Unlink()  is a function  for file system handling.  It will simply delete the file in context
Unset()  is a function  for variable  management.  It will make a variable undefined
      
      21. What is Joomla in PHP?
Joomla is a content management system. Powerful online applications and web sites are build using Joomla. Joomla is an open source CMS tool. Clients can easily manage their web sites with minimal amount of instructions. It is highly extensible. Joomla runs off PHP or MySQL. Joomla is used to create, maintain a structured, flexible portal, add or edit content, changes the look and feel of the site. PHP scripting is used and persisted most of its data / information in MySQL database.

      22. What is Zend engine?
Zend Engine is used internally by PHP as a complier and runtime engine. PHP Scripts are loaded into memory and compiled into Zend opcodes.

      23. Explain the architecture of Zend engine with the diagram.
Zend Engine is used internally by PHP as a compiler and runtime engine. PHP Scripts are loaded into memory and compiled into Zend opcodes. These opcodes are executed and the HTML generated is sent to the client. The same is depicted below
Zend engine is like a virtual machine and is an open source, and is known for its role in automating the web using PHP. Zend is named after its developers Zeev and Aandi. Its reliability, performance and extensibility has a significant role in increasing the PHP’s popularity. The Zend Engine II is the heart of PHP 5. It is an open source project and freely available under BSD style license.

      24. What is the difference between Split and Explode?
Both the functions are used to Split a string. However, Split is used to split a string using a regular expression. On the other hand, Explode is used to split a string using another string.
E.g explode (" this", "this is a string"); will return “Is a string”
Split (" + ", "This+ is a string")

      25. What is CAPTCHA?
CAPTCHA is a test to determine if the user using the system (usually a web form) is a human. It identifies this by throwing challenges to users. Depending on the responses the identification can be made. E,g Answering to identification of distorted images. Captcha Creator is a PHP Script that generates Strong Captchas

      26. What is difference between developing website using Java and PHP?
In order to make interactive pages, java uses JSP (Java Server pages). PHP is open source while JSP is not. Libraries are much stronger in Java as compared tp PHP. Huge codes can be managed with ease in Java by making classes.  

Both technologies are used for dynamic websites development.
PHP is an interpreter based technology where as java is compiler based(usually JSP).
PHP is open source where as JSP is not.
Web sites developed in PHP are much more faster compared to Java technology
Java is a distributed technology, which means N tier application can be developed, where as PHP is used only for web development.

      27. How can I embed a java program in php file and what changes have to be done in php.ini file?
There are two possible ways to bridge PHP and Java: you can either integrate PHP info a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension
The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.
Example Code:
getProperty(‘java.version'). ";
 echo 'Java vendor=‘. $system->getProperty(‘java.vendor'). ";
echo 'OS=' . $system->getProperty('os.name'). ‘   ‘. $system->getProperty('os.version') . ‘on ' . $system->getProperty(‘os.arch') . '  '; // java.util.Date example
$formatter = new Java('java.text.SimpleDateFormat',."EEEE, MMMM dd, yyyy 'at' h.mm.ss a zzzz"); echo $formatter->format(new Java(‘java.util.Date'));   ?>
The behavior of these functions is affected by settings in php.ini.
Table 1. Java configuration options
Name
Default
Changeable
java.class.path
NULL
PHP_INI_ALL
Name Default Changeable
java.home
NULL
PHP_INI_ALL
java.library.path
NULL
PHP_INI_ALL
java.library.path
JAVALIB
PHP_INI_ALL
Answer 2: PHP can be integrated into the servlet environment of java or java support can be integrated with php. The java extension can be used to create and invoke methods on Java objects from PHP.

      28. How do you create sub domains using PHP?
Wild card domains can be used. Sub domains can be created by first creating a sub directory in the /htdocs folder. E.g. /htdocs/mydomain. Then, the host file needs to be modified to define the sub domain. If the sub domains are not configured explicitly, all requests should be thrown to the main domain.

      29. How to upload files using PHP?
Files can be uploaded in PHP by using the tag type=”file”. An upload form must have encytype="multipart/form-data" , method also needs to be set to method="post". Also, hidden input MAX_FILE_SIZE before the file input. To restrict the size of files
E.g. method="POST">

30. What is the difference between using copy() and move() function in php file uploading?
Copy() makes a copy of the file. It returns TRUE on success. It can copy from any source to destination. Move simple Moves the file to destination if the file is valid. While move can move the uploaded file from temp server location to any destination on the server. If filename is a valid upload file, but cannot be moved for some reason, no action will occur.
- Select a file from the form using
- Specify the path into which the file is to be stored.
- Insert the following code in php script to upload the file.
move_uploaded_file($_FILES["file"]["tmp_name"], "myfolder/" . $_FILES["file"]["name"]);

      31. What is the difference between Notify URL and Return URL?
Notify URL and Return URL is used in Paypal Payment Gateway integration. Notify URL is used by PayPal to post information about the transaction. Return URL issued by the browser; A url where the user needs to be redirected on completion of the payment process.

      32. Describe functions STRSTR() and STRISTR().
Answer 1:
Both the functions are used to find the first occurrence of a string. Parameters includes: input String, string whose occurrence needs to be found, TRUE or FALSE (If TRUE, the functions return the string before the first occurrence.
STRISTR is similar to STRSTR. However, it is case-insensitive
E.g. strstr ($input_string, string)
Answer 2:
string strstr ( string haystack, string needle) returns part of haystack string from the first occurrence of needle to the end of haystack. This function is case-sensitive.
Strstr() returns part of a given string from the first occurrence of a given substring to the end of the string. For example:  strstr("user@example.com","@”) will return “@example.com".
stristr() is identical to strstr() except that it is case insensitive.

      33. What are the various methods to pass data from one web page to another web page?
Different methods to pass data from one web page to another:
1. Store the data in a session variable. By storing the data, the data can be passed from one page to another.
2. Store data in a cookie: By storing data in a persistent cookie, data can be passed from one form to another.
3. Set the data in a hidden field and post the data using a submit button.
Short note on passing parameter by reference and returning parameter by reference with examples.
Passing parameter by reference: In PHP, variables can be passed by reference so as to modify them. Variables, statements which have new and references returned from function can be passed.
Example: references returned from function
Function &sample()
{
         $a =1;
         Return &a;
}
Foo(bar());
?>
Returning parameter by reference: Returning parameter by reference is used when a function to find to which variable a reference should be bound.
Example:
$obj = new foo;
$myValue = &$obj->getValue(); // $myValue is a reference to $obj-value, which is 42.
$obj->value = 2;
echo $myValue;

      34. How many ways I can redirect a PHP page?
a. Header function in PHP redirects to a new URL
Example:
         header("Location: http://www.redirecturl.com/");
?>
b. http_redirect() is also used to redirect to a new page or URL.
Syntax: void http_redirect ( [string url [, array params [, bool session = FALSE [, int status]]]] )
Here, the URL is the path of the new page. params can be some query parameters followed by whether the session information needs to be passed and the custom response status code.

      35. Explain the purpose of output buffering in PHP.
Output buffering in PHP buffers a scripts output. This buffer can be edited before returning it to the client. Without output buffering, PHP sends data to the web server as soon as it is ready. Output buffering "send" cookies at any point in the script. Cookies do not have to be necessarily sent near the start of page. Output buffers are stackable and hence sending to output is by choice.

      36. How can we know the number of days between two given dates using PHP?
Answer 1: The start date and end date can be first found as shown below:
$date1= strotime($start_date);
$date2= strotime($end_date);
$date_diff = (($date1)- ($date2)) / (60*60*24)
Answer 2: Simple arithmetic:
$datel = date('Y-m-d');
$date2 = '2006-07-01';
$days = (strtotime() – strtotime())/ (60 * 60 * 24);
echo "Number  of days since '2006-07-01 ': $days";
Answer 3: Use DATEDIFF()
SELECT DATEDIFF(NOW():’2008-10-01');

      37. How can we encrypt the password using PHP?
crypt() function is used to create one way encryption. It takes one input string and one optional parameter. The function look is defined as: crypt (input_string, salt), where input_string consists of the string which has to be encrypted and salt is an optional parameter. PHP uses DES for encryption. The format is as follows:-
$password = crypt('mypassword');
print $password . “ is the encrypted version of mypassword”;
?>

      38. How will you change the name of a column in a table? 
ALTER TABLE table_name CHANGE old_colm_name new_colm_name 
     
      39. What is the default session time in PHP?
Until closing the browser.

40. How will you create a database using PHP and MySQL?
By using : mysql_create_db("Database Name")
      
      41. How will you find out the value of current session id?
By using: session_id()
\     
      42. What is the Difference between Dynamic & Static Web Pages?
In simplest terms, static Web pages are those with content that cannot change without a developer editing its source code, while dynamic Web pages can display different content from the same source code.
Static Web Pages
Static Web pages display the exact same information whenever anyone visits it. Static Web pages do not have to be simple plain text. They can feature detailed multimedia design and even videos. However, every visitor to that page will be greeted by the exact same text, multimedia design or video every time he visits the page until you alter that page's source code.
Dynamic Web Pages
Dynamic Web pages are capable of producing different content for different visitors from the same source code file. The website can display different content based on what operating system or browser the visitor is using, whether she is using a PC or a mobile device, or even the source that referred the visitor. A dynamic Web page is not necessarily better than a static Web page.

43. What is the difference between == and === in PHP?
When comparing values in PHP for equality you can use either the == operator or the === operator. What’s the difference between the 2? Well, it’s quite simple. The == operator just checks to see if the left and right values are equal. But, the === operator (note the extra “=”) actually checks to see if the left and right values are equal, and also checks to see if they are of the same variable type (like whether they are both booleans, ints, etc.).

44. In PHP, what are magic methods and how are they used?
PHP functions that start with a double underscore – a “__” – are called magic functions (and/or methods) in PHP. They are functions that are always defined inside classes, and are not stand-alone (outside of classes) functions. The magic functions available in PHP are: __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone(), and __autoload().

45. What is the difference between self and $this?
$this is used to reference the current object, whereas self is used to access the current class itself.

46. How to delete an element from an array in php?
When deleting an element from an array in PHP, a good function to use is the unset function. Here is an example of its usage:
An example of using unset to delete an element from an array:
$anArray = array("X", "Y", "Z");
unset($anArray[0]);
//'dumps' the content of $anArray to the page:
var_dump($anArray); 
The output of the var_dump function will be:
array(2) { [1]=> string(1) "Y" [2]=> string(1) "Z" }

47. The code to turn off error messages in PHP:
You have to place this line of code before the code that is causing the warning to be displayed. If you place this code after the offending code, then it will not work in suppressing the error message that gets displayed. Here is the line of code to use:
error_reporting(E_ERROR | E_PARSE);

48. 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?
When  we submit  a form, which  has the GET method  it displays  pair of name/value  used in the form  at the address  bar of the browser  preceded  by url. Post method doesn't display these values.

49. Meaning of Open Source Software.
OSS (Open Source Software) is computer s/w with its source code made available & licensed with a license in which the copyright holder provides the rights to study, change & distribute s/w to anyone & for any purpose.

50. How to Download and Install PHP on Windows?
PHP is one of the most popular languages to develop dynamic Web pages. It supports all major database servers, including:  MySQL, MS SQL Server, Oracle, mSQL, Sybase, etc.
If you  are  developing   a Web  application   that uses  PHP  and needs  to access  MS  SQL Server,  you  should  go download  and install  PHP  to your  local  machine  to practice  PHP and SQL Server connection.  The best way to download and install PHP on Windows systems is to:
·          Go to http:/www.php.net. Which is the official Web site for PHP.
·          Click the Downloads menu link. You will see the PHP download page.
·          Go to the "Windows  Binaries"  section,  and click "PHP 5.2.3 zip package"  link to download  PHP binary version  for Windows  in ZIP format
·          Save the downloaded file, php-S.2.3-Win32.zip   with 9,847,499 bytes, in C: Temp directory.
·          Unzip the downloaded file info directory C: php.
You are done. No need to run any installation program.

51. How to Check Your PHP Installation?
PHP provides two execution interfaces: Command Line Interlace (CLI) and Common Gateway
Interface (CGI). If PHP is installed in the php directory on your system, you can try this to check
your installation:
·          Run "phpphp -v" command to check the Command Line Interface (CLI).
·          Run "phpphp-cgi -v" command to check the Common Gateway Interface (CGI).
If you see PHP printing the version information on your screen for both commands, your installation is ok. Open a command window and run the commands below:
C:>phpphp -v
PHP 5.22 (cli) (built: May 2 2007 19:18:26)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0 Copyright (c) 1998-2007 Zend Technologies
C:>phpphp-cgi -v
PHP 5.22 (cgi-fcgi) (built: May 2 2007 19:18:25)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2_0 Copyright (c) 1998-2007 Zend Technologies

52. How To Download and Install PHP for Windows?
The best way to download and install PHP on Windows systems is to:
·          Go to http:/www.php.net, which is the official Web site for PHP.
·          Download PHP binary version  for Windows  in ZIP format
·          Unzip the downloaded file into a directory.
You are done. No need to run any installation program.

53. Where Are PHP Configuration Settings Stored?
PHP stores configuration settings in a file called php.ini in PHP home directory. You can open it with any text editor to your settings.

54. How to Run a PHP Script?
A standard alone PHP script can be executed directly with the PHP Command Line Interface (CLI). Write the following script in a file called hello.php:
This script can be executed by CLI interface like this phpphp hello.php
You should see the "Hello world!" Message printed on your screen.

55. What Are the Special Characters You Need to Escape in Single-Quoted Stings?
There are two special characters you need to escape in a single-quote string: the single quote (') & the back slash (\). Here is a PHP script example of single-quoted strings:
echo 'Hello world! '. ,
echo 'It's Friday! ';
echo 'Represents an operator.';
?>
This script will print:
Hello world! It’s Friday! Represents an operator.

56. Can You Specify the "new line" Character in Single-Quoted Strings?
You can not specify the "new line" character in a single-quoted string. If you don't believe, try this script
This script will print:
will not work in single  quoted strings.

57. How Many Escape Sequences Are Recognized in Single-Quoted Strings?
There are 2 escape sequences you can use in single-quoted   strings:
·          \ - Represents the back slash character.
·          ‘- Represents the single quote character.

58. What Are the Special Characters You Need to Escape in Double-Quoted Stings?
There are two special characters you need to escape in a double-quote string: the double quote (") and the back slash (\).  Here is a PHP script example   of double-quoted strings:
echo "Hello world!";
echo "Tom said: "Who's there?””;
echo " represents an operator. ";
?>
This script will print:
Hello world! Tom said: "Who's there?" represents an operator.

59. How Many Escape Sequences Are Recognized in Double-Quoted Strings in PHP?
There are 12 escape sequences you can use in double-quoted strings:
·          \ - Represents the back slash character.
·          “- Represents the double quote character.
·          $ - Represents the dollar sign.
·          {- Represents the open brace character.
·          } - Represents the dose brace character.
·          [- Represents the open bracket character.
·          ] - Represents the close bracket character.
·          nn - Represents  a character  as an octal value,
·          xnn - Represents  a character  as a hex value.

60. How To Include Variables in Double-Quoted Strings in PHP?
Variables included in double-quoted strings will be interpolated. Their values will be concatenated into the enclosing strings.  For example, two statements in the following PHP script will print out the same string:
$variable = "and";
echo "part 1 $variable part 2 ".,
echo "part 1 ".$variable." part 2”; ?>
This script will print:
part 1 and part 2 part 1 and part 2

61. How Many Ways to Include Variables in Double-Quoted Strings in PHP?
There are 3 formats to include variables in double-quoted strings:
·          "part 1 $variable  part 2" - This is the simplest  format  to include  a variable  in a string,  The variable  name  starts with the dollar sign and ends at the first  character that cannot be used in variable  name,  Space is good character  to end a variable  name,
·          "part  1 $ {variable} part 2" - This format  helps you to clearly  end the variable  name,  The variable  name  starts at dollar sign before the open brace  (${) and ends at the close brace (}),
·          "part  1{$variable}part 2" - This  format  is also called  complex  format, You use  this format  to specify  any complex variable  expression  in the same way  as in a normal  statement,  The van able expression  starts  at ( {$) followed  by a variable  name  and ends at (}).
Here is a PHP script example of different ways to include variables in double-quoted strings:
$beer = 'Heineken';
echo "$beer's taste is great.";
echo "He drank some $ {beer}s and water.”;
echo "She drank some  {$beer}s and water.”;
?>
This script will print: Heineken’s taste is great.
He drank some Heinekens and water.
She drank some Heinekens and water.

62. How Many Ways to Include Array Elements in Double-Quoted Strings using PHP?
There are 2 formats to include array elements in double-quoted strings in PHP:
·          "part 1 $array[key]  part 2" - This is called simple format.  In this format, you can not specify the element key in quotes.
·          "part 1 {$array['key']} part 2" - This is called complex format. In this format, the array element expression is specified in the same way as in a normal statement. Here is a PHP script example of different ways to include variables in double-quoted strings
$fruits = array (‘strawberry’ => 'red', 'banana' => 'yellow');
echo "A banana  is $fruits[banana].”;
echo "A banana  is {Sfruits['banana']}”.;
?>
This script will print: A banana is yellow.
A banana is yellow.
"A banana is $fruits['banana'].
“ will give you a syntax error.

63. How to Access a Specific Character in a String using PHP?
Any character in a string can be accessed by a special string element expression:
·          $string{index}           - The index is the position of the character counted from left and starting from 0. Here is a PHP script example:
$string = 'It's Friday!’;
echo "The first character is $string {0}”;
echo "The first  character  is {$string{0}}”;
?>
This script will print:
The first character is It's Friday! {0} The first character is I

64. How to Assigning a New Character in a String using PHP?
The string element expression, $string{index}, can also be used  at the left side of an assignment  statement. This allows you to assign a new character to any position in a string. Here is a PHP script example:
$string = 'It's Friday?';
echo "$string";
$string{11} = '!';
echo "$string";
?>
This script will print: It's Friday?
It's Friday!

65. How to Concatenate Two Strings Together in PHP?
You can use the string concatenation operator (.) to join two strings into one. Here is a PHP script example of string concatenation:
?>
This script will print: Hello World!

66. How to Compare Two Strings with Comparison Operators in PHP7
PHP supports 3 string comparison operators,   <, ==, and >, that generates Boolean values.  Those  operators  use  ASCII  values  of characters   from  both  strings  to determine  the comparison  results.  Here is a PHP script on how to use comparison   operators:
$a = "PHP is a scripting language.";
$b = "PHP is a general-purpose   language.";
if($a > $b) {
print('$a  >-$b is true.'.””);
} else {
print('$a  >-$b is false.',"");
}
if($a==$b)  {
print('$a == $b is true.'."");
} else {
print('$a== $b is false.'."");
}
if($a  < $b) {
print('$a< $b is true.'."");
} else  {
print('$a< $b is false!"“);
}
?>
This script will print:
$a > $b is true.
$a == $b is false. $a < $b is false.

67. How to Convert Numbers to Strings in PHP?
In a string context, PHP will automatically convert any numeric value to a string. Here is a PHP script examples:
print(-1.3e3);
print(" ");
print(slrlen(-1.3e3));
print(" ");
print("Price  = $"  . 99.99  . "”);
print(l . "+". 2 ."=".1+2."");
print(l   ."+ “.2."=".(1+2)."”);
print(l   ."+".2."=” 3");
print("“);
?>
This script will print:
-1300
5
Price = $99.99
3
1+2=3
1+2=3

The print() function requires a string, so numeric value  -1.3e3 is automatically converted to a string "-1300".  The concatenation operator (.) also requires a string, so numeric value 99.99 is automatically converted to a string "99.99". Expression (1. "+ '". 2." =" . 1+2. "") is a little bit interesting.  The result is "3" because concatenation operations and addition operation are carried out from left to right. So when the addition operation is reached. We have "1 + 2 = 1"+2, which will cause the string to be converted to a value 1.

68. How to Convert Strings to Numbers in PHP?
In a numeric context, PHP will automatically convert any string to a numeric value. Strings will be converted into two types of numeric values, double floating number and integer, based on the following rules:
·          The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used.  Otherwise the value will be 0 (zero).
·          If the valid numeric data contains '.', 'e', or 'E', it will be converted to a double floating number. Otherwise it will be converted to an integer.

69. How to Get the Number of Characters in a String?
You can use the "strlen()" function to get the number of characters in a string. Here is a PHP script example of strlen():
print(strlen('lt's Friday!”));
?>
This script will print:
12

70. How to Remove White Spaces from the Beginning and/or the End of a String in PHP?
There are 4 PHP functions you can use remove white space characters from the beginning and/or the end of a string:
·          trim() - Remove white space characters from the beginning and the end of a string.
·          ltrim() - Remove white space characters from the beginning of a string.
·          rtrim() - Remove white space characters from the end of a string.
·          chop() - Same as rtrim().
White space characters are defined as:
·          " " (ASCII  32 (ox20)), an ordinary space.
·          " " (ASCII  9 (Ox09)), a tab.
·          “ " (ASCII  10 (OxOA)), a new line (line feed)
·          "" (ASCII  13 (OxOD)), a carriage  return.
·          " " (ASCII  0 (OxOO)), the NULL-byte.
·          "xOB" (ASCII  11 (OxOB), a vertical tab.
Here is a PHP script example of trimming strings:
$text ="        Hello world!      '';
$leftTrimmed = ltrim($text);
$rightTrimmed = rtrim($text);
$bothTrimmed = trim($text);
print(“leftTrimmed = ($leftTrimmed)“);
print(“rightTrimmed = ($rightTrimmed)");
print(“bothTrimmed = ($bothTrimmed)”);
?>
This script will print:


 leftTrimmed = (Hello
world!       )
rightTrimmed = (       Hello world!)
bothTrimmed = (Hello world!)

71. How to Remove the New Line Character from the End of a Text Line in PHP?
If you are using fgets() to read a line from a text file, you may want to use the chop() function to remove the new line character from the end of the line as shown in this PHP script:
$handle = fopen("/tmp/inputfile.txt", "r");
while($line=fgets())   {
$line = chop($line.);
# process $line here ...
}
fclose($handle);
?>

72. How To Remove Leading and Trailing Spaces from User Input Values in PHP?
If you are taking input values from users with a Web form, users may enter extra spaces at the beginning and/or the end of the input values. You should always use the trim() function to remove those extra spaces as shown in this PHP script:
$name = $_REQUEST("name");
$name = trim($name);
# $name is ready to be used...
?>

73. How to Find a Substring from a Given String in PHP?
To find a substring in a given string, you can use the strpos() function.  If you call strpos($haystack, $needle),  it will try to find the position  of the first  occurrence the $needle  string  in the $haystack string.  If found, it will return a non-negative integer represents the position of $needle.  Otherwise, it will return a Boolean false. Here is a PHP script example of strpos():
$haystack1  = "123456789hello10111213";
$haystack2  = "hello123456789";
$haystack3  = "hello123456789hh12";
$pos1 = strpos($haystackl,    "hello");
$pos2 = strpos($haystac.k2,  "hello");
$pos3 = strpos($haystack3,   "hello");
print("pos1  = ($post);   type is " . gettype($pos1)   . " ");
print("pos2  = (sposz);  type is " . gettype($pos2)   . " ");
print("pos3  = ($pos3); type is " . gettype($pos3)   . "”);
?>

This script will print
pos1 = (9); type is integer
pos2 = (0); type is integer
pos3 = 0; type is boolean
"pos3" shows strpos() can return a Boolean value

74. What Is the Best Way to Test the strpos() Return Value in PHP?
Because strpos() could two types of values, Integer and Boolean, you  need  to be careful  about  testing the return value. The best way is to use the "Identical(===)" operator. Do not use the "Equal(==)" operator, because it does not differentiate  "0" and "false". Check out this PHP script on how to use strpos():
$haystack  = "needle234953413434516504381640386488129";
$pos = strpos($haystack, "needle"};
if ($pos==false)     {
print("Not found based (==)    test “);
} else {
print("Found  based  (==) test”);
}
if ($pos===false)        {
print(''Not found based (===) test");
} else {
print("Found based  (===) test”);
}
?>
This script will print:
Not found based (==) test
Found based (===) test
Of course, (===) test is correct.

75. How To Take a Substring from a Given. String in PHP?
If you know the position of a substring in a given string, you can take the substring out by the substr() function. Here is a PHP script on how to use substr():
$string= "beginning";
print("Position counted from left: ".substr($string,0,5)." “);
print(“Position counted form right: ".substr($string,-7,3)." “);
?>
This script will print:
Position counted from left: begin
Position counted form right: gin
substr() can take negative starting position counted from the end of the string.

76. How to Replace a Substring in a Given String in PHP?
If you know the position of a substring in a given string, you can replace that substring by another string by using the substr _replaceO  function.  Here is a PHP script on how to use substr_replace():
$string = "Warning:  System will shut down in NN minutes!";
$pos = strpos($striug, "NN");
print(substr_replace($string, "15", $pos, 2)." “);
sleep(10*60);
print(substr_replace($string, "5", $pos, 2)."“);
?>
This script will print:
Warning:  System will shut down in 15 minutes!
(10 minutes later)
Warning:  System will shut down in 5 minutes!
Like substr(), substr_replace() can take negative starting position counted from the end of the string.

77. How can we repair a MySQL table?
The syntax for repairing a MySQL table is:
REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR. TABLE tablename EXTENDED
This command will repair the table specified.
If QUICK is given, MySQL will do a repair of only the index tree.
If EXTENDED is given, it will create index row by row.

78. What does a special set of tags do in PHP?
What does a special set of tags do in PHP? The output is displayed directly to the browser.

79. How do you define a constant in PHP?
Via define()  directive,  like define (“MYCONSTANT",  100);

80. How to Write the FORM Tag Correctly for Uploading Files?
When users clicks the submit button, files specified in the will be transferred from the browser to the Web server. This transferring (uploading) process is controlled by a properly written
tag as:
Note that you must specify METHOD as "post" and ENCTYPE as "multipart/form-data"   in order for the uploading process to work.  The following PHP code, called logo_upload.php, shows you a complete FORM tag for file uploading:
print("
print("Please  submit  an image file a Web site logo for"."google.com:
n");
print("
n ");
print("n");
print("
?>

81. How to Get the Uploaded File Information in the Receiving Script?
Once the Web server received the uploaded file, it will call the PHP script specified in the form. action attribute to process  them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES.  Uploaded file information is organized in $_FILES as a two-dimensional array as:
·          $_FILES [$fieldName]['name'] - The Original file name on the browser  system.
·          $_FILES [$fieldName]['type']   - The file type determined  by the browser.
·          $_FILES [$fieldName]['size']  - The Number  of bytes of the file content.
·          $_FILES [$fieldName][‘tmp _ name']  - The temporary filename of the file in which the uploaded  file was stored on the server.
·          $_FILES [$fieldName]['error'] -  The error code associated with  this file upload.
The $fieldName is the name used in the .

82. 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.

83. I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what is the problem?
PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.

84. Would I use print "$a dollars" or" {$a} dollars" to print out the amount of dollars in this example?
In this example it wouldn't matter, since the variable is all by itself, but if you were to print something like "{$a}, 000,000 mln dollars", then you definitely need to use the braces.

85. What are the different tables present MySQL? Which type of table is generated when we are creating a table in the following syntax: create table employee (eno int(2),ename   varchar(10))?
Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23. When you fire the above create query MySQL will create a MyISAM table.

86. How to Create a Table using PHP?
If you want to create a table, you can run the CREATE TABLE statement as shown in the following sample script:
include "mysql_ connection.php'';
$sql= "CREATE TABLE  ggl_links  (" ." id INTEGER  NOT NULL". ", url VARCHAR(80) NOT NULL". ", notes VARCHAR(1024)". ", counts INTEGER". ", time TIMESTAMP DEFAULT sysdate()". ")'";
if (mysql_ query($sql, $con)   (
print("Table ggl_links created.n");
} else (
printf(“Table creation failed.n");
}
mysql_close($con);
?>      Remember that mysql_ query() returns TRUE/FALSE on CREATE  statements. If you run this script, you will get something like this: Table ggl_links created.

87. How can we encrypt the username & password using PHP?
Answer 1:
You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD (“Password”);
Answer 2:
You can use the MySQL PASSWORD() function to encrypt username and password. For example, INSERT into user (password, …) VALUES (PASSWORD($password")), ...);

88. How do you pass a variable by value?
Just like in C++, put an ampersand in front of it, like $a = &$b

89. When are you supposed to use endif to end the conditional statement?
When the original if was followed by : and then the code block without braces.

90. How can we send mail using JavaScript?
No. There is no way to send emails directly using JavaScript.
But you can use JavaScript to execute a client side email program send the email using the "rnailto" code. Here is an example:
function myfunction(form)
{
tdata=document.myform.tbox1.value;
location=”mailto:mailid@domain.com?subject= ..."; return  true;
}

91. What is the difference between ereg_replace() and eregi_replace()?
eregi _replace() function is identical to ereg_replace() except that it ignores case distinction  when matching alphabetic characters.

92. How do I find out the number of parameters passed into function9?
func _num _args() function  returns  the number  of parameters  passed  in.

      93. What is the purpose of the following files having extensions:  frm, myd, and myi? What these files contain?
In MySQL, the default table type is MyISAM.                                                                                                                                       
Each MyISAM table is stored on disk in three flies.  The files have names that begin with the table name and have an extension to indicate the file type.
The '.frm' file stores the table definition.
The data file has a '.MYD’ (MYData) extension.
The index file lias a '.MYI' (MYIndex) extension,

      94. If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?
100, it's a reference to existing variable.

      95. How to Protect Special Characters in Query String?
If you  want to include  special  characters  like spaces  in the query  string,  you need  to protect  them  by applying  the urlencode() translation  function.  The script below shows how to use urlencode():
")  ;
print("Please click the links below"." to submit comments about google.com:
");
$comment = 'I want to say: "It's a good site!  :->’";
$comment = urlencode($comment);
print("".""
."It's an excellent site!
");
$comment = 'This visitor said: "It's an average site!:-(''';
Scomment = urlencode($comment);
print("");
?>

      96. Are objects passed by value or by reference?
Everything is passed by value.

      97. What are the differences between DROP a table and TRUNCATE a table?
DROP TABLE 
     
      98. Differences between GET and POST methods in form submitting, give the case where we can use GET and we can use POST methods?
When  we submit  a form, which  has the GET method  it displays  pair  of name/value   used in the form at the address  bar of the browser  preceded  by URL. Post method doesn't display these values.
table_name  - This will delete the table and its data.
TRUNCATE TABLE  table_name  - This will delete the data of the table, but not the table definition.

      99. How do you call a constructor for a parent class?
parent::constructor($value)
    
      101. What is tile special meaning of __sleep   and__wakeup?
__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.

      102. Would you initialize your strings with single quotes or double quotes?
Since the data inside the single-quoted   string is not parsed  for variable  substitution,   it's  always  a better  idea speed-wise   to initialize  a string with single quotes,  un1ess you specifically  need variable  substitution.

      103. How can we extract string abc.com from a string http://info@abc.com using regular expression of php?
We can use the preg_match() function with "/.*@(.*)$/" as the regular expression pattern. For example:
preg_ match("/. *@(.*)$/" , ''http://info@abc.com'' ,$data);
echo $data[1];

      104. How come the code works, but does not for two-dimensional array of mine?
Any time you have an array with more than one dimension, complex parsing syntax is required.  print “Contents:  {$arr[1][2]} " would've  worked.

       105. How can we register the variables into a session?
session_ register($session_ var);
$_SESSION['var') = 'value';

      106. What is the difference between characters \023 and \x23?
The first one is octal 23, the second is hex 23.

      107. With a heredoc syntax, do I get variable substitution inside the heredoc contents?
Yes.

      108. 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.

      109. Can we use include ("abc.php") two times in a php page “makeit.php"?
Yes.

      110. For printing out strings, there are echo, print and printf. Explain the differences.
echo is the most  primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling  it), but it returns TRUE on successful output and FALSE  if it was tillable to print out the string.  However, you can pass multiple parameters to echo, like:
and it will output  the string "Welcome to Google!" print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages as formatted output, but it's  the slowest way to print out data out of echo, print and printf
   
      111. I am writing an application in PHP that outputs a printable version of driving directions.  It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters.  How do I accomplish that with PHP?
On large strings that need to be formatted according to some length specifications, use wordwrap()  or chunk _ split().

      112. What is the output of the ucwords function in this example?
$formatted  = ucwords("Google is COLLECTION of information");
print $formatted;
What will be printed is Google is COLLECTION of information.
Ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it's worth using strtolower()  first.

      113. What Is the difference between htmlentities() and htmlspecialchars()?
Htmlspecialchars only takes care of <, >, single quote ‘double quote “and ampersand.  htmlentities translates   all occurrences of character sequences that have different meaning in HTML.

      114. How can we destroy the session, how can we unset the variable of a session?
session_unregister() - Unregister a global variable from the current session session_unset()  - Free all session variables

      115. What are the different functions in sorting an array'?
Sorting functions in PHP:
asort()    arsort()   ksort() krsort() uksort()  sort() natsort() rsort()

      116. How can we know the count/number of elements of an array?
2 ways:
a) sizeof($array) - This function  is an alias of count()
b) count($urarray) - This function  returns  the number  of elements  in an array.
Interestingly if you just pass a simple var instead of an array, count() will return 1.

      117. How many ways we can pass the variable through the navigation between the pages?
At least 3 ways:
I. Put the variable into session in the first page,  and get it back from session  in the next page.
2. Put the variable  into cookie in the first page, and get it back from  the cookie in the next page.
3. Put the variable  into a hidden  form field, and get it back from the form in the next page.

      118. What is the maximum length of a table name, a database name, or a field name in MySQL?
Database name: 64 characters Table name: 64 characters Column name:  64 charac.ters

      119. How many values can the SET function of MySQL take?
MySQL SET function can take zero or more values, but at the maximum it can take 64 values.

      120. How can we find the number of rows in a table using MySQL?
Use this for MySQL
SELECT COUNT(*)  FROM  table_name;

      121. What is the difference between md5(), crc32() and sha1() crypto on PHP?
The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.

      122. How can we find the number of rows in a result set using PHP?
Here is how you can find the number of rows in a result set in PHP:
$result = mysql_ query($any _valid _ sql, $database _link);
$num _rows = mysql_ num _rows($result);•
echo "$num_rows  rows found";

      123. How many ways we can we find the current date using MySQL?
SELECT CURDATE();
SELECT CURRENT _DATE();
SELECT CURTIME();
SELECT CURRENT _TIME();

      124. Give the syntax of GRANT commands?
The generic syntax for GRANT is as following
GRANT [rights) on [database] TO [username@hostname) IDENTIFIED BY [password] Now rights can be:
a) ALL privileges
b) Combination of CREATE, DROP,  SELECT,  INSERT,  UPDATE  and DELETE  etc.
We can grant rights on all database by using *.* or some specific database by database.* or a specific table by database.table_name.

      125. Give the syntax of REVOKE commands?
The generic syntax for revoke is as following:
REVOKE [rights] on [database] FROM [username@hostname]
Now rights can be:
a) ALL privileges
b) Combination of CREATE,  DROP,  SELECT,  INSERT, UPDATE and DELETE  etc.
We can grant rights on all database by using *.* or some specific database by database. * or a specific table by database.table_name.

      126. What is the difference between CHAR and VARCHAR data types?
CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For example, ''Hello!'' will be stored as "Hello!" in CHAR(10) column.
VARCHAR is a variable length data type. VARCHAR(n) will take only the required storage for the actual number of characters  entered to that column. For example, "Hello!" will be stored as "Hello!' in VARCHAR( 10) column.

      127. How can we encrypt and decrypt a data present in a MySQL table using MySQL?
AES_ENCRYPT() and AES_DECRYPT()

      128. What is the functionality of MD5 function in PHP?
string md5(string)
It calculates the MDS hash of a string. The hash is a 32-character hexadecimal number.

      129. How can we change the data type of a column of a table?
This will change the data type of a column:
ALTER TABLE table_name CHANGE colmname same_colm_name[new data type]

      130. What is the difference between GROUP BY and ORDER BY in SQL?
To sort a result, use an ORDER BY clause.
The most general way to satisfy a GROUP BY clause is to scan the whole table and create  a new temporary  table where all rows from each  group  are consecutive, and then use this temporary table to discover  groups  and apply aggregate functions (if any).                                                                                             .
ORDER BY [col1],[coI2], ...[coln]; Tells DBMS according to what columns it should sort the result If two rows will have the same value in cok1 it will try to sort them according to co12 and so on.
GROUP BY [col1],[co12], ...[coln]; Tells DBMS to group (aggregate) results with same value of column col1 . You can use COUNT(col1),  SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average.

      131. How can we know that a session is started or not?
A session starts by session_start() function,
This session_start() is always declared in header portion. It always declares first then we write session_register().

      132. What are the MySQL database files stored in system?
Data is stored in name.myd
Table structure is stored in name.frm
Index is stored in name.myi

      133. What is the difference between PHP4 and PHP5?
PHP4 cannot support oops concepts and Zend engine 1 is used.
PHP5 supports oops concepts and Zend engine 2 is used. Error supporting is increased in PHP5.
XML and SQLite will is increased in PHP5.

      134. What is meant by nl2br()?
Answer l:
nl2br() inserts a HTML tag
before all new line characters n in a string.
echo nl2br("god  bless n you");
Output: god bless
you

      135. How can we encrypt and decrypt a data presented in a table using MySQL?
You can use functions: AES_ENCRYPTO and AES_DECRYPTO like:
AES_ENCRYPT(str, key_str)      AES_DECRYPT(crypt_str, key_str)

      136. What are encryption functions in PHP?
CRYPT()
MD5()

      137. What types of images that php supports?
Using imagetypes() function to find out what types of images are supported in your PHP engine.
Imagetypes() - Returns  the image types supported.
This function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP.  The following bits are returned, IMG _ GIF | IMG_JPG | IMG_PNG | IMG_ WBMP | IMG_XPM.

      138. How can I know that a variable is a number or not using a JavaScript?
Answer 1:
bool is_ numeric( mixed var)
Returns TRUE if var is a number or a numeric string, FALSE otherwise.
Answer 2:
Definition and Usage
The is NaN() function is used to check if a value  is not a number.
Syntax is NaN(number)
Parameter Description: number required.  The value to be tested

      139. How can we destroy the cookie in PHP?
Set the cookie with a past expiration time.

      140. What are the current versions of Apache, PHP, and MySQL?
PHP: PHP 5.5.14
MySQL:  MySQL 5.6.24
Apache:  Apache 2.4.12

      141. What is the use of friend function in PHP?
Friend functions
Sometimes a function is best" shared among a number of different classes.  Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class. A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.
class mylinkage
{
private:
mylinkage * prev;
mylinkage * next;
protected:
friend void set_prev(mylinkage* L, mylinkage* N);
void set_next(mylinkage* L);
public:
mylinkage * succ();
mylinkage * pred();
mylinkage();
};
void mylinkage::set_next(mylinkage*  L) {next  = L; }
void set_prev(mylinkage * L, mylinkage * N) {N->prev = L; }
Friends in other classes
It is possible to specify a member function of another class as a friend as follows:
class C
{ friend int B:: f1(); };
class B
{ int f1(); };
It is also possible to specify all the functions in another class as friends, by specifying the entire class as a friend.
class A
{ friend class B; };

      142.  How can we get second of the current time using date function?
$second = date("s");

      143. How can I make a script that can be bilingual (supports English, German)?
You can change charset variable in above line in the script to support bilanguage.

      144. What are the differences between abstract class and interface?
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.

      145. What are the advantages of stored procedures, triggers, indexes in PHP?
A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don’t need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side.  Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted. Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data.

      146. What is maximum size of a database in MySQL?
If the operating system or file system places a limit on the number of files in a directory, MySQL is bound by that constraint. The efficiency of the operating system in handling large numbers of files in a directory can place a practical limit on the number of tables in a database. If the time required to open a file in the directory increases significantly as the number of files increases, database performance can be adversely affected.
The amount of available disk space limits the number of tables.
MySQL 3.22 had a 4GB (4 gigabytes) limit on table size. With the   MyISAM storage engine in MySQL 3.23, the maximum table size was increased to 65536 terabytes (2567 -1 bytes). With this larger allowed table size, the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits.
The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files. This allows a table to exceed the maximum individual file size. The tablespace can include raw disk partitions, which allows extremely large tables. The maximum tablespace size is 64TB.

      147. Explain normalization concept?
The  normalization process involves getting our data to conform  to three  progressive   normal  forms,  and a higher  level  of normalization   cannot  be achieved  until the previous  levels have been achieved  (there are actually  five normal  forms, but the last two are mainly  academic  and will not be discussed).
First Normal Form
The First Normal Form (or INF) involves removal of redundant data from horizontal rows. We want to ensure that there is no duplication of data in a given row and that every column stores the least amount of information possible (making the field atomic).
Second Normal Form
Where the First Normal Form deals with redundancy of data across a horizontal row, Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms are progressive,   so to achieve Second Normal Form, your tables must already be in First Normal Form.
Third Normal Form
I have a confession to make; I do not often use Third Normal Form. In Third Normal Form we are looking for data in our tables that is not fully dependent on the primary key, but defendant on another value in the table

      148. What type of inheritance that php supports?
In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is not supported.  Classes are extended using the keyword ‘extends’.

      149. How can increase tile performance of MySQL select query?
We can use LIMIT to stop MySQL for further search in table after we have received our required no. of records, also we can use LEFT JOIN or RIGHT JOIN instead of full join in cases we have related  data in two or more tables.

      150. How can I use the COM components in php?
The COM class provides a framework to integrate (D) COM components into your PHP scripts.
string COM::COM(  string_module_name [,string server_name [,int  codepage]])  - COM class constructor. Parameters:
module _name:  name or class-id of the requested component.
server_ name:  name of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com, allow_ dcom has to be set to TRUE in php.ini.
codepage - specifies tile codepage that is used to convert php-strings to unicode-strings and vice versa.  Possible values are CP_ACP, CP_MACCP,   and CP _OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.
Usage:
$word->Visible = 1; //open an empty document
$word->Documents->Add();  //do  some weird stuff
$word->Selection->TypeText("This is a test ... ");
$word->Documents [1] ->Save As ("Useless test.doc"); //closing word
$word->Quit();   //free the .object
$word->Release();
$word = null;


      151. How many ways we can give the output to a browser?
HTMLoutput, PHP, ASP, JSP, Servlet Function
Script Language output Function
Different Type of embedded Package to output to a browser
               
      152. What changes I have to do in php.ini file for file uploading?
Make the following line uncomment like:
; Whether to allow HTTP file uploads. file_uploads = On
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
upload _tmp _ dir = C:apache2triadtemp
; Maximum allowed size for uploaded files. upload_max _ filesize = 2M

      153. What type of headers have to be added in the mail function to attach a file?
$boundary = '--'.md5(uniqid (rand()) );
$headers = "From:  "Me"n";
$headers .= “MIME-Version: 1.0n";
$headers .= "Content- Type: multipart/mixed;   boundary=’$boundary'";

      154. What is the difference between Reply-to and Return-path in the headers of a mail function?
Reply-to: Reply-to is where to deliver the reply of the mail.
Return-path:  Return path is when there is a mail delivery failure occurs then where to deliver the failure notification.

      155. Explain about Type Juggling in php?
PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.
An example of PHP’s automatic type conversion is the addition operator ‘+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted   as integers, and the result will also be an integer.  Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.
$foo += 2; //$foo is now an integer (2)
$foo = Sfoo + 1.3; // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small pigs"; // $foo is integer (15)
If the last two examples above seem odd, see string conversion to numbers.
If you wish to change the type of a variable, see settypef).
If you would like to test any of the examples in this section, you can use the var_dump () function.
Note: The behavior of an automatic conversion to array is currently undefined.
Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem should $a become an array with its first element being “f", or should "f' become the first character of

      156. How to Turn on the Session Support in PHP?
The session support can be turned on automatically at the site level, or manually in each PHP page script
* Turning on session support automatically   at the site level: Set session.auto_start= 1 in php.ini.
* Turning on session support manually in each page script:  Call session_start() function,

      157. Explain the ternary conditional operator in PHP'?
Expression preceding the. ? is evaluated,  if it's  true, then the expression  preceding  the : is executed,  otherwise,  the expression  following:   is executed.

      158. How to Read the Entire File into a Single String?
If you have a file, and you want to read the entire file into a single string, you can use the file_get_contents()   function.  It opens the specified file, reads all characters ill the file, and returns them in a single string. Here is a PHP script example on how to file_get_ contents():
$file = file _get_ contents("/windows/system32/drivers/etc/services");
print("Size  of the file: ".strlen($file). "n");
?>
This script will print:  Size of the file: 7116

       159. What is the difference between Get & Post method?
Action
GET method
POST method
Back Button /Reload
Harmless
Data will be re-submitted ( the browser should alert user that the data are about to be re-submitted)
Bookmarked
Can be bookmarked
Can’t be bookmarked
Cached
Can be cached
Can’t be cached
Encoding Type
Application/ x-www-form-url encoded
Application/ x-www-form-url encoded or multipart/form-data. Use multipart encoding for binary data.
History
Parameters remains in browser history
Parameters are not saved in browser history
Restrictions on data length
Yes, When sending data, Get method add the data to url, length of url is limited (max length is 2048 characters)
No restrictions
Restrictions on data type
Only ASCII characters allowed
No restrictions, Binary Data is also allowed
Security
GET is less secure compared to POST because data sent is part of the url. Never use GET when sending passwords or other sensitive information.
POST is little safer than GET because parameters are not stored in browser history or in web server.
Visibility
Data is visible to everyone in URL
Data is not displayed in URL





1 comment:

Anonymous said...

Thank you for the auspicious writeup. It in fact was a amusement account
it. Look advanced to more added agreeable from you! However,
how can we communicate?

Also visit my site ... rumah dijual di jogja