PHP Interview Questions - 001
PHP Interview Questions - 001
PHP Interview Questions - 001
Who is the father of PHP ? Rasmus Lerdorf is known as the father of PHP. What is the difference between $name $name is variable where as $$name is like $name=sonia and $$name=singh so $sonia value is singh. How can we submit a form without a submit button? Java script submit() function is used for submit on click call document.formname.submit() and reference $$name? variable
form
without
submit
button
In how many ways we can retrieve the data in the result set of MySQL using PHP? We can do it by 4 Ways 1. mysql_fetch_row. , 2. mysql_fetch_array , 3. mysql_fetch_object 4. mysql_fetch_assoc What is the difference between mysql_fetch_object and mysql_fetch_array? mysql_fetch_object() is similar tomysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names). What are the differences between Get and post methods. There are some defference between GET and POST method 1. GET Method have some limit like only 2Kb data able to send for request But in POST method unlimited data can we send 2. when we use GET method requested data show in url but Not in POST method so POST method is good for send sensetive request How can we extract string "pcds.co.in " from a string "http://info@pcds.co.in using regular expression of PHP? preg_match("/^http:\/\/.+@(.+)$/","http://info@pcds.co.in",$matches); echo $matches[1]; How can we create a database using PHP and MySQL? We can create MySQL database mysql_create_db("Database Name")
with
the
use
of
What are the differences between require and include? Both include and require used to include a file but when included file not found Include send Warning where as Require send Fatal Error .
# 26/34, 2nd A, 50 Feet Main Road, T.G. Layout, Ittamadu, BSK III Stage, Bengaluru 560085 Can we use include ("xyz.PHP") two times in a PHP page "index.PHP"? Yes we can use include("xyz.php") more than one time in any page. but it create a prob when xyz.php file contain some funtions declaration then error will come for already declared function in this file else not a prob like if you want to show same content two time in page then must incude it two time not a prob What are the different tables(Engine) present in MySQL, which one is default? Following tables (Storage Engine) we can create 1. MyISAM(The default storage engine IN MYSQL Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. An .frm file stores the table format. The data file has an .MYD (MYData) extension. The index file has an .MYI (MYIndex) extension. ) 2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data.) 3. Merge 4. Heap (MEMORY)(The MEMORY storage engine creates tables with contents that are stored in memory. Formerly, these were known as HEAP tables. MEMORY is the preferred term, although HEAP remains supported for backward compatibility. ) 5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL with the Berkeley DB transactional storage engine. This storage engine typically is called BDB for short. BDB tables may have a greater chance of surviving crashes and are also capable of COMMIT and ROLLBACK operations on transactions) 6. EXAMPLE 7. FEDERATED (It is a storage engine that accesses data in tables of remote databases rather than in local tables. ) 8. ARCHIVE (The ARCHIVE storage engine is used for storing large amounts of data without indexes in a very small footprint. ) 9. CSV (The CSV storage engine stores data in text files using comma-separated values format.) 10. BLACKHOLE (The BLACKHOLE storage engine acts as a "black hole" that accepts data but throws it away and does not store it. Retrievals always return an empty result What is use of header() function in php ? The header() function sends a raw HTTP header to a client.We can use herder() function for redirection of pages. It is important to notice that header() must be called before any actual output is seen.. How can I execute a PHP script using command line? Just run the PHP CLI (Command Line Interface) provide the PHP script file name as the command line argument. Suppose your Zend engine supports the mode <? configure your PHP Zend engine to support <?PHP ?> mode In php.ini file: set short_open_tag=on to make PHP support ?> Then
program
and
how
can
# 26/34, 2nd A, 50 Feet Main Road, T.G. Layout, Ittamadu, BSK III Stage, Bengaluru 560085 Shopping cart online validation i.e. how can we etc.? Nothing more we have to do only redirect to the submit all information needed by paypal like amount,adresss etc. What is meant by nl2br()? Inserts HTML line breaks (<BR />) before all newlines in a string. What is htaccess? Why do we use this and Where? htaccess files are configuration files of Apache Server which provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof. How we get IP address of client, previous reference page etc ? By using $_SERVER['REMOTE_ADDR'],$_SERVER['HTTP_REFERER'] etc. What are the reasons for selecting lamp (Linux, apache, MySQL, PHP) instead of combination of other software programs, servers and operating systems? All of those are open source resource. Security of Linux is very very more than windows. Apache is a better server that IIS both in functionality and security. MySQL is world most popular open source database. PHP is more faster that asp or any other scripting language. How can we encrypt and decrypt using MySQL? AES_ENCRYPT () and AES_DECRYPT () a data present in a MySQL table configure payPal url Paypal, after
How can we encrypt the username and password using PHP? The functions in this section perform encryption compression and uncompression:
encryption AES_ENCRYT() ENCODE() DES_ENCRYPT() ENCRYPT() MD5() PASSWORD() SHA() or SHA1() Not available decryption AES_DECRYPT() DECODE() DES_DECRYPT() Not available Not available Not available Not available UNCOMPRESSED_LENGTH()
and
decryption,
and
# 26/34, 2nd A, 50 Feet Main Road, T.G. Layout, Ittamadu, BSK III Stage, Bengaluru 560085 What are the features and advantages of object-oriented programming? One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system What are the differences between procedure-oriented languages and object-oriented languages? There are lot of difference between procedure language and object oriented like below 1>Procedure language easy for new developer but complex to understand whole software as compare to object oriented model 2>In Procedure language it is difficult to use design pattern mvc , Singleton pattern etc but in OOP you we able to develop design pattern 3>IN OOP language we able to ree use code like Inheritance ,polymorphism etc but this type of thing not available in procedure language on that our Fonda use COPY and PASTE . What is the use of friend function? 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. What are the differences between public, private, protected, static, transient, final and volatile? Public: Public declared items can be accessed everywhere. Protected: Protected limits access to inherited and parent classes (and to the class that defines the item). Private: Private limits visibility only to the class that defines the item.
# 26/34, 2nd A, 50 Feet Main Road, T.G. Layout, Ittamadu, BSK III Stage, Bengaluru 560085 Static: A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Final: Final keyword prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended. transient: A transient variable is a variable that may not be serialized. volatile: a variable that might be concurrently modified by multiple threads should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at any time. What is the functionality of the function strstr and stristr? strstr Returns part of string from the first occurrence of needle(sub string that we finding out ) to the end of string. $email= 'sonialouder@gmail.com'; $domain = strstr($email, '@'); echo $domain; // prints @gmail.com here @ is the needle stristr is case-insensitive means able not able to differentiate between a and A What is the functionality of the function htmlentities? Convert all applicable characters to HTML This function is identical to htmlspecialchars() in all ways, with htmlentities(), all characters which have HTML character equivalents are translated into these entities.
second
of
the
current
time
using
date
function?
What is meant by urlencode and urldocode? URLencode returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. urldecode decodes any %## encoding in the given string. What is the difference between the functions unlink and unset? unlink() deletes the given file from unset() makes a variable undefined.
the
file
system.
# 26/34, 2nd A, 50 Feet Main Road, T.G. Layout, Ittamadu, BSK III Stage, Bengaluru 560085 How can we register the variables into a session? $_SESSION['name'] = "sonia"; How can we get the properties (size, image using PHP image functions? To know the Image type use exif_imagetype () function To know the Image size use getimagesize () function To know the image width use imagesx () function To know the image height use imagesy() function t How can we get the browser properties using PHP? By using
$_SERVER['HTTP_USER_AGENT'] variable.
type,
width,
height)
of
an
What is the maximum size of a file that and how can we change this? By default the maximum size is 2MB. and setup at php.iniupload_max_filesize = 2M
can we
be can
uploaded change
using the
PHP
following
How can we increase the execution time of a PHP script? by changing the following setup at php.inimax_execution_time = 30 ; Maximum execution time of each script, in seconds How can query?
we
optimize
or
increase
the
speed
of
MySQL
select
first of all instead of using select * from column1, column2, column3.. from table1 Look for the opportunity to introduce index in querying. use limit keyword if you are looking for any rows from the result set.
use you
select are of
specific
number
How many ways can we get the value of current session id? session_id() returns the session id for the current session. How can we set and destroy the cookie n php? By using setcookie(name, value, expire, path, domain); function we can set the cookie in php ; Set the cookies in past for destroy. like setcookie("user", "sonia", time()+3600); for set the cookie setcookie("user", "", time()-3600); for destroy or delete the cookies
# 26/34, 2nd A, 50 Feet Main Road, T.G. Layout, Ittamadu, BSK III Stage, Bengaluru 560085 How many ways between the pages?
we
can
pass
the
variable
through
the
navigation
GET/QueryString POST
What are the different functions in sorting an array? Sort(), arsort(), asort(), ksort(), natsort(), natcasesort(), rsort(), usort(), array_multisort(), and uksort().
How can we know the count/number of elements of an array? 2 ways a) sizeof($urarray) This function is an alias of count() b) count($urarray)
What is session_set_save_handler in PHP? session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database. How can I know that a variable is a number or not using a JavaScript? bool is_numeric ( mixed var) Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number. List out some mysql. Case Studio Smart Draw tools through which we can draw E-R diagrams for
# 26/34, 2nd A, 50 Feet Main Road, T.G. Layout, Ittamadu, BSK III Stage, Bengaluru 560085 List out the predefined classes in PHP? Directory stdClass __PHP_Incomplete_Class exception php_user_filter How can I make a script that can be bi-language (supports English, German)? You can maintain two separate language file for each of the language. all the labels are putted in both language files as variables and assign those variables in the PHP source. on runtime choose the required language option. What are the difference 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. How can we send mail using JavaScript? JavaScript does not have any networking capabilities as it is designed to work on client site. As a result we can not send mails using JavaScript. But we can call the client side mail protocol mailto via JavaScript to prompt for an email to send. this requires the client to approve it. How can we repair a MySQL table? The syntex for repairing a MySQL table is REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended] This command will repair the table specified if the quick is given the MySQL will do a repair of only the index tree if the extended is given it will create index row by row What are the advantages of stored procedures, triggers, indexes? 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
# 26/34, 2nd A, 50 Feet Main Road, T.G. Layout, Ittamadu, BSK III Stage, Bengaluru 560085 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 the 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. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks. What is the maximum length of fieldname in MySQL? The following table describes the identifier.
Identifier Maximum Length (bytes) 64 64 64 255
table
name, length
name, type
and of
maximum
some
restrictions
on
the
characters
that
may
appear
in
How many values can the SET function of MySQL take? MySQL set can take zero or more values but take 64 values What are the other commands to know MySQL commands except explain command? describe Table-Name; the
at
the
maximum
it
can
structure
of
table
using
How many tables will create when we create table, what are they? The '.frm' file stores the table definition. The data file has a '.MYD' (MYData) extension. The index file has a '.MYI' (MYIndex) extension,
# 26/34, 2nd A, 50 Feet Main Road, T.G. Layout, Ittamadu, BSK III Stage, Bengaluru 560085 How can we find the number of rows in a table using MySQL? Use this for mysql >SELECT COUNT(*) FROM table_name; How can we find the number of rows in a result set using PHP?
$result = mysql_query($sql, $db_link); $num_rows = mysql_num_rows($result); echo "$num_rows rows found";
How many ways we can we find the current date using MySQL? SELECT CURDATE(); CURRENT_DATE() = CURDATE() for time use SELECT CURTIME(); CURRENT_TIME() = CURTIME() 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'. What is the difference between Primary Key and Unique key? Primary Key: A column in a table whose values uniquely identify the rows in the table. A primary key value cannot be NULL. Unique Key: Unique Keys are used to uniquely identify each row in the table. There can be one and only one row for each unique key value. So NULL can be a unique key.There can be only one primary key for a table but there can be more than one unique for a table. What is garbage collection? default time ? refresh time? Garbage Collection is an automated part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any session files that have not been accessed in a certain amount of time and physically deletes them. Garbage Collection process only runs in the default session save directory, which is /tmp. If you opt to save your sessions in a different directory, the Garbage Collection process will ignore it. the Garbage Collection process does not differentiate between which sessions belong to whom when run. This is especially important note on shared web servers. If the process is run, it deletes ALL files that have not been accessed in the directory. There are 3 PHP.ini variables, which deal with the garbage collector: PHP ini value name default session.gc_maxlifetime 1440 seconds or 24 minutes session.gc_probability 1 session.gc_divisor 100 What are the advantages/disadvantages of MySQL and PHP? Both of them are open source software (so free cross platform. php is faster then ASP and JSP.
of
cost),
support
# 26/34, 2nd A, 50 Feet Main Road, T.G. Layout, Ittamadu, BSK III Stage, Bengaluru 560085 What is the difference between GROUP BY and ORDER BY in Sql? ORDER BY [col1],[col2],,[coln]; Tels DBMS according to what columns it should sort the result. If two rows will hawe the same value in col1 it will try to sort them according to col2 and so on.GROUP BY [col1],[col2],,[coln]; Tels DBMS to group 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 What is the functionality of md5 function in PHP? Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number. I use it to generate keys which I use to identify users etc. If I add random no techniques to it the md5 generated now will be totally different for the same string I am using. How can I load data from a text file into a table? you can use LOAD DATA INFILE file_name; syntax to load data from a text file. but you have to make sure thata) data is delimited b) columns and data matched correctly How can MySQL? we know the number of days between two given dates using
SELECT DATEDIFF("2007-03-07","2005-01-01"); How can we know the number of days between two given dates using PHP? Answer : 80 $date1 = date("Y-m-d"); $date2 = "2006-08-15"; $days = (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24);
How many types of Inheritances used in PHP and how we achieve it As far PHP concern it only support single Inheritance we can also use interface to achieve multiple inheritance.
in
scripting.
What are default session time and path? default session time in PHP is Default session save path id temporary folder /tmp
1440
seconds
or
24
minutes
How to track user logged out or not? when user is idle ? By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes. The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds.
# 26/34, 2nd A, 50 Feet Main Road, T.G. Layout, Ittamadu, BSK III Stage, Bengaluru 560085 If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server. How to track no of user logged in ? whenever a user logs in track the IP, userID etc..and store it in a DB with a active flag while log out or sesion expire make it inactive. At any time by counting the no: of active records we can get the no: of visitors. In PHP for pdf which library used? The PDF functions in PHP can create PDF files using the PDFlib library With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. There is also the Panda module. FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs. FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5 What is design pattern? singleton pattern? A design pattern is a general reusable solution to a commonly occurring problem in software design. The Singleton design pattern allows many parts of a program to share a single resource without having to work out the details of the sharing themselves. What is magic quotes? Magic Quotes is a process that automagically escapes ncoming data to the PHP script. Its preferred to code with magic quotes off and to instead escape the data at runtime, as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged. What is cross site scripting? SQL injection? Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts. SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed What is URL rewriting? Using URL rewriting we can convert dynamic URl to static URL Static URLs are known to be better than Dynamic URLs because of a number of reasons 1. Static URLs typically Rank better in Search Engines. 2. Search Engines are known to index the content of dynamic pages a lot slower compared to static pages. 3. Static URLs are always more friendlier looking to the End Users. along with this we can use URL rewriting in adding variables [cookies] to the URL to handle the sessions.
# 26/34, 2nd A, 50 Feet Main Road, T.G. Layout, Ittamadu, BSK III Stage, Bengaluru 560085 What is the major php security hole? how to avoid? 1. Never include, require, or otherwise open a file with a filename based on user input, without thoroughly checking it first. 2. Be careful with eval() Placing user-inputted values into the eval() function can be extremely dangerous. You essentially give the malicious user the ability to execute any command he or she wishes! 3. Be careful when using register_globals = ON It was originally designed to make programming in PHP easier (and that it did), but misuse of it often led to security holes 4. Never run unescaped queries 5. For protected areas, use sessions or validate the login every time. 6. If you dont want the file contents to be seen, give the file a .php extension. Whether PHP supports Microsoft SQL server ? The SQL Server Driver for PHP v1.0 is designed to enable reliable, scalable integration with SQL Server for PHP applications deployed on the Windows platform. The Driver for PHP is a PHP 5 extension that allows the reading and writing of SQL Server data from within PHP scripts. using MSSQL or ODBC modules we can access Microsoft SQL server. What is MVC? why its been used? Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model. WHY ITS NEEDED IS 1 Modular separation of function 2 Easier to maintain 3 View-Controller separation means: A Tweaking design (HTML) without altering code B Web design staff can modify UI without understanding code What is framework? how it works? what is advantage? In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something useful. Advantages : Consistent Programming Model Direct Support for Security Simplified Development Efforts Easy Application Deployment and Maintenance