Top 50 Php Interview Questions You Must Prepare 19.May.2024

At least 3 ways:
@Put the variable into session in the first page, and get it back from session in the next page.
@Put the variable into cookie in the first page, and get it back from the cookie in the next page.
@Put the variable into a hidden form field, and get it back from the form in the next page.

If you want to create a table, you can run the CREATE TABLE statement as shown in the following sample script:

  <?php  include "mysql_connection.php";  $sql = "CREATE TABLE fyi_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 fyi_links created.n");  } else {  print("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 fyi_links created.

Cookies are trported from a Web browser to a Web server in the header area of the HTTP request message. Each cookie will be included in a separate "Cookie:" header line in the following format:
GET / HTTP/1.1
Cookie: name1=value1
Cookie: name2=value2
Cookie: name3=value3
......
Accept: */*

The syntex 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.

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.

The generic syntax for revoke is as following
REVOKE [rights] on [database] FROM [username@hostname]

Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.

We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.

Just like in C++, put an ampersand in front of it, like $a = &$b.

func_num_args() function returns the number of parameters passed in.

eregi_replace() function is identical to ereg_replace() except that it ignores case distinction when matching alphabetic characters.

Use this for MySQL
SELECT COUNT(*) FROM table_name;

MIME is Multipurpose Internet Mail Extensions is an Internet standard for the format of e-mail. However browsers also uses MIME standard to trmit files. MIME has a header which is added to a beginning of the data. When browser sees such 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

You can use the mkdir() function to create a directory. Here is a PHP script example on how to use mkdir():
<?php
if (file_exists("/temp/download")) {
print("Directory already exists.n");
} else {
mkdir("/temp/download");
print("Directory created.n");
}
?>
This script will print:
Directory created.
If you run this script again, it will print:
Directory already exists.

Like a normal variable, an array is passed through an argument by value, not by reference. That me when an array is passed as an argument, a copy of the array will be passed into the function. Modipickzyng that copy inside the function will not impact the original copy. Here is a PHP script on passing arrays by values:
<?php
function shrink($array) {
array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before shrinking: ".join(",",$numbers)."n");
shrink($numbers);
print("After shrinking: ".join(",",$numbers)."n");
?>
This script will print:
Before shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5,7,6,2,1,3,4,2
As you can see, original variables were not affected.

An array in PHP is really an ordered map of pairs of keys and values.
Comparing with Perl, an array in PHP is not like a normal array in Perl. An array in PHP is like an associate array in Perl. But an array in PHP can work like a normal array in Perl.
Comparing with Java, an array in PHP is not like an array in Java. An array in PHP is like a TreeMap class in Java. But an array in PHP can work like an array in Java.

PHP says that an array is an ordered map. But how the values are ordered in an array?
The wer is simple. Values are stored in the same order as they are inserted like a queue. If you want to reorder them differently, you need to use a sort function. Here is a PHP script show you the order of array values:
<?php
$mixed = array();
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
$mixed["Two"] = "";
unset($mixed[4]);
print("Order of array values:n");
print_r($mixed);
?>
This script will print:
Order of array values:
Array
(
[Two] =>
[3] => C+
[Zero] => PHP
[1] => Perl
[] => Basic
[5] => FORTRAN
)

You can change char set variable in above line in the script to support bi language.

If you want access the MySQL server, you must create a connection object first by calling the mysql_connect() function in the following format:
$con = mysql_connect($server, $username, $password);
If you are connecting to a local MySQL server, you don't need to specify username and password. If you are connecting to a MySQL server offered by your Web hosting company, they will provide you the server name, username, and password.
The following script shows you how to connect to a local MySQL server, obtained server information, and closed the connection:
<?php
$con = mysql_connect('localhost');
print(mysql_get_server_info($con)."n");
print(mysql_get_host_info($con)."n");
mysql_close($con);
?>

Reply-to : Reply-to is where to delivery the reply of the mail.

Return-path : Return path is when there is a mail delivery failure occurs then where to delivery the failure notification.

$boundary = '--' . md5( uniqid ( rand() ) );
$headers = "From: "Me"n";
$headers .= "MIME-Version: 1.0n";
$headers .= "Content-Type: multipart/mixed; boundary="$boundary"";

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.

You can encrypt a password with the following Mysql>SET
PASSWORD=PASSWORD("Password");

Use DATEDIFF()
SELECT DATEDIFF(NOW(),'2006-07-01');

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 can not be used for tracking long-term information.
· Persistent cookies can be used for tracking long-term information.
· Temporary cookies are safer because no programs other than the browser can access them.
· Persistent cookies are less secure because users can open cookie files see the cookie values.

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.

External Style Sheets
Advantages
Can control styles for multiple documents at once Classes can be created for use on multiple HTML element types in many documents Selector and grouping methods can be used to apply styles under complex contexts

Disadvantages

An extra download is required to import style information for each document The rendering of the document may be delayed until the external style sheet is loaded Becomes slightly unwieldy for small quantities of style definitions

Embedded Style Sheets
Advantages
Classes can be created for use on multiple tag types in the document Selector and grouping methods can be used to apply styles under complex contexts No additional downloads necessary to receive style information

Disadvantage

This method can not control styles for multiple documents at once

Inline Styles
Advantages
Useful for small quantities of style definitions Can override other style specification methods at the local level so only exceptions need to be listed in conjunction with other style methods

Disadvantages

Does not distance style information from content (a main goal of SGML/HTML) Can not control styles for multiple documents at once Author can not create or control classes of elements to control multiple element types within the document Selector grouping methods can not be used to create complex element addressing scenarios

mysql_fetch_array - Fetch a result row as an associative array, a numeric array, or both
mysql_fetch_assoc - Fetch a result row as an associative array
mysql_fetch_object - Fetch a result row as an object
mysql_fetch_row - Get a result row as an enumerated array

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 traction for the same visitor.

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

You can define a user function anywhere in a PHP script using the function statement like this: "function name() {...}". Here is a PHP script example on how to define a user function:
<?php
function msg() {
print("Hello world!n");
}
msg();
?>
This script will print:
Hello world!

You can use the "strlen()" function to get the number of characters in a string. Here is a PHP script example of strlen():
<?php
print(strlen('It's Friday!'));
?>
This script will print:
12

If you want to remove an existing file, you can use the unlink() function. Here is a PHP script example on how to use unlink():
<?php
if (file_exists("/temp/todo.txt")) {
unlink("/temp/todo.txt");
print("File removed.n");
} else {
print("File does not exist.n");
}
?>
This script will print:
File removed.
If you run this script again, it will print:
File does not exist.

If you have a list of favorite greeting messages, and want to randomly select one of them to be used in an email, you can use the array_rand() function. Here is a PHP example script:
<?php
$array = array("Hello!", "Hi!", "Allo!", "Hallo!", "Coucou!");
$key = array_rand($array);
print("Random greeting: ".$array[$key]."n");
?>
This script will print:
Random greeting: Coucou!

If you want to define a function with any number of arguments, you need to:
•Declare the function with no argument.
•Call func_num_args() in the function to get the number of the arguments.
•Call func_get_args() in the function to get all the arguments in an array.
Here is a PHP script on how to handle any number of arguments:
<?php
function myAverage() {
$count = func_num_args();
$args = func_get_args();
$sum = array_sum($args);
return $sum/$count;
}
$average = myAverage(102, 121, 105);
print("Average 1: $averagen");
$average = myAverage(102, 121, 105, 99, 101, 110, 116, 101, 114);
print("Average 2: $averagen");
?>
This script will print:
Average 1: 109.33333333333
Average 2: 107.66666666667

yes, because attacking your Web site using URL parameters is much easier than using cookies.
So if you are the system administrator of your Web server, you should set session.use_only_cookies=1.
If your Web server is provided by a hosting service provider, ask them to set session.use_only_cookies=1.

MySQL query to rename table: RENAME TABLE tbl_name TO new_tbl_name
or,
ALTER TABLE tableName CHANGE OldName newName.

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');

Like more of other programming languages, variables are passed through arguments by values, not by references. That me when a variable is passed as an argument, a copy of the value will be passed into the function. Modipickzyng that copy inside the function will not impact the original copy. Here is a PHP script on passing variables by values:
<?php
function swap($a, $b) {
$t = $a;
$a = $b;
$b = $t;
}
$x = "PHP";
$y = "JSP";
print("Before swapping: $x, $yn");
swap($x, $y);
print("After swapping: $x, $yn");
?>
This script will print:
Before swapping: PHP, JSP
After swapping: PHP, JSP
As you can see, original variables were not affected.

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:
<?php
$name = $_REQUEST("name");
$name = trim($name);
# $name is ready to be used...
?>

nl2br() inserts a HTML tag
before all new line characters n in a string.

echo nl2br("god bless n you");

output:
god bless
you

There is at least 3 ways to logon to a remote server:
Use ssh or telnet if you concern with security
You can also use rlogin to logon to a remote server.

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 idential to strstr() except that it is case insensitive.

MySQL SET function can take zero or more values, but at the maximum it can take 64 values.

If you want to generate characters from ASCII values, you can use the chr() function.
chr() takes the ASCII value in decimal format and returns the character represented by the ASCII value. chr() complements ord(). Here is a PHP script on how to use chr():
<?php
print(chr(72).chr(101).chr(108).chr(108).chr(111)."n");
print(ord("H")."n");
?>
This script will print:
Hello
72

The float property sets where an image or a text will appear in another element.

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],[col2],...[coln]; Tells DBMS according to what columns it should sort the result. If two rows will have the same value in col1 it will try to sort them according to col2 and so on.

GROUP BY [col1],[col2],...[coln]; Tells DBMS to group (aggregate) results with same value of column col@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.