Escolar Documentos
Profissional Documentos
Cultura Documentos
PEAR means “PHP Extension and Application Repository.” It is a framework and distribution
system for reusable PHP components. It extends PHP and gives a higher level of
programming for all web developers. PEAR is divided into three different classes that are:
PEAR Core Components, PEAR Packages, and PECL Packages. The PEAR Packages
include functionality giving for authentication, networking, and file system features and tools
for working with HTML and XML templates.
Just use the PHP command line interface (CLI) and specify the file name of
the script to be executed as follows:
php script.php
7) How to run the interactive PHP shell from the command line
interface?
Just use the PHP CLI program with the option -a as follows:
php -a
8) What is the correct and the most two common way to start and
finish a PHP block of code?
The two most common ways to start and finish a PHP script are:
<?php [ --- PHP code---- ] ?> and <? [--- PHP code ---] ?>
To be able to display the output directly to the browser, we have to use the
special tags <?= and ?>.
10) What is the main difference between PHP 4 and PHP 5? What is the
use of “ksort” in php?
PHP 5 is an upgrade version of PHP 4. PHP 5 offers many extra OOPs features. It
introduces new functions which are not found in PHP4.
In PHP 5, Magic methods are introduced such as __call, __get, __set and
__toString.
'final' is introduced in PHP5. Final class means that this class cannot be
extended and a final method cannot be overridden.
PHP and Javascript cannot directly interact since PHP is a server side
language and Javascript is a client-side language. However, we can
exchange variables since PHP can generate Javascript code to be
executed by the browser and it is possible to pass specific variables back
to PHP via the URL.
17) What is the difference between explode() and split() functions? What is
needed to be able to use image function?
Split function splits a string into array by regular expression. Explode splits a string into array
by string.
The GD library is required to be able to do image functions. It also helps to execute more
image functions.
imagetypes() gives the image format and types supported by the current
version of GD-PHP.
19) What are the functions to be used to get the image's properties
(size, width, and height)?
There are three functions are used to get image properties. That functions are:
We can include a file utilizing “include() ” or “require()” function with file path as its
parameter.
There are some failures when using functions include() and require(). If the function
require() cannot access/unable to find the file then it stops the execution of the
script and ends with a fatal error. However, in the same case (file not found)
the include() function gives a warning, and the PHP script continues to
execute (execution will continue). Thios is is the main difference between
these two functions.
require(), and require_once() perform the same task except that the second
function checks if the PHP script is already included or not before executing
it.
22) How can I display text with a PHP script? What is the use of “echo” in
PHP?
24) How to enlarge the execution time of a PHP script? How is it possible to set
an infinite execution time for PHP script?
It is possible to enlarge the execution time of a PHP script by utilizing the set_time_limit
function. It enables to enlarge the execution time of a PHP script.
Fatal Error – These are basically runtime errors which are caused when you try to
access what cannot be done.
Warning Error – This error occurs when you try to include a file that is not present.
Notice Error – This error occurs when you try to utilize a variable that has not been
declared.
b) This is a PHP syntax error expressing that a mistake at the line x stops
parsing and executing the program.
The most common and used way is to get data into a format supported by
Excel. For example, it is possible to write a .csv file, to choose for example
comma as a separator between fields and then to open the file with Excel.
mysql_connect(servername,username,password);
count() function is used for fetching the total number records in a table.
30) How be the result set of Mysql handled in PHP?
34) How can we access the data sent through the URL with the GET
method?
To access the data sent via the GET method, we use $_GET array like this:
www.url.com?var=value
$variable = $_GET["var"]; this will now contain 'value'
35) How can we access the data sent through the URL with the POST
method?
To access the data sent this way, you use the $_POST array.
Imagine you have a form field called 'var' on the form when the user clicks
submit to the post form, you can then access the value like this:
$_POST["var"];
The unlink() function is dedicated for file system handling. It simply deletes
the file given as entry.
40) What does the unset() function mean? What is the difference between
unset() and unlink() function?
unset() function is used to destroy a variable whereas unlink() function is used to destroy a
file.
The addslashes function enables us to escape data before storage into the
database.
We have to enable the Magic quotes entry in the configuration file of PHP.
45) What are tags used for? Is it possible to remove the HTML tags from
data?
They allow making the result of the expression between the tags directly to the browser
response.
The strip_tags() function enables us to clean a string from the HTML tags.
A static variable is defined within a function only the first time, and its value
can be modified during function calls as follows:
54) What are the data types of PHP? How is it possible to cast types in
PHP? What is a numeric array? What function do we use to find length of string, and
length of array?
The name of the output type has to be specified in parentheses before the
variable which is to be cast as follows:
Numeric array − An array with a numeric index. The values are stored and accessed in a
linear fashion.
For finding a length of string we apply strlen() function and for array we use count() function.
When the original if was followed by: and then the code block without
braces.
Expression_1?Expression_2 : Expression_3;
58) If the variable $var1 is set to 10 and the $var2 is set to the
character var1, what's the value of $$var2?
parent::constructor($value)
__sleep returns the array of all the variables that need to be saved, while
__wakeup retrieves them.
$variable2 = 'World';
$variable3 = $variable1.$variable2;
Or
2- $variable3 = "$variable1$variable2";
$variable3 will contain "Hello World". The first code is faster than the
second code especially for large large sets of data.
64) What is session and why do we use it? what is the definition of a
session?
A session is a super global variable that preserves data across subsequent pages. Session
uniquely defines all users with a session ID. So it supports building a customized web
application where user tracking is required.
67) What is cookie and why do we use it? How to Retrieve a Cookie Value? What is
the meaning of a Persistent Cookie?
Sessions automatically end when the PHP script finishes executing but can
be manually ended using the session_write_close().
71) What does $_SERVER mean? What is the default page in web server?
74) How can we get the error when there is a problem to upload a file?
75) How can we change the maximum size of the files to be uploaded?
The scope of a variable is the context within which it is defined. For the
most part, all PHP variables only have a single scope. This single scope
spans included and required files as well.
79) what the difference between the 'BITWISE AND' operator and the
'LOGICAL AND' operator?
$a & $b: Bits that are set in both $a and $b are set.
The first is the concatenation operator ('.'), which returns the concatenation
of its right and left arguments. The second is ('.='), which appends the
argument on the right to the argument on the left.
$a === $b TRUE if $a and $b have the same key/value pairs in the same
order and of the same types.
!= means inequality (TRUE if $a is not equal to $b) and !== means non-
identity (TRUE if $a is not identical to $b).
The goto statement can be placed to enable jumping inside the PHP
program. The target is pointed by a label followed by a colon, and the
instruction is specified as a goto statement followed by the desired target
label.
85) what is the difference between Exception::getMessage and
Exception:: getLine?
The boolean function isset determines if a variable is set and is not NULL.
NULL is a particular type which contains only one value: NULL. If you need any variable to
set NULL, just assign it.
89) What is the difference between the functions strstr() and stristr()?
The string function strstr(string allString, string occ) returns part of allString
from the first occurrence of occ to the end of allString. This function is case-
sensitive. stristr() is identical to strstr() except that it is case insensitive.
90) What types of loops exist in PHP? what is the difference between for and
foreach?
statement
However, foreach provides an easy way to iterate over arrays, and it is only
used with arrays and objects.
91) Is it possible to or how submit a form with a dedicated button?
94) What are the three classes of errors that can occur in PHP?
96) How can we pass the variable through the navigation between the
pages?
It is possible to pass the variables between the PHP pages using sessions,
cookies or hidden form fields.
97) How can you break PHP script? Is it possible to extend the execution
time of a PHP script?
There is not a way to directly delete a cookie. Just use the setcookie function with the
expiration date in the past, to trigger the removal mechanism in your web browser.
102) Explain how you can update Memcached when you make
changes to PHP?
107) What is JOIN in MySQL? What are the different types of join?
MySQL JOINS are utilized to retrieve data from multiple tables. It is performed
whenever two or more tables are joined in a SQL statement. There are various types
of MySQL joins: INNER JOIN, LEFT JOIN, RIGHT JOIN and OUTER JOIN.
You can send an e-mail in PHP with mail() function or SMTP details.
It is not actually a real function, it is a language construct. So you can utilize without
parentheses with its argument list.
SQL injection is a malicious code injection technique that might destroy your
database. It exploiting SQL vulnerabilities in Web applications. It is one of the most
common web hacking techniques.
What is PHP?
PHP is an open source server side scripting language commonly used for web applications.
Software in which the source codes are freely used, modify, and shared by anyone are called Open
Source Software. These can also be distributed under licenses that adhere with the Open Source
Definition.
The include() statement includes and evaluates a specified line i.e. it will include a file based in the
given path. require() does the same thing expect upon failure it will generate a fatal error and halt the
script whereas include() will just gives a warning and allow script to continue. require_once() will check
if the file already has been included and if so it will not include the file again.
GET and POST are used to send information from client browser to web server. In case of GET the
information is send via GET method in name/value pair and is URL encoded. The default GET has a
limit of 512 characters. The POST method transfers the information via HTTP Headers. The POST
method does not have any restriction in data size to be sent. POST is used for sending data securely
and ASCII and binary type’s data. The $_REQUEST contains the content of both $_GET, $_POST
and $_COOKIE.
Parse Error – Commonly caused due to syntax mistakes in codes e.g. missing semicolon, mismatch
brackets.
Fatal Error – These are basically run time errors which are caused when you try to access what can’t
be done. E.g. accessing a dead object, or trying to use a function that hasn’t been declared.
Warning Error – These occurs when u try to include a file that is not present, or delete a file that is
not on the server. This will not halt the script; it will give the notice and continue with the next line of
the script.
Notice Error – These errors occurs when u try to use a variable that hasn’t been declared, this will not
halt the script, It will give the notice and continue with the next line of the script.
Session is a super global variable that preserve data across subsequent pages. Session uniquely
defines each user with a session ID, so it helps making customized web application where user
tracking is needed.
Cookie is a small piece of information stored in client browser. It is a technique used to identify a user
using the information stored in their browser (if already visited that website) . Using PHP we can both
set and get COOKIE.
For finding length of string we use strlen() function and for array we use count() function.
2
3 <?php
4 session_start();
5 echo session_id();
6 ?>
How do we destroy a session.
2
3 <?php session_start(); session_destroy(); ?>
What is the difference between explode() and split() functions?
Both are used to split a string to array, the basic difference is that split() uses pattern for splitting
and explode()uses a string. explode() is faster than split() as it does not match the string based on
regular expression. Also split() is deprecated as of 5.3.0. So using of this function is discouraged.
Associative arrays are arrays that use named keys that you assign to them.
2
3 <?php
4 $capitals=array("India"=>"New Delhi","China"=>"Beijing","Pakistan"=>"Islamabad");
5 ?>
What is PDO classes?
The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing
databases in PHP. It is a data-access abstraction layer, so no matter what database we use the
function to issue queries and fetch data will be same. Using PDO drivers we can connect to database
like DB2, Oracle, PostgreSQL etc.
Javascript is a client side scripting language whereas PHP is a server side scripting language.
What is CSS?
The difference between an ID and Class is that an ID can be used to identify one element, whereas a
class can be used to identify more than one.
We can use javascript submit function. We can either use form name or form id to print
2
3 document.getElementById("formID").submit();
4 document.formname.submit();
Why do we use multipart/form-data in html form?
This is the encoding used to send image or files via form, The data will be split into multiple parts and,
one for each files plus one for the text of the form body that may be sent with them.
What is AJAX?
AJAX (Asynchronous JavaScript and XML) is a technique which allows updating parts of a web page,
without reloading the whole page. Data is exchanged asynchronously in small amounts of data with
the server.
What is jQuery?
jQuery is a fast, small, and feature-rich JavaScript library. It is an easy-to-use API which makes things
like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler
across a multitude of browsers.
2
3 // show div
4 $('#div1').show();
5 // hide div
6 $('#div1').hide();
How can we add change font size using jquery?
Suppose we want change a font size of and div with id div1 from 12px to 18px.
2
3 $('#div1').css('font-size', '18px');
What is the difference between sql and Mysql?
SQL or Structured Query Language is a programming language designed for managing data held in a
Relational Database Management System. Mysql is a open source, relational database management
System.
Group By is used for retrieving information about a group of data. It is generally used with some
aggregate function like SUM, AVG etc. ORDER BY is used to sort the records using column name. It
can sort column in both ascending and descending order.
When we have to fetch records from more than one table we can use JOIN keyword. The process is
known as joining the tables. There are various types of join like INNER JOIN, LEFT JOIN, RIGHT
JOIN, and OUTER JOIN.
Why is the basic difference between LEFT JOIN, RIGHT JOIN and INNER JOIN?
INNER Join compares two tables and only returns results where a match exists. Records from the 1st
table are duplicated when they match multiple results in the 2nd. INNER joins tend to make result sets
smaller, but because records can be duplicated this isn’t guaranteed.
LEFT join means keep all records from the 1st table no matter what and insert NULL values when the
2nd table doesn’t match.
RIGHT Join means the opposite: keep all records from the 2nd table no matter what and insert NULL
values when the 1st table doesn’t match.
If we use SUM function in mysql, does it return sum of that row or for that column?
Sum function works on the column basis and will return the sum of that particular row only.
Suppose take an example where you need to fetch all customer data where name stats with sa
Another case is where you need to fetch all customer data where kumar is found irrespective of the
position (middle name or last name).
Take an example
In this case it will delete the record of the customer with customer id 150
<?php
echo $_SERVER[‘HTTP_USER_AGENT’].”\n\n”;
$browser=get_browser(null,true);
print_r($browser);
?>
5. What Is a Session?
A session is a logical object created by the PHP engine to allow you to preserve data across
subsequent HTTP requests. Sessions are commonly used to store temporary data to allow multiple
PHP pages to offer a complete functional transaction for the same visitor.
<?php
session_register($ur_session_var);
?>
7. How many ways we can pass the variable through the navigation between the pages?
sizeof($array_var)
count($array_var)
mysql_create_db();
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.
The mysql_error() message will tell us what was wrong with our query, similar to the message we
would receive at the MySQL console.
CONSTRUCTOR : PHP allows developers to declare constructor methods for classes. Classes which
have a constructor method call this method on each newly-created object, so it is suitable for any
initialization that the object may need before it is used.
DESTRUCTORS : PHP 5 introduces a destructor concept similar to that of other object-oriented
languages, such as C++. The destructor method will be called as soon as all references to a
particular object are removed or when the object is explicitly destroyed or in any order in
shutdown sequence.
The visibility of a property or method must be defined by prefixing the declaration with the
keywords public, protected or private.
Class members declared public can be accessed everywhere.
Members declared protected can be accessed only within the class itself and by inherited and
parent classes.
Members declared as private may only be accessed by the class that defines the member.
16. What are the differences between Get and post methods.
Both include and require used to include a file but when included file not found
Include send Warning where as Require send Fatal Error
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.
19. List out the predefined classes in PHP?
Directory
stdClass
__PHP_Incomplete_Class
exception
php_user_filter
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'.
21. How can we encrypt the username and password using php?
Split function splits string into array by regular expression. Explode splits a string into array by
string.
For Example:explode(" and", "India and Pakistan and Srilanka");
split(" :", "India : Pakistan : Srilanka");
Both of these functions will return an array that contains India, Pakistan, and Srilanka.
Constants in PHP are defined using define() directive, like define("MYCONSTANT", 100);
25. What does a special set of tags <?= and ?> do in PHP?
parent::constructor($value)
__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves
them.
29. What is the difference between the functions unlink and unset?
30. How many ways can we get the value of current session id?
we will need to compile PHP with the GD library of image functions for this to work. GD and PHP
may also require other libraries, depending on which image formats you want to work with.
33. How can we get second of the current time using date function?
<?php
$second = date(“s”);
?>
34. What are the Formatting and Printing Strings available in PHP?
35. How can we find the number of rows in a result set using PHP?
The full form of PHP is Hypertext Preprocessor. It is used by embedding HTML for
creating dynamic content, communicating with a database server, handling session etc.
Q #2) Why do we use PHP?
Answer:
There are several benefits of using PHP. First of all, it is totally free to use. So anyone
can use PHP without any cost and host the site at a minimal cost.
It supports multiple databases. The most commonly used database is MySQL which is
also free to use. Many PHP frameworks are used now for web development, such as
CodeIgniter, CakePHP, Laravel etc.
These frameworks make the web development task much easier than before.
Which means PHP does not require to declare data types of the variable when you
declare any variable like the other standard programming languages C# or Java. When
you store any string value in a variable then the data type is the string and if you store a
numeric value in that same variable then the data type is an Integer.
Sample code:
1 $var = "Hello"; //String
2 $var = 10; //Integer
Q #4) What is meant by variable variables in PHP?
Answer:
When the value of a variable is used as the name of the other variables then it is called
variable variables. $$ is used to declare variable variables in PHP.
Sample code:
1 $str = "PHP";
2 $$str = " Programming"; //declaring variable variables
3 echo "$str ${$str}"; //It will print "PHP programming"
4 echo "$PHP"; //It will print "Programming"
Q #5) What are the differences between echo and print?
Answer:
Both echo and print method print the output in the browser but there is a difference
between these two methods.
echo does not return any value after printing the output and it works faster than the print
method. print method is slower than the echo because it returns boolean value after
printing the output.
Sample code:
1 echo "PHP Developer";
2 $n = print "Java Developer";
Q #6) How can you execute PHP script from the command line?
Answer:
You have to use PHP command in the command line to execute a PHP script. If the
PHP file name is test.php then the following command is used to run the script from the
command line.
php test.php
1 //Numeric Array
2 $computer = array("Dell", "Lenavo", "HP");
3 //Associative Array
4 $color = array("Sithi"=>"Red", "Amit"=>"Blue", "Mahek"=>"Green");
5 //Multidimensional Array
Sample code:
1 echo gettype(true).''; //boolean
2 echo gettype(10).''; //integer
3 echo gettype('Web Programming').''; //string
4 echo gettype(null).''; //NULL
Q #11) How can you increase the maximum execution time of a script in PHP?
Answer:
You need to change the value of the max_execution_time directive in the php.ini file
for increasing the maximum execution time.
For Example, if you want to set the max execution time for 120 seconds, then set the
value as follows,
1 max_execution_time = 120
Q #12) What is meant by ‘passing the variable by value and reference' in PHP?
Answer:
When the variable is passed as value then it is called pass variable by value.
Here, the main variable remains unchanged even when the passed variable changes.
Sample code:
1 function test($n) {
2 $n=$n+10;
3}
4
5 $m=5;
6 test($m);
7 echo $m;
When the variable is passed as a reference then it is called pass variable by
reference. Here, both the main variable and the passed variable share the same
memory location and & is used for reference.
So, if one variable changes then the other will also change.
Sample code:
1 function test(&$n) {
2 $n=$n+10;
3}
4 $m=5;
5 test($m);
6 echo $m;
Q #13) Explain type casting and type juggling.
Answer:
The way by which PHP can assign a particular data type for any variable is called
typecasting. The required type of variable is mentioned in the parenthesis before the
variable.
Sample code:
1 $str = "10"; // $str is now string
2 $bool = (boolean) $str; // $bool is now boolean
PHP does not support data type for variable declaration. The type of the variable is
changed automatically based on the assigned value and it is called type juggling.
Sample code:
1 $val = 5; // $val is now number
2 $val = "500" //$val is now string
Q #14) How can you make a connection with MySQL server using PHP?
Answer:
You have to provide MySQL hostname, username and password to make a connection
with the MySQL server in mysqli_connect() method or declaring database object of the
mysqli class.
Sample code:
1 $mysqli = mysqli_connect("localhost","username","password");
2 $mysqli = new mysqli("localhost","username","password");
Q #15) How can you retrieve data from the MySQL database using PHP?
Answer:
Many functions are available in PHP to retrieve the data from the MySQL database.
1 file_uploads = On
#2) Create an HTML form using enctype attribute and file element for uploading the file.
<form action="upload.php" method="post" enctype="multipart/form-data">
</form>
Sample code:
10 and “10” are equal by values but are not equal by data type. One is a string and one
is a number. So, if condition will be false and print “n is not equal to 10”.
1 $n = 10;
2 if ($n === "10")
3 echo "n is equal to 10";
4 else
5 echo "n is not equal to 10"; //This will print
Q #34) Which operator is used to combine string values in PHP?
Answer:
Two or more string values can be combined by using ‘.’ operator.
Sample code:
1 $val1 = "Software ";
2 $val2 = "Testing";
3 echo $val1.$val2; // The output is “Software Testing”
Q #35) What is PEAR?
Answer:
The full form of PEAR is “PHP Extension and Application Repository”.
Anyone can download reusable PHP components by using this framework at a free of
cost. It contains different types of packages from different developers.
Website: PEAR
Q #36) What type of errors can be occurred in PHP?
Answer:
Different type of errors can occur in PHP.
Sample code:
Here, two interfaces, Isbn and Type are declared and implemented in a class, book
details to add the feature of multiple inheritances in PHP.
1 interface Isbn {
2 public function setISBN($isbn);
3}
4 interface Type{
5 public function setType($type);
6}
7 class bookDetails implements Isbn, Type {
8 private $isbn;
9 private $type;
10 public function setISBN($isbn)
11 {
12 $this -> isbn = $isbn;
13 }
14 public function setType($type)
15 {
16 $this -> type = $type;
17 }
18 }
Q #38) What are the differences between session and cookie?
Answer:
The session is a global variable which is used in the server to store the session data.
When a new session creates the cookie with the session id is stored on the visitor's
computer. The session variable can store more data than the cookie variable.
Session data are stored in a $_SESSION array and Cookie data are stored in a
$_COOKIE array. Session values are removed automatically when the visitor closes the
browser and cookie values are not removed automatically.
Sample code:
$DBconnection=mysqli_connect("localhost","username","password","dbname")
1
;
2 $productName = mysqli_real_escape_string($con, $_POST['proname']);
3 $ProductType = mysqli_real_escape_string($con, $_POST['protype']);
Q #40) Which functions are used to remove whitespaces from the string?
Answer:
There are three functions in PHP to remove the whitespaces from the string.
trim() – It removes whitespaces from the left and right side of the string.
ltrim() – It removes whitespaces from the from the left side of the string.
rtrim() – It removes whitespaces from the from the right side of the string.
Sample code:
1 $str = " Tutorials for your help";
2 $val1 = trim($str);
3 $val2 = ltrim($str);
4 $val3 = rtrim($str);
Q #41) What is a persistence cookie?
Answer:
A cookie file that is stored permanently in the browser is called a persistence cookie. It is
not secure and is mainly used for tracking a visitor for long times.
When it runs, it removes all sessions data which are not accessed for a long time. It runs
on /tmp directory which is the default session directory.
The disadvantages of this methods are, it doesn't allow persistence between the
sessions and, the user can easily copy and paste the URL and send to another user.
It is a lightweight PHP extension that uses consistence interface for accessing the
database. Using PDO, a developer can easily switch from one database server to the
other. But it does not support all the advanced features of the new MySQL server.