Top 50 Php Interview Questions
Q1. How Many Ways We Can Pass The Variable Through The Navigation Between The Pages?
At least three methods:
@Put the variable into session in the first page, and get it returned from consultation in the next page.
@Put the variable into cookie inside the first web page, and get it again from the cookie within the next web page.
@Put the variable into a hidden shape field, and get it again from the form within the subsequent web page.
Q2. How To Create A Table?
If you want to create a desk, you can run the CREATE TABLE declaration as shown in the following pattern 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'll get some thing like this:
Table fyi_links created.
Q3. How Cookies Are Trported From Browsers To Servers?
Cookies are trported from a Web browser to a Web server inside the header area of the HTTP request message. Each cookie may be covered in a separate "Cookie:" header line within the following layout:
GET / HTTP/1.1
Cookie: name1=value1
Cookie: name2=value2
Cookie: name3=value3
......
Accept: */*
Q4. How Can We Repair A Mysql Table?
The syntex for repairing a mysql desk is:
REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR TABLE tablename EXTENDED
This command will repair the table designated.
If QUICK is given, MySQL will do a restore of best the index tree.
If EXTENDED is given, it will create index row via row.
Q5. How Do You Call A Constructor For A Parent Class?
Determine::constructor($cost).
Q6. What's The Difference Between Md5(), Crc32() And Sha1() Crypto On Php?
The principal difference is the period of the hash generated. CRC32 is, obviously, 32 bits, while sha1() returns a 128 bit cost, and md5() returns a 160 bit fee. This is important when fending off collisions.
Q7. Give The Syntax Of Revoke Commands?
The widely wide-spread 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 and so on.
We can supply rights on all databse by using usingh *.* or a few specific database by database.* or a particular table by database.Table_name.
Q8. When You Want To Show Some Part Of A Text Displayed On An Html Page In Red Font Color? What Different Possibilities Are There To Do This? What Are The Advantages/hazards Of These Methods?
There are 2 ways to reveal some part of a textual content in purple:
@Using HTML tag <font color="red">
@Using HTML tag </font>
Q9. How Do You Pass A Variable By Value?
Just like in C++, put an ampersand in front of it, like $a = &$b.
Q10. How Do I Find Out The Number Of Parameters Passed Into Function9?
Func_num_args() feature returns the variety of parameters handed in.
Q11. What Is The Difference Between Ereg_replace() And Eregi_replace()?
Eregi_replace() characteristic is same to ereg_replace() except that it ignores case difference whilst matching alphabetic characters.
Q12. How Can We Find The Number Of Rows In A Table Using Mysql?
Use this for MySQL
SELECT COUNT(*) FROM table_name;
Q13. What Is Meant By Mime?
MIME is Multipurpose Internet Mail Extensions is an Internet wellknown for the format of email. However browsers also uses MIME trendy to trmit files. MIME has a header that is introduced to a starting of the statistics. When browser sees such header it suggests the statistics as it might be a file (for example picture) Some examples of MIME kinds:
audio/x-ms-wmp
photo/png
software/x-shockwave-flash
Q14. How To Create A Directory?
You can use the mkdir() feature to create a listing. 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's going to print:
Directory already exists.
Q15. How Arrays Are Passed Through Arguments?
Like a everyday variable, an array is handed through an issue by way of fee, no longer through reference. That me whilst an array is handed as an issue, a copy of the array could be surpassed into the feature. Modipickzyng that reproduction in the function will no longer effect the original replica. Here is a PHP script on passing arrays with the aid of 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,three,four,2
After shrinking: five,7,6,2,1,three,four,2
As you could see, unique variables have been not affected.
Q16. What Is An Array In Php?
An array in PHP is in reality an ordered map of pairs of keys and values.
Comparing with Perl, an array in PHP isn't always like a everyday array in Perl. An array in PHP is like an accomplice array in Perl. But an array in PHP can paintings like a everyday array in Perl.
Comparing with Java, an array in PHP is not like an array in Java. An array in PHP is sort of a TreeMap class in Java. But an array in PHP can work like an array in Java.
Q17. How The Values Are Ordered In An Array?
PHP says that an array is an ordered map. But how the values are ordered in an array?
The wer is easy. Values are saved inside the identical order as they may be inserted like a queue. If you need to reorder them otherwise, you want to apply a kind characteristic. 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
)
Q18. How Can I Make A Script That Can Be Bilingual (supports English, German)?
You can change char set variable in above line in the script to guide bi language.
Q19. How To Connect To Mysql From A Php Script?
If you need get right of entry to the MySQL server, you should create a connection object first through calling the mysql_connect() characteristic in the following layout:
$con = mysql_connect($server, $username, $password);
If you are connecting to a nearby MySQL server, you don't want to specify username and password. If you are connecting to a MySQL server supplied via your Web web hosting business enterprise, they'll offer you the server name, username, and password.
The following script suggests you ways to connect to a neighborhood MySQL server, obtained server data, and closed the relationship:
<?Php
$con = mysql_connect('localhost');
print(mysql_get_server_info($con)."n");
print(mysql_get_host_info($con)."n");
mysql_close($con);
?>
Q20. What Is The Difference Between Reply-to And Return-course In The Headers Of A Mail Function?
Reply-to : Reply-to is where to shipping the reply of the mail.
Return-direction : Return direction is whilst there may be a mail transport failure occurs then in which to shipping the failure notification.
Q21. 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/blended; boundary="$boundary"";
Q22. What's Php?
The PHP Hypertext Preprocessor is a programming language that lets in web developers to create dynamic content material that interacts with databases. PHP is largely used for growing net based totally software programs.
Q23. How Can We Encrypt The Username And Password Using Php?
You can encrypt a password with the subsequent Mysql>SET
PASSWORD=PASSWORD("Password");
Q24. How Can We Know The Number Of Days Between Two Given Dates Using Mysql?
Use DATEDIFF()
SELECT DATEDIFF(NOW(),'2006-07-01');
Q25. What Is A Persistent Cookie?
A persistent cookie is a cookie that is stored in a cookie document completely at the browser's computer. By default, cookies are created as brief cookies which stored only within the browser's memory. When the browser is closed, transient cookies will be erased. You have to determine when to use transient cookies and whilst to apply chronic cookies primarily based on their differences:
· Temporary cookies can not be used for tracking lengthy-time period information.
· Persistent cookies may be used for monitoring long-term facts.
· Temporary cookies are safer because no packages apart from the browser can get right of entry to them.
· Persistent cookies are much less cozy because users can open cookie files see the cookie values.
Q26. What Is Meant By Urlencode And Urldecode?
Urlencode() returns the URL encoded version of the given string. URL coding converts unique characters into % symptoms observed by using hex digits. For instance: urlencode("10.00%") will return "10p.C2E00%25". URL encoded strings are secure for use as a part of URLs.
Urldecode() returns the URL decoded version of the given string.
Q27. What Are The Advantages And Disadvantages Of Cascade Style Sheets?
External Style Sheets
Advantages
Can control patterns for more than one files immediately Classes may be created to be used on multiple HTML detail types in many files Selector and grouping strategies may be used to apply styles below complicated contexts
Disadvantages
An extra download is needed to import style statistics for every record The rendering of the file can be behind schedule till the external fashion sheet is loaded Becomes slightly unwieldy for small portions of style definitions
Embedded Style Sheets
Advantages
Classes can be created to be used on a couple of tag sorts within the document Selector and grouping techniques may be used to apply styles below complicated contexts No additional downloads important to receive style data
Disadvantage
This approach can't manipulate styles for more than one files at once
Inline Styles
Advantages
Useful for small quantities of fashion definitions Can override other style specification techniques on the local stage so only exceptions need to be indexed together with other fashion strategies
Disadvantages
Does no longer distance fashion information from content (a chief purpose of SGML/HTML) Can no longer manipulate patterns for more than one documents without delay Author can't create or control training of factors to manipulate a couple of element sorts within the report Selector grouping techniques can not be used to create complicated detail addressing scenarios
Q28. In How Many Ways We Can Retrieve Data In The Result Set Of Mysql Using Php?
Mysql_fetch_array - Fetch a end result row as an associative array, a numeric array, or each
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 end result row as an enumerated array
Q29. What Is A Session?
A session is a logical item created by using the PHP engine to can help you maintain records throughout next HTTP requests.
There is best one session object to be had on your PHP scripts at any time. Data stored to the session by a script may be retrieved via the equal script or every other script whilst asked from the same vacationer.
Sessions are generally used to shop brief information to permit more than one PHP pages to provide a entire practical traction for the same traveler.
Q30. Are Objects Passed By Value Or By Reference?
Everything is passed by way of price.
Q31. What Are The Different Types Of Errors In Php?
Here are three simple styles of runtime mistakes in PHP:
Notices: These are trivial, non-crucial mistakes that PHP encounters even as executing a script - as an example, gaining access to a variable that has no longer but been described. By default, such mistakes are not displayed to the user at all - even though you may trade this default behavior.
Warnings: These are more critical errors - as an example, trying to encompass() a report which does not exist. By default, those mistakes are displayed to the consumer, but they do not result in script termination.
Fatal errors: These are vital errors - as an example, instantiating an item of a nonexistent elegance, or calling a non-existent feature. These mistakes purpose the on the spot termination of the script, and PHP's default behavior is to display them to the person after they take location.
Internally, those variations are represented by using twelve one-of-a-kind error sorts.
Q32. How To Define A User Function?
You can define a person characteristic anywhere in a PHP script using the function assertion like this: "characteristic name() ...". Here is a PHP script example on the way to define a user feature:
<?Php
function msg()
print("Hello world!N");
msg();
?>
This script will print:
Hello world!
Q33. How To Get The Number Of Characters In A String?
You can use the "strlen()" feature to get the quantity of characters in a string. Here is a PHP script instance of strlen():
<?Php
print(strlen('It's Friday!'));
?>
This script will print:
12
Q34. How To Remove A File?
If you want to do away with an existing file, you can use the unlink() function. Here is a PHP script example on a way 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's going to print:
File does no longer exist.
Q35. How To Randomly Retrieve A Value From An Array?
If you have got a listing of preferred greeting messages, and need to randomly pick certainly one of them to be used in an e-mail, you could use the array_rand() function. Here is a PHP instance 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!
Q36. How To Define A Function With Any Number Of Arguments?
If you need to define a characteristic with any number of arguments, you want to:
•Declare the characteristic with out a argument.
•Call func_num_args() within the function to get the variety of the arguments.
•Call func_get_args() in the function to get all of the arguments in an array.
Here is a PHP script on a way to handle any range 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
Q37. Is It More Secure To Use Cookies To Trfer Session Ids?
Yes, because attacking your Web website online the use of URL parameters is a whole lot easier than the use of cookies.
So in case you are the system administrator of your Web server, you ought to set session.Use_only_cookies=1.
If your Web server is furnished by way of a web hosting provider company, ask them to set session.Use_only_cookies=1.
Q38. How Can We Change The Name Of A Column Of A Table?
MySQL query to rename desk: RENAME TABLE tbl_name TO new_tbl_name
or,
ALTER TABLE tableName CHANGE OldName newName.
Q39. How To Reset/ruin A Cookie ?
Reset a cookie with the aid of specifying expire time inside the beyond:
Example: setcookie('Test',$i,time()-3600); // already expired time
Reset a cookie by way of specifying its name best
Example: setcookie('Test');
Q40. How Variables Are Passed Through Arguments?
Like greater of different programming languages, variables are handed thru arguments by values, now not by references. That me whilst a variable is passed as a controversy, a replica of the fee will be exceeded into the function. Modipickzyng that replica within the function will now not effect the unique replica. 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 may see, authentic variables had been not affected.
Q41. How To Remove Leading And Trailing Spaces From User Input Values?
If you're taking input values from users with a Web shape, users may additionally input extra spaces at the start and/or the end of the input values. You have to always use the trim() characteristic to remove those more areas as shown on this PHP script:
<?Php
$name = $_REQUEST("name");
$name = trim($name);
# $name is ready to be used...
?>
Q42. What Is Meant By Nl2br()?
Nl2br() inserts a HTML tag
before all new line characters n in a string.
Echo nl2br("god bless n you");
output:
god bless
you
Q43. What Are The Different Ways To Login To A Remote Server? Explain The Me, Advantages And Disadvantages?
There is at least 3 approaches to logon to a faraway server:
Use ssh or telnet if you concern with security
You also can use rlogin to logon to a far flung server.
Q44. What Is The Functionality Of The Function Strstr And Stristr?
Strstr() returns part of a given string from the primary occurrence of a given substring to the cease of the string. For instance: strstr("consumer@example.Com","@") will return "@example.Com".
Stristr() is idential to strstr() besides that it is case insensitive.
Q45. Who Is The Father Of Php And What Is The Current Version Of Php And Mysql?
Rasmus Lerdorf.
PHP five.@Beta
MySQL five.Zero
Q46. How Can We Get Second Of The Current Time Using Date Function?
$2nd = date("s");
Q47. How Many Values Can The Set Function Of Mysql Take?
MySQL SET function can take zero or more values, however on the most it may take sixty four values.
Q48. How To Generate A Character From An Ascii Value?
If you want to generate characters from ASCII values, you can use the chr() function.
Chr() takes the ASCII fee in decimal format and returns the man or woman represented by way of the ASCII value. Chr() complements ord(). Here is a PHP script on a way 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
seventy two
Q49. What Is 'glide' Property In Css?
The waft assets sets in which an photograph or a text will seem in some other element.
Q50. What Is The Difference Between Group By And Order By In Sql?
To sort a result, use an ORDER BY clause.
The maximum general manner to meet a GROUP BY clause is to test the complete desk and create a brand new transient table in which all rows from each group are consecutive, and then use this brief desk to find out businesses and follow mixture functions (if any). ORDER BY [col1],[col2],...[coln]; Tells DBMS in step with what columns it must sort the result. If two rows may have the same price in col1 it'll try to sort them in line with col2 and so forth.
GROUP BY [col1],[col2],...[coln]; Tells DBMS to institution (aggregate) results with same fee of column col@You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to be counted all items in organization, sum all values or view average.
