PHP Questions For Interview With Answers 2020
This article will give you a list of PHP Questions for Interview with Answers that is useful to those students and professionals who are preparing for exam certification and Job Interview.
Most of the PHP interview questions with answers have been asked by many companies in information technology industries.
You click here if you are looking for a PHP Projects with Source Code Free download.
List of Top PHP Questions For Interview With Answers 2020
PHP Questions For Interview with Answer 2020
- PHP Questions For Interview: What is PHP?
Answer: PHP stands for Hypertext Preprocessor. It is an open source server-side scripting language which is widely used for web development. It supports many databases like MySQL, Oracle, Sybase, Solid, PostgreSQL, generic ODBC etc.
- PHP Questions For Interview: What is PEAR in PHP?
Answer: PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP Extension and Application Repository. It contains all types of PHP code snippets and libraries. It also provides a command line interface to install “packages” automatically.
- PHP Questions For Interview: Who is known as the father of PHP?
Answer: Rasmus Lerdorf
- PHP Questions For Interview: What was the old name of PHP?
Answer: The old name of PHP was Personal Home Page.
- PHP Questions For Interview: Explain the difference b/w static and dynamic websites?
Answer: In static websites, content can’t be changed after running the script. You can’t change anything on the site. It is predefined.
In dynamic websites, content of script can be changed at the run time. Its content is regenerated every time a user visit or reload. Google, yahoo and every search engine is the example of dynamic website. - PHP Questions For Interview: What is the name of scripting engine in PHP?
Answer: The scripting engine that powers PHP is called Zend Engine 2.
- PHP Questions For Interview: Explain the difference between PHP4 and PHP5.
Answer: PHP4 doesn’t support oops concept and uses Zend Engine 1.
PHP5 supports oops concept and uses Zend Engine 2. - PHP Questions For Interview: What are the popular frameworks in PHP?
Answer:
o CakePHP
o CodeIgniter
o Yii 2
o Symfony
o Zend Framework etc. - PHP Questions For Interview: Which programming language does PHP resemble to?
Answer: PHP has borrowed its syntax from Perl and C.
List some of the features of PHP7.
o Scalar type declarations
o Return type declarations
o Null coalescing operator (??)
o Spaceship operator
o Constant arrays using define()
o Anonymous classes
o Closure::call method
o Group use declaration
o Generator return expressions
o Generator delegation
o Space ship operator - PHP Questions For Interview: What is “echo” in PHP?
Answer: PHP echo output one or more string. It is a language construct not a function. So the use of parentheses is not required. But if you want to pass more than one parameter to echo, the use of parentheses is required.
Syntax:
void echo ( string $arg1 [, string $… ] ) - PHP Questions For Interview: What is “print” in PHP?
Answer: PHP print output a string. It is a language construct not a function. So the use of parentheses is not required with the argument list. Unlike echo, it always returns 1.
Syntax:
int print ( string $arg) - PHP Questions For Interview: What is the difference between “echo” and “print” in PHP?
Answer: Echo can output one or more string but print can only output one string and always returns
Echo is faster than print because it does not return any value. - PHP Questions For Interview: How a variable is declared in PHP?
Answer: A PHP variable is the name of the memory location that holds data. It is temporary storage.
Syntax:
$variableName=value; - PHP Questions For Interview: What is the difference between $message and $$message?
Answer: $message stores variable data while $$message is used to store variable of variables.
$message stores fixed data whereas the data stored in $$message may be changed dynamically. - PHP Questions For Interview: What are the ways to define a constant in PHP?
Answer: PHP constants are name or identifier that can’t be changed during execution of the script.
PHP constants are defined in two ways:
o Using define() function
o Using const() function - PHP Questions For Interview: What are magic constants in PHP?
Answer: PHP magic constants are predefined constants, which change based on their use. They start with a double underscore () and end with a double underscore ().
- PHP Questions For Interview: How many data types are there in PHP?
Answer: PHP data types are used to hold different types of data or values. There are 8 primitive data types which are further categorized in 3 types:
o Scalar types
o Compound types
o Special types
PHP Data Types: Scalar Types
There are 4 scalar data types in PHP.
boolean
integer
float
string
PHP Data Types: Compound Types
There are 2 compound data types in PHP.
array
object
PHP Data Types: Special Types
There are 2 special data types in PHP.
resource
NULL - PHP Questions For Interview: What is Comments in Php
Answer: PHP comments can be used to describe any line of code so that other developer can understand the code easily. It can also be used to hide any code.
PHP supports single line and multi line comments. These comments are similar to C/C++ and Perl style (Unix shell style) comments. - PHP Questions For Interview: What are the different loops in PHP?
Answer: For, while, do-while and for each.
- PHP Questions For Interview: What is the use of count() function in PHP?
Answer: The PHP count() function is used to count total elements in the array, or something an object.
- PHP Questions For Interview: What is the use of header() function in PHP?
Answer: The header() function is used to send a raw HTTP header to a client. It must be called before sending the actual output. For example, you can’t print any HTML element before using this function.
- PHP Questions For Interview: What does isset() function?
The isset() function checks if the variable is defined and not null.
- Explain PHP parameterized functions?
Answer: PHP parameterized functions are functions with parameters. You can pass any number of parameters inside a function. These given parameters act as variables inside your function. They are specified inside the parentheses, after the function name. Output depends upon dynamic values passed as parameters into the function.
- PHP Questions For Interview: Explain PHP variable length argument function?
Answer: PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments in function. To do this, you need to use 3 ellipses (dots) before the argument name. The 3 dot concept is implemented for variable length argument since PHP 5.6.
- PHP Questions For Interview: What is the array in PHP?
Answer: An array is used to store multiple values in a single value. In PHP, it orders maps of pairs of keys and values. It saves the collection of the data type.
How many types of array are there in PHP?
There are three types of array in PHP:
Indexed array: an array with a numeric key.
Associative array: an array where each key has its specific value.
Multidimensional array: an array containing one or more arrays within itself. - PHP Questions For Interview: Explain some of the PHP array functions?
Answer: There are many array functions in PHP:
o array()
o array_change_key_case()
o array_chunk()
o count()
o sort()
o array_reverse()
o array_search()
o array_intersect() - PHP Questions For Interview: What is the difference between indexed and associative array?
Answer: The indexed array holds elements in an indexed form which is represented by number starting from 0 and incremented by 1. For example:
$season=array(“summer”,”winter”,”spring”,”autumn”);
The associative array holds elements with name. For example:
$salary=array(“Sonoo”=>”350000″,”John”=>”450000″,”Kartik”=>”200000”); - PHP Questions For Interview: How to get the length of string?
Answer: The strlen() function is used to get the length of the string.
- PHP Questions For Interview: Explain some of the PHP string functions?
Answer: There are many array functions in PHP:
o strtolower()
o strtoupper()
o ucfirst()
o lcfirst()
o ucwords()
o strrev()
o strlen() - PHP Questions For Interview: What are the methods to submit form in PHP?
Answer: There are two methods GET and POST.
PHP Form Handling
We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and $_POST.
The form request may be get or post. To retrieve data from get request, we need to use $_GET, for post request $_POST.
PHP Get Form
Get request is the default form request. The data passed through get request is visible on the URL browser so it is not secured. You can send limited amount of data through get request.
PHP Post Form
Post request is widely used to submit form that have large amount of data such as file upload, image upload, login form, registration form etc.
The data passed through post request is not visible on the URL browser so it is secured. You can send large amount of data through post request. - PHP Questions For Interview: How can you submit a form without a submit button?
Answer: You can use JavaScript submit() function to submit the form without explicitly clicking any submit button.
- PHP Questions For Interview: What are the ways to include file in PHP?
Answer: PHP allows you to include file so that page content can be reused again. There are two ways to add the file in PHP.
1. include
2. require
PHP include is used to include file on the basis of given path. You may use relative or absolute path of the file.
PHP require is similar to include. Let’s see a simple PHP require example. - PHP Questions For Interview: Differentiate between require and include?
Answer: Require and include both are used to include a file, but if data is not found include sends warning whereas require sends Fatal error
- PHP Questions For Interview: Explain setcookie() function in PHP?
Answer: PHP setcookie() function is used to set cookie with HTTP response. Once the cookie is set, you can access it by $_COOKIE superglobal variable.
Syntax:
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
[, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] ) - PHP Questions For Interview: How can you retrieve a cookie value?
Answer: echo $_COOKIE [“user”];
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends request to the server, cookie is embedded with request. Such way, cookie can be received at the server side.
PHP setcookie() function
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access it by $_COOKIE superglobal variable. - PHP Questions For Interview: What is a session?
Answer: PHP Engine creates a logical object to preserve data across subsequent HTTP requests, which is known as session.
Sessions generally store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same user.
Simply, it maintains data of an user (browser).
PHP session_start() function
PHP session_start() function is used to start the session. It starts a new or resumes existing session. It returns existing session if session is created already. If session is not available, it creates and returns new session.
PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session variable values.
PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session variable values. - PHP Questions For Interview: What is the method to register a variable into a session?
Answer:
<?php
Session_register($ur_session_var);
?> - PHP Questions For Interview: What is PHP session_start() function?
Answer: PHP session_start() function is used to start the session. It starts new or resumes the current session. It returns the current session if the session is created already. If the session is not available, it creates and returns new sessions.
- PHP Questions For Interview: What is the difference between session and cookie?
Answer: The main difference between session and cookie is that cookies are stored on user’s computer in the text file format while sessions are stored on the server side.
Cookies can’t hold multiple variables, on the other hand, Session can hold multiple variables.
You can manually set an expiry for a cookie, while session only remains active as long as browser is open. - PHP Questions For Interview: Write syntax to open a file in PHP?
Answer: PHP fopen() function is used to open file or URL and returns resource. It accepts two arguments: $filename and $mode.
Syntax:
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] ) - PHP Questions For Interview: How to read a file in PHP?
Answer: PHP provides various functions to read data from the file. Different functions allow you to read all file data, read data line by line, and read data character by character.
PHP file read functions are given below:
o fread()
o fgets()
o fgetc() - PHP Questions For Interview: How to delete file in PHP?
Answer: The unlink() function is used to delete a file in PHP.
bool unlink (string $filename) - What is the method to execute a PHP script from the command line?
Answer: You should just run the PHP command line interface (CLI) and specify the file name of the script to be executed as follows.
- PHP Questions For Interview: How to upload file in PHP?
Answer: The move_uploaded_file() function is used to upload file in PHP.
bool move_uploaded_file ( string $filename , string $destination ) - PHP Questions For Interview: How to download file in PHP?
Answer: The readfile() function is used to download the file in PHP.
int readfile ( string $filename ) - PHP Questions For Interview: How can you send email in PHP?
Answer: The mail() function is used to send email in PHP.
bool mail($to,$subject,$message,$header); - PHP Questions For Interview: How do you connect MySQL database with PHP?
Answer: There are two methods to connect MySQL database with PHP. Procedural and object-oriented style.
How to create connection in PHP?
The mysqli_connect() function is used to create a connection in PHP.
resource mysqli_connect (server, username, password) - PHP Questions For Interview: How to create database connection and query in PHP?
Answer: Since PHP 4.3, mysql_reate_db() is deprecated. Now you can use the following 2 alternatives.
o mysqli_query()
o PDO::_query() - PHP Questions For Interview: How can we increase execution time of a PHP script?
Answer: By default, the maximum execution time for PHP scripts is set to 30 seconds. If a script takes more than 30 seconds, PHP stops the script and returns an error.
You can change the script run time by changing the max_execution_time directive in the php.ini file.
When a script is called, set_time_limit function restarts the timeout counter from zero. It means, if default timer is set to 30 sec, and 20 sec is specified in function set_time_limit(), then script will run for 45 seconds. If 0sec is specified in this function, script takes unlimited time. - PHP Questions For Interview: What are the different types of errors in PHP?
Answer: There are 3 types of error in PHP.
Notices:These are non-critical errors. These errors are not displayed to the users.
Warnings:These are more serious errors, but they do not result in script termination. By default, these errors are displayed to the user.
Fatal Errors:These are the most critical errors. These errors may cause due to immediate termination of script. - PHP Questions For Interview: How to stop the execution of PHP script?
Answer: The exit() function is used to stop the execution of PHP script.
- PHP Questions For Interview: What are the encryption functions in PHP?
Answer: CRYPT() and MD5()
- PHP Questions For Interview: What is htaccess in PHP?
Answer: The .htaccess is a configuration file on Apache server. You can change configuration settings using directives in Apache configuration files like .htaccess and httpd.conf.
Explain PHP explode() function.
The PHP explode() function breaks a string into an array.
____________________________ Explain PHP split() function.
The PHP split() function splits string into an array by regular expression. - PHP Questions For Interview: How can we get IP address of a client in PHP?
Answer: $_SERVER[“REMOTE_ADDR”];
- PHP Questions For Interview: What is the meaning of a Persistent Cookie?
Answer: A persistent cookie is permanently stored in a cookie file on the browser’s computer. By default, cookies are temporary and are erased if we close the browser.
- PHP Questions For Interview: What is the use of the function ‘imagetypes()’?
Answer: imagetypes() gives the image format and types supported by the current version of GD-PHP.
- PHP Questions For Interview: What are include() and require() functions?
Answer: The Include() function is used to put data of one PHP file into another PHP file. If errors occur, then the include() function produces a warning but does not stop the execution of the script, and it will continue to execute.
The Require() function is also used to put data of one PHP file to another PHP file. If there are any errors, then the require() function produces a warning and a fatal error and stops the script. - What is Cookies? How to create cookies in PHP?
A cookie is used to identify a user. A cookie is a little record that the server installs on the client’s Computer. Each time a similar PC asks for a page with a program, it will send the cookie as well. With PHP, you can both make and recover cookie value.
Some important points regarding Cookies:
Cookies maintain the session id generated at the back end after verifying the user’s identity in encrypted form, and it must reside in the browser of the machine
You can store only string values not object because you can’t access any object across the website or web apps
Scope: – Multiple pages.
By default, cookies are temporary and transitory cookie saves in the browser only.
By default, cookies are URL particular means Gmail isn’t supported in Yahoo and the vice versa.
Per site 20 cookies can be created in one website or web app
The Initial size of the cookie is 50 bytes.
The Maximum size of the cookie is 4096 bytes. - What is the Importance of Parser in PHP?
PHP parser parses the PHP developed website from the opening to the closing tag. Tags indicate that from where PHP code is being started and ended. In other words, opening and closing tags decide the scope of PHP scripting syntax of closing tag in PHP
syntax of closing tag in PHP
How can we create a database using PHP and MySQL?
The necessary steps to create a MySQL database using PHP are:
o Establish a connection to MySQL server from your PHP script.
o If the connection is successful, write a SQL query to create a database and store it in a string variable.
o Execute the query. - What’s the difference between the include() and require() functions?
They both include a specific file but on require the process exits with a fatal error if the file can’t be included, while include statement may still pass and jump to the next step in the execution.
- How can we get the IP address of the client?
This question might show you how playful and creative the candidate is because there are many options. $_SERVER[“REMOTE_ADDR”]; is the easiest solution, but the candidate can write x line scripts for this question.
- What’s the difference between unset() and unlink()
unset() sets a variable to “undefined” while unlink() deletes a file we pass to it from the file system.
- What are the main error types in PHP and how do they differ?
In PHP there are three main type of errors:
• Notices – Simple, non-critical errors that are occurred during the script execution. An example of a Notice would be accessing an undefined variable.
• Warnings – more important errors than Notices, however the scripts continue the execution. An example would be include() a file that does not exist.
• Fatal – this type of error causes a termination of the script execution when it occurs. An example of a Fatal error would be accessing a property of a non-existent object or require() a non-existent file.
Understanding the error types is very important as they help developers understand what is going on during the development, and what to look out for during debugging. - What is the difference between GET and POST?
GET displays the submitted data as part of the URL, during POST this information is not shown as it’s encoded in the request.
• GET can handle a maximum of 2048 characters, POST has no such restrictions.
• GET allows only ASCII data, POST has no restrictions, binary data are also allowed.
• Normally GET is used to retrieve data while POST to insert and update.
Understanding the fundamentals of the HTTP protocol is very important to have for a PHP developer, and the differences between GET and POST are an essential part of it. - How can you enable error reporting in PHP?
Check if “display_errors” is equal “on” in the php.ini or declare “ini_set(‘display_errors’, 1)” in your script.
Then, include “error_reporting(E_ALL)” in your code to display all types of error messages during the script execution.
Enabling error messages is very important especially during the debugging process as one can instantly get the exact line that is producing the error and can see also if the script in general is behaving correctly. - What are Traits?
Traits are a mechanism that allows you to create reusable code in languages like PHP where multiple inheritance is not supported. A Trait cannot be instantiated on its own.
It’s important that a developer knows the powerful features of the language (s)he is working on, and Trait is one of such features. - Can the value of a constant change during the script’s execution?
No, the value of a constant cannot be changed once it’s declared during the PHP execution.
- Can you extend a Final defined class?
No, you cannot extend a Final defined class. A Final class or method declaration prevents child class or method overriding.
- What are the __construct() and __destruct() methods in a PHP class?
All objects in PHP have Constructor and Destructor methods built-in. The Constructor method is called immediately after a new instance of the class is being created, and it’s used to initialize class properties. The Destructor method takes no parameters.
Understanding these two in PHP means that the candidate knows the very basics of OOP in PHP. - How we can get the number of elements in an array?
The count() function is used to return the number of elements in an array.
Understanding of arrays and array related helper functions is important for any PHP developer. - What are the 3 scope levels available in PHP and how would you define them?
Private – Visible only in its own class
Public – Visible to any other code accessing the class
Protected – Visible only to classes parent(s) and classes that extend the current class
This is important for any PHP developer to know because it shows an understanding that building applications is more than just being able to write code. One must also have an understanding about privileges and accessibility of that code. There are times protected variables or methods are extremely important, and an understanding of scope is needed to protect the integrity of the data in your application along with provide a clear path through the code. - What are getters and setters and why are they important?
Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer. Within a getter or setter one is able to consistently handle data that will eventually be passed into a variable or additional functions. An example of this would be a user’s name. If a setter is not being used and the developer is just declaring the $userName variable by hand, you could end up with results as such: “kevin”, “KEVIN”, “KeViN”, “”, etc. With a setter, the developer can not only adjust the value, for example, ucfirst($userName), but can also handle situations where the data is not valid such as the example where “” is passed. The same applies to a getter – when the data is being returned, it can be modifyed the results to include strtoupper($userName) for proper formatting further up the chain.
This is important for any developer who is looking to enter a team-based / application development job to know. Getters and setters are often used when dealing with objects, especially ones that will end up in a database or other storage medium. Because PHP is commonly used to build web applications, developers will run across getters and setters in more advanced environments. They are extremely powerful yet not talked about very much. It is impressive if a developer shows that he/she knows what they are and how to use them early on. - What does MVC stand for and what does each component do?
MVC stands for Model View Controller.
The controller handles data passed to it by the view and also passes data to the view. It’s responsible for interpretation of the data sent by the view and dispersing that data to the appropriate models awaiting results to pass back to the view. Very little, if any business logic should be occurring in the controller.
The model’s job is to handle specific tasks related to a specific area of the application or functionality. Models will communicate directly with your database or other storage system and will handle business logic related to the results.
The view is passed data by the controller and is displayed to the user. - How does one prevent the following Warning ‘Warning: Cannot modify header information – headers already sent’ and why does it occur in the first place?
The candidate should not output anything to the browser before using code that modifies the HTTP headers. Once the developer calls echo or any other code that clears the buffer, the developer can no longer set cookies or headers. That is also true for error messages, so if an error happens before using the header command and the INI directive display_errors is set, then that will also cause that error to show.
- What are PSRs? Choose 1 and briefly describe it.
PSRs are PHP Standards Recommendations that aim at standardising common aspects of PHP Development.
- What PSR Standards do you follow? Why would you follow a PSR standard?
One should folow a PSR because coding standards often vary between developers and companies. This can cause issues when reviewing or fixing another developer’s code and finding a code structure that is different from yours. A PSR standard can help streamline the expectations of how the code should look, thus cutting down confusion and in some cases, syntax errors.
- What do the initials of PHP stand for?
PHP means PHP: Hypertext Preprocessor.
- Which programming language does PHP resemble?
PHP syntax resembles Perl and C
- What does PEAR stand for?
PEAR means “PHP Extension and Application Repository”. It extends PHP and provides a higher level of programming for web developers.
- What is the actually used PHP version?
Version 7.1 or 7.2 is the recommended version of PHP.
- How can we display the output directly to the browser?
To be able to display the output directly to the browser, we have to use the special tags .
- Is multiple inheritance supported in PHP?
PHP supports only single inheritance; it means that a class can be extended from only one single class using the keyword ‘extended’.
- What is the meaning of a final class and a final method?
‘final’ is introduced in PHP5. Final class means that this class cannot be extended and a final method cannot be overridden.
- How is the comparison of objects done in PHP?
We use the operator ‘==’ to test is two objects are instanced from the same class and have same attributes and equal values. We can test if two objects are referring to the same instance of the same class by the use of the identity operator ‘===’.
- How can PHP and HTML interact?
It is possible to generate HTML through PHP scripts, and it is possible to pass pieces of information from HTML to PHP.
- What type of operation is needed when passing values through a form or an URL?
If we would like to pass values through a form or an URL, then we need to encode and to decode them using htmlspecialchars() and urlencode().
- How can PHP and Javascript interact?
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.
- What is needed to be able to use image function?
GD library is needed to execute image functions.
- What is the use of the function ‘imagetypes()’?
imagetypes() gives the image format and types supported by the current version of GD-PHP.
- What are the functions to be used to get the image’s properties (size, width, and height)?
The functions are getimagesize() for size, imagesx() for width and imagesy() for height.
- How failures in execution are handled with include() and require() functions?
If the function require() cannot access the file then it ends with a fatal error. However, the include() function gives a warning, and the PHP script continues to execute.
- What is the main difference between require() and require_once()?
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.
(same for include_once() and include()) - How can we display information of a variable and readable by a human with PHP?
To be able to display a human-readable result we use print_r().
- How is it possible to set an infinite execution time for PHP script?
The set_time_limit(0) added at the beginning of a script sets to infinite the time of execution to not have the PHP error ‘maximum execution time exceeded.’ It is also possible to specify this in the php.ini file.
- What does the PHP error ‘Parse error in PHP – unexpected T_variable at line x’ means?
This is a PHP syntax error expressing that a mistake at the line x stops parsing and executing the program.
- What should we do to be able to export data into an Excel file?
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.
What is the function file_get_contents() useful for?
file_get_contents() lets reading a file and storing it in a string variable. - How can we connect to a MySQL database from a PHP script?
To be able to connect to a MySQL database, we must use mysqli_connect() function
- What is the function mysql_pconnect() useful for?
mysql_pconnect() ensure a persistent connection to the database, it means that the connection does not close when the PHP script ends.
- How be the result set of Mysql handled in PHP?
The result set can be handled using mysqli_fetch_array, mysqli_fetch_assoc, mysqli_fetch_object or mysqli_fetch_row.
- How is it possible to know the number of rows returned in the result set?
The function mysqli_num_rows() returns the number of rows in a result set.
- Which function gives us the number of affected entries by a query?
mysqli_affected_rows() return the number of entries affected by an SQL query.
- What is the difference between mysqli_fetch_object() and mysqli_fetch_array()?
The mysqli_fetch_object() function collects the first single matching record where mysqli_fetch_array() collects all matching records from the table in an array.
- 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’ - 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”]; - How can we check the value of a given variable is a number?
It is possible to use the dedicated function, is_numeric() to check whether it is a number or not.
- How can we check the value of a given variable is alphanumeric?
It is possible to use the dedicated function, ctype_alnum to check whether it is an alphanumeric value or not.
- How do I check if a given variable is empty?
If we want to check whether a variable has a value or not, it is possible to use the empty() function.
- What does the unlink() function mean?
The unlink() function is dedicated for file system handling. It simply deletes the file given as entry.
- What does the unset() function mean?
The unset() function is dedicated for variable management. It will make a variable undefined.
- How do I escape data before storing it in the database?
The addslashes function enables us to escape data before storage into the database.
- How is it possible to remove escape characters from a string?
The stripslashes function enables us to remove the escape characters before apostrophes in a string.
- How can we automatically escape incoming data?
We have to enable the Magic quotes entry in the configuration file of PHP.
- What does the function get_magic_quotes_gpc() means?
The function get_magic_quotes_gpc() tells us whether the magic quotes is switched on or no.
Is it possible to remove the HTML tags from data?
The strip_tags() function enables us to clean a string from the HTML tags. - what is the static variable in function useful for?
A static variable is defined within a function only the first time, and its value can be modified during function calls
- How can we define a variable accessible in functions of a PHP script?
This feature is possible using the global keyword.
- How is it possible to return a value from a function?
A function returns a value using the instruction ‘return $value;’.
- What is the most convenient hashing method to be used to hash passwords?
It is preferable to use crypt() which natively supports several hashing algorithms or the function hash() which supports more variants than crypt() rather than using the common hashing algorithms such as md5, sha1 or sha256 because they are conceived to be fast. Hence, hashing passwords with these algorithms can create vulnerability.
- Which cryptographic extension provide generation and verification of digital signatures?
The PHP-OpenSSL extension provides several cryptographic operations including generation and verification of digital signatures.
- How is a constant defined in a PHP script?
The define() directive lets us defining a constant as follows:
define (“ACONSTANT”, 123); - How can you pass a variable by reference?
To be able to pass a variable by reference, we use an ampersand in front of it, as follows $var1 = &$var2
Will a comparison of an integer 12 and a string “13” work in PHP?
“13” and 12 can be compared in PHP since it casts everything to the integer type. - How is it possible to cast types in PHP?
The name of the output type has to be specified in parentheses before the variable which is to be cast as follows:
(int), (integer) – cast to integer
(bool), (boolean) – cast to boolean
(float), (double), (real) – cast to float
(string) – cast to string
(array) – cast to array
(object) – cast to object - When is a conditional statement ended with endif?
When the original if was followed by: and then the code block without braces.
- How is the ternary conditional operator used in PHP?
It is composed of three expressions: a condition, and two operands describing what instruction should be performed when the specified condition is true or false as follows:
Expression_1?Expression_2 : Expression_3; - What is the function func_num_args() used for?
The function func_num_args() is used to give the number of parameters passed into a function.
If the variable $var1 is set to 10 and the $var2 is set to the character var1, what’s the value of $$var2?
$$var2 contains the value 10. - What does accessing a class via :: means?
:: is used to access static methods that do not require object initialization.
In PHP, objects are they passed by value or by reference?
In PHP, objects passed by value.
Are Parent constructors called implicitly inside a class constructor?
No, a parent constructor have to be called explicitly as follows:
parent::constructor($value) - What’s the difference between __sleep and __wakeup?
__sleep returns the array of all the variables that need to be saved, while __wakeup retrieves them.
- How can you propagate a session id?
You can propagate a session id via cookies or URL parameters.
- What is the meaning of a Persistent Cookie?
A persistent cookie is permanently stored in a cookie file on the browser’s computer. By default, cookies are temporary and are erased if we close the browser.
- When do sessions end?
Sessions automatically end when the PHP script finishes executing but can be manually ended using the session_write_close().
- What is the difference between session_unregister() and session_unset()?
The session_unregister() function unregister a global variable from the current session and the session_unset() function frees all session variables.
- What does $GLOBALS mean?
$GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.
- What does $_SERVER mean?
$_SERVER is an array including information created by the web server such as paths, headers, and script locations.
- What does $_FILES means?
$_FILES is an associative array composed of items sent to the current script via the HTTP POST method.
- What is the difference between $_FILES[‘userfile’][‘name’] and $_FILES[‘userfile’][‘tmp_name’]?
$_FILES[‘userfile’][‘name’] represents the original name of the file on the client machine,
$_FILES[‘userfile’][‘tmp_name’] represents the temporary filename of the file stored on the server. - How can we get the error when there is a problem to upload a file?
$_FILES[‘userfile’][‘error’] contains the error code associated with the uploaded file.
- How can we change the maximum size of the files to be uploaded?
We can change the maximum size of files to be uploaded by changing upload_max_filesize in php.ini.
- What does $_ENV mean?
$_ENV is an associative array of variables sent to the current PHP script via the environment method.
- What does the scope of variables mean?
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.
- what the difference between the ‘BITWISE AND’ operator and the ‘LOGICAL AND’ operator?
$a and $b: TRUE if both $a and $b are TRUE.
$a & $b: Bits that are set in both $a and $b are set. - What are the two main string operators?
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.
- What does the array operator ‘===’ means?
$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
- What is the differences between $a != $b and $a !== $b?
!= means inequality (TRUE if $a is not equal to $b) and !== means non-identity (TRUE if $a is not identical to $b).
- How can we determine whether a PHP variable is an instantiated object of a certain class?
To be able to verify whether a PHP variable is an instantiated object of a certain class we use instanceof.
- What is the goto statement useful for?
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.
- what is the difference between Exception::getMessage and Exception:: getLine?
Exception::getMessage lets us getting the Exception message
Exception::getLine lets us getting the line in which the exception occurred. - What does the expression Exception::__toString means?
Exception::__toString gives the String representation of the exception.
- How is it possible to parse a configuration file?
The function parse_ini_file() enables us to load in the ini file specified in filename and returns the settings in it in an associative array.
- How can we determine whether a variable is set?
The boolean function isset determines if a variable is set and is not NULL.
- 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.
- what is the difference between for and foreach?
for is expressed as follows:
for (expr1; expr2; expr3)
statement
The first expression is executed once at the beginning. In each iteration, expr2 is evaluated. If it is TRUE, the loop continues, and the statements inside for are executed. If it evaluates to FALSE, the execution of the loop ends. expr3 is tested at the end of each iteration.
However, foreach provides an easy way to iterate over arrays, and it is only used with arrays and objects. - Is it possible to submit a form with a dedicated button?
It is possible to use the document.form.submit() function to submit the form. For example:
- What is the difference between ereg_replace() and eregi_replace()?
The function eregi_replace() is identical to the function ereg_replace() except that it ignores case distinction when matching alphabetic characters.
- Is it possible to protect special characters in a query string?
Yes, we use the urlencode() function to be able to protect special characters.
- What are the three classes of errors that can occur in PHP?
The three basic classes of errors are notices (non-critical), warnings (serious errors) and fatal errors (critical errors).
- What is the difference between characters \034 and \x34?
\034 is octal 34
\x34 is hex 34. - 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.
- Is it possible to extend the execution time of a PHP script?
The use of the set_time_limit(int seconds) enables us to extend the execution time of a PHP script. The default limit is 30 seconds.
- Is it possible to destroy a cookie?
Yes, it is possible by setting the cookie with a past expiration time.
- What is the default session time in PHP?
The default session time in php is until the closing of the browser
- Is it possible to use COM component in PHP?
Yes, it’s possible to integrate (Distributed) Component Object Model components ((D)COM) in PHP scripts which is provided as a framework.
- Why do we use PHP?
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. - Is PHP a strongly typed language?
No. PHP is a weakly typed or loosely typed language.
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. - What is meant by variable variables in PHP?
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:
view source
print?
- What are the differences between echo and print?
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. - How can you execute PHP script from the command line?
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 - How can you declare the array in PHP?
You can declare three types of arrays in PHP. They are numeric, associative and multidimensional arrays.
Sample code:
view source
print?
- What are the uses of explode() and implode() functions?
explode() function is used to split a string into an array and implode() function is used to make a string by combining the array elements.
Sample code:
view source
print?
- Which function can be used to exit from the script after displaying the error message?
You can use exit() or die() function to exit from the current script after displaying the error message.
- Which function is used in PHP to check the data type of any variable?
gettype() function is used to check the data type of any variable.
Sample code:
view source
print?
- Explain type casting and type juggling.
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.
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. - How can you make a connection with MySQL server using PHP?
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:
view source
print?
- What are the differences between mysqli_connect and mysqli_pconnect?
mysqli_pconnect() function is used for making a persistence connection with the database that does not terminate when the script ends.
mysqli_connect() function searches any existing persistence connection first and if no persistence connection exists, then it will create a new database connection and terminate the connection at the end of the script. - Which function is used in PHP to count the total number of rows returned by any query?
mysqli_num_rows() function is used to count the total number of rows returned by the query.
- Which function you can use in PHP to open a file for reading or writing or for both?
You can use fopen() function to read or write or for doing both in PHP.
- Which function is used in PHP to delete a file?
unlink() function is used in PHP to delete any file.
- How can you send HTTP header to the client in PHP?
header() function is used to send raw HTTP header to a client before any output is sent.
- Which functions are used to count the total number of array elements in PHP?
count() and sizeof() functions can be used to count the total number of array elements in PHP.
- What is the difference between substr() and strstr()?
substr() function returns a part of the string based on the starting point and length. Length parameter is optional for this function and if it is omitted then the remaining part of the string from the starting point will be returned.
strstr() function searches the first occurrence of a string inside another string. The third parameter of this function is optional and it is used to retrieve the part of the string that appears before the first occurrence of the searching string. - What is the use of $_REQUEST variable?
The $_REQUEST variable is used to read the data from the submitted HTML form.
- What is the difference between for and foreach loop in PHP?
for loop is mainly used for iterating a pre-defined number of times
foreach loop is used for reading array elements or MySQL result set where the number of iteration can be unknown. - Which operator is used to combine string values in PHP?
Two or more string values can be combined by using ‘.’ operator.
- Does PHP support multiple inheritances?
PHP does not support multiple inheritances. To implement the features of multiple inheritances, the interface is used in PHP.
- What is the use of mysqli_real_escape_string() function?
mysqli_real_escape_string() function is used to escape special characters from the string for using a SQL statement
Sample code:
view source
print?
- Which functions are used to remove whitespaces from the string?
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:
view source
print?
- How can a cross-site scripting attack be prevented by PHP?
Htmlentities() function of PHP can be used for preventing cross-site scripting attack.
- Which PHP global variable is used for uploading a file?
$_FILE[] array contains all the information of an uploaded file.
The use of various indexes of this array is mentioned below:
$_FILES[$fieldName][‘name’] – Keeps the original file name.
$_FILES[$fieldName][‘type’] – Keeps the file type of an uploaded file.
$_FILES[$fieldName][‘size’] – Stores the file size in bytes.
$_FILES[$fieldName][‘tmp_name’] – Keeps the temporary file name which is used to store the file in the server.
$_FILES[$fieldName][‘error’] – Contains error code related to the error that appears during the upload. - What is meant by public, private, protected, static and final scopes?
• Public– Variables, classes, and methods which are declared public can be accessed from anywhere.
• Private– Variables, classes and methods which are declared private can be accessed by the parent class only.
• Protected– Variables, classes, and methods which are declared protected can be accessed by the parent and child classes only.
• Static– The variable which is declared static can keep the value after losing the scope.
• Final– This scope prevents the child class to declare the same item again. - How can image properties be retrieved in PHP?
getimagesize() – It is used to get the image size.
exif_imagetype() – It is used to get the image type.
imagesx() – It is used to get the image width.
imagesy() – It is used to get the image height. - What is garbage collection?
It is an automated feature of PHP.
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.
PHP directives which are used for garbage collection include:
• session.gc_maxlifetime (default value, 1440)
• session.gc_probability (default value, 1)
• session.gc_divisor (default value, 100) - What is URL rewriting?
Appending the session ID in every local URL of the requested page for keeping the session information is called URL rewriting.
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. - What is PDO?
The full form of PDO is PHP Data Objects.
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. - What are the common uses of PHP?
Uses of PHP
It performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
It can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user.
You can add, delete, modify elements within your database with the help of PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website and also encrypt data. - Is PHP a case sensitive language?
PHP is partially case sensitive. The variable names are case-sensitive but function names are not. If you define the function name in lowercase and call them in uppercase, it will still work. User-defined functions are not case sensitive but the rest of the language is case-sensitive.
- What is the meaning of ‘escaping to PHP’?
The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The mechanism for doing so is known as ‘escaping to PHP’. Escaping a string means to reduce ambiguity in quotes used in that string.
- What are the characteristics of PHP variables?
Some of the important characteristics of PHP variables include:
• All variables in PHP are denoted with a leading dollar sign ($).
• The value of a variable is the value of its most recent assignment.
• Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
• Variables can, but do not need, to be declared before assignment.
• Variables in PHP do not have intrinsic types – a variable does not know in advance whether it will be used to store a number or a string of characters.
• Variables used before they are assigned have default values. - What are the different types of PHP variables?
There are 8 data types in PHP which are used to construct the variables:
Integers − are whole numbers, without a decimal point, like 4195.
Doubles − are floating-point numbers, like 3.14159 or 49.1.
Booleans − have only two possible values either true or false.
NULL − is a special type that only has one value: NULL.
Strings − are sequences of characters, like ‘PHP supports string operations.’
Arrays − are named and indexed collections of other values.
Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
Resources − are special variables that hold references to resources external to PHP. - What are the rules for naming a PHP variable?
The following rules are needed to be followed while naming a PHP variable:
• Variable names must begin with a letter or underscore character.
• A variable name can consist of numbers, letters, underscores but you cannot use characters like + , – , % , ( , ) . & , etc. - What are the rules to determine the “truth” of any value which is not already of the Boolean type?
The rules to determine the “truth” of any value which is not already of the Boolean type are:
• If the value is a number, it is false if exactly equal to zero and true otherwise.
• If the value is a string, it is false if the string is empty (has zero characters) or is the string “0”, and is true otherwise.
• Values of type NULL are always false.
• If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value.
• Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).
• Don’t use double as Booleans. - What is NULL?
NULL is a special data type which can have only one value. A variable of data type NULL is a variable that has no value assigned to it. It can be assigned as follows:
$var = NULL;
The special constant NULL is capitalized by convention but actually it is case insensitive. So,you can also write it as :
$var = null;
A variable that has been assigned the NULL value, consists of the following properties:
• It evaluates to FALSE in a Boolean context.
• It returns FALSE when tested with IsSet() function. - Name some of the constants in PHP and their purpose.?
LINE – It represents the current line number of the file.
FILE – It represents the full path and filename of the file. If used inside an include,the name of the included file is returned.
FUNCTION – It represents the function name.
CLASS – It returns the class name as it was declared.
METHOD – It represents the class method name. - How many ways we can retrieve the date in result set of mysql Using php?
As individual objects so single record or as a set or arrays.
- What are the different tables present in mysql?
Total 5 types of tables we can create
MyISAM
Heap
Merge
InnoDB
ISAM
BDB
MyISAM is the default storage engine as of MySQL 3.23. - What is meant by nl2br()?
Nl2br Inserts HTML line breaks before all newlines in a string string nl2br (string); For example: echo nl2br(“god bless you”)
will output “god bless you” to your browser. - What are the current versions of apache, php, and mysql?
PHP: php 5.3
MySQL: MySQL 5.5
Apache: Apache 2.2 - 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 a data present in a mysql table using mysql?
AES_ENCRYPT () and AES_DECRYPT ()
- How can we encrypt the username and password using php?
You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD(“Password”); We can encode data using base64_encode($string) and can decode using base64_decode($string);
- What is meant by urlencode and urldocode?
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. - How can we get the properties (size, type, width, height) of an 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 - 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)
interestingly if u just pass a simple var instead of a an array it will return 1. - What is the maximum length of a table name, database name, and fieldname in mysql?
Database name- 64
Table name -64 Fieldname-64 - How many values can the SET function of mysql takes?
Mysql set can take zero or more values but at the maximum it can take 64 values
- What is mean by LAMP?
LAMP means combination of Linux, Apache, MySQL and PHP.
- How do you make one way encryption for your passwords in PHP?
Using md5 function or sha1 function
- What is the use of Mbstring?
Mbstring is an extension used in PHP to handle non-ASCII strings. Mbstring provides multibyte specific string functions that help us to deal with multibyte encodings in PHP. Multibyte character encoding schemes are used to express more than 256 characters in the regular byte-wise coding system. Mbstring is designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-byte encodings for convenience PHP Character Encoding Requirements.
- What is Cross-site scripting?
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side script into web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-origin policy.
- What are different types of Print Functions available in PHP?
PHP is a server side scripting language for creating dynamic web pages. There are so many functions available for displaying output in PHP. Here, I will explain some basic functions for displaying output in PHP. The basic functions for displaying output in PHP are as follows:
• print() Function
• echo() Function
• printf() Function
• sprintf() Function
• Var_dump() Function
• print_r() Function
•
• What are the differences between GET and POST methods in form submitting, give the case where we can use get and we can use post methods?
•
• In PHP, one can specify two different submission methods for a form. The method is specified inside a FORM element, using the METHOD attribute. The difference between METHOD=”GET” (the default) and METHOD=”POST” is primarily defined in terms of form data encoding. According to the technical HTML specifications, GET means that form data is to be encoded (by a browser) into a URL while POST means that the form data is to appear within the message body of the HTTP request. - Why should I store logs in a database rather than a file?
A database provides more flexibility and reliability than does logging to a file. It is easy to run queries on databases and generate statistics than it is for flat files. Writing to a file has more overhead and will cause your code to block or fail in the event that a file is unavailable. Inconsistencies caused by slow replication in AFS may also pose a problem to errors logged to files. If you have access to MySQL, use a database for logs, and when the database is unreachable, have your script automatically send an e-mail to the site administrator.
- How to add 301 redirects in PHP?
• You can add 301 redirect in PHP by adding below code snippet in your file.
• header(“HTTP/1.1 301 Moved Permanently”);
• header(“Location: /option-a”);
• exit(); - How can you get web browser’s details using PHP?
get_browser() function is used to retrieve the client browser details in PHP. This is a library function is PHP which looks up the browscap.ini file of the user and returns the capabilities of its browser.
Syntax:
get_browser(user_agent,return_array)
Example Usage:
$browserInfo = get_browser(null, true);
print_r($browserInfo); - How to access standard error stream in PHP?
You can access standard error stream in PHP by using following code snippet:
$stderr = fwrite(“php://stderr”);
$stderr = fopen(“php://stderr”, “w”);
$stderr = STDERR; - What is Mcrypt used for?
MCrypt is a file encryption function and that is delivered as Perl extension. It is the replacement of the old crypt() package and crypt(1) command of Unix. It allows developers to encrypt files or data streams without making severe changes to their code.
MCrypt is was deprecated in PHP 7.1 and completely removed in PHP 7.2. - What is PECL?
PECL is an online directory or repository for all known PHP extensions. It also provides hosting facilities for downloading and development of PHP extensions.
You can read More about PECL from https://pecl.php.net/ - What is a composer in PHP?
It is an application-level package manager for PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
- What is cURL in PHP ?
cURL is a library in PHP that allows you to make HTTP requests from the server.
- How to check curl is enabled or not in PHP
use function_exists(‘curl_version’) function to check curl is enabled or not. This function returns true if curl is enabled other false
Example :
if(function_exists(‘curl_version’) ){
echo “Curl is enabled”;
}else{
echo “Curl is not enabled”;
} - What is php.ini & .htacess file?
oth are used to make the changes to your PHP setting. These are explained below:
php.ini: It is a special file in PHP where you make changes to your PHP settings. It works when you run PHP as CGI. It depends on you whether you want to use the default settings or changes the setting by editing a php.ini file or, making a new text file and save it as php.ini.
.htaccess: It is a special file that you can use to manage/change the behavior of your site. It works when PHP is installed as an Apache module. These changes include such as redirecting your domain’s page to https or www, directing all users to one page, etc. - How to block direct directory access in PHP?
You can use a .htaccess file to block the direct access of directory in PHP. It would be best if you add all the files in one directory, to which you want to deny access.
For Apache, you can use this code:
<< Order deny, allow Deny from all</<
But first, you have to create a .htaccess file, if it is not present. Create the .htaccess file in the root of your server and then apply the above rule. - What is difference between ksort() and usort() functions.
• ksort() function is used to sort an array according to its key values whereas asort() function is used to sort an array according to its values.
• They both used to sort an associative array in PHP.
•
• How can i execute PHP File using Command Line?
•
• It is easy and simple to execute PHP scripts from the windows command prompt. You just follow the below steps:
• 1. Open the command prompt. Click on Start button->Command Prompt.
• 2. In the Command Prompt, write the full path to the PHP executable(php.exe) which is followed by the full path of a script that you want to execute. You must add space in between each component. It means to navigate the command to your script location. - What are access specifiers?
An access specifier is a code element that is used to determine which part of the program is allowed to access a particular variable or other information. Different programming languages have different syntax to declare access specifiers. There are three types of access specifiers in PHP which are:
• Private: Members of a class are declared as private and they can be accessed only from that class.
• Protected: The class members declared as protected can be accessed from that class or from the inherited class.
• Public: The class members declared as public can be accessed from everywhere. - Difference between array_combine and array_merge?
array_combine is used to combine two or more arrays while array_merge is used to append one array at the end of another array.
array_combine is used to create a new array having keys of one array and values of another array that are combined with each other whereas array_merge is used to create a new array in such a way that values of the second array append at the end of the first array.
array_combine doesn’t override the values of the first array but in array_merge values of the first array overrides with the values of the second one. - What is a path Traversal ?
Path Traversal also is known as Directory Traversal is referring to an attack which is attacked by an attacker to read into the files of the web application. Also, he/she can reveal the content of the file outside the root directory of a web server or any application. Path traversal operates the web application file with the use of dot-dot-slash (../) sequences, as ../ is a cross-platform symbol to go up in the directory.
Path traversal basically implements by an attacker when he/she wants to gain secret passwords, access token or other information stored in the files. Path traversal attack allows the attacker to exploit vulnerabilities present in web file. - Explain preg_Match and preg_replace?
• These are the commonly used regular expressions in PHP. These are an inbuilt function that is used to work with other regular functions.
• preg-Match: This is the function used to match a pattern in a defined string. If the patterns match with string, it returns true otherwise it returns false.
• Preg_replace: This function is used to perform a replace operation. In this, it first matches the pattern in the string and if pattern matched, ten replace that match with the specified pattern. - Explain mail function in PHP with syntax?
The mail function is used in PHP to send emails directly from script or website. It takes five parameters as an argument.
Syntax of mail (): mail (to, subject, message, headers, parameters);
• to refers to the receiver of the email
• Subject refers to the subject of an email
• the message defines the content to be sent where each line separated with /n and also one line can’t exceed 70 characters.
• Headers refer to additional information like from, Cc, Bcc. These are optional.
• Parameters refer to an additional parameter to the send mail program. It is also optional - What is difference between md5 and SHA256?
Both MD5 and SHA256 are used as hashing algorithms. They take an input file and generate an output which can be of 256/128-bit size. This output represents a checksum or hash value. As, collisions are very rare between hash values, so no encryption takes place.
• The difference between MD5 and SHA256 is that the former takes less time to calculate than later one.
• SHA256 is difficult to handle than MD5 because of its size.
• SHA256 is less secure than MD5
• MD5 result in an output of 128 bits whereas SHA256 result output of 256 bits.
Concluding all points, it will be better to use MDA5 if you want to secure your files otherwise you can use SHA256. - What is the difference between nowdoc and heredoc?
Heredoc and nowdoc are the methods to define the string in PHP in different ways.
• Heredoc process the $variable and special character while nowdoc doesn’t do the same.
• Heredoc string uses double quotes “” while nowdoc string uses single quote ”
• Parsing is done in heredoc but not in nowdoc. - What should be the length of variable for SHA256?
It is clear from the name SHA256 that the length is of 256 bits long. If you are using hexadecimal representation, then you require 64 digits to replace 256 bits, as one digit represents four bits. Or if you are using a binary representation which means one byte equals to eight bits, then you need 32 digits.
- What is Type hinting in PHP ?
In PHP5 or above, type hinting is a process used to specify the data type of a given argument. This is mainly used in a function declaration. Whenever the function is called, PHP checks if the arguments are of the type preferred by the user or not. If the argument is not of the specified type, the run time will display an error and the program will not execute.
X - Explain mail function in PHP with syntax?
The mail function is used in PHP to send emails directly from script or website. It takes five parameters as an argument.
Syntax of mail (): mail (to, subject, message, headers, parameters);
• to refers to the receiver of the email
• Subject refers to the subject of an email
• the message defines the content to be sent where each line separated with /n and also one line can’t exceed 70 characters.
• Headers refer to additional information like from, Cc, Bcc. These are optional.
• Parameters refer to an additional parameter to the send mail program. It is also optional - How can you get the size of an image in PHP?
getimagesize() function is used to get the size of an image in PHP. This function takes the path of file with name as an argument and returns the dimensions of an image with the file type and height/width. Syntax:
array getimagesize( $filename, $image_info ) - How can we convert the time zones using PHP?
date_default_timezone_set() funtion is used to convert/change the time zones in PHP.
Example
date_default_timezone_set(‘Asia/Philippines’); - What is the difference between == and === operator in PHP ?
In PHP == is equal operator and returns TRUE if $a is equal to $b after type juggling and === is Identical operator and return TRUE if $a is equal to $b, and they are of the same data type.
- Where sessions stored in PHP ?
Default session time in PHP is 1440 seconds (24 minutes) and the Default session storage path is temporary folder/tmp on server.
- What is difference between include,require,include_once and require_once() ?
Include :-Include is used to include files more than once in single PHP script.You can include a file as many times you want.
Syntax:- include(“file_name.php”);
Include Once:-Include once include a file only one time in php script.Second attempt to include is ignored.
Syntax:- include_once(“file_name.php”);
Require:-Require is also used to include files more than once in single PHP script.Require generates a Fatal error and halts the script execution,if file is not found on specified location or path.You can require a file as many time you want in a single script.
Syntax:- require(“file_name.php”);
Require Once :-Require once include a file only one time in php script.Second attempt to include is ignored. Require Once also generates a Fatal error and halts the script execution ,if file is not found on specified location or path.
Syntax:- require_once(“file_name.php”); - What are constructor and destructor in PHP ?
PHP constructor and a destructor are special type functions which are automatically called when a PHP class object is created and destroyed.
Generally Constructor are used to intializes the private variables for class and Destructors to free the resources created /used by class . - How to increase the execution time of a PHP script ?
The default max execution time for PHP scripts is set to 30 seconds. If a php script runs longer than 30 seconds then PHP stops the script and reports an error.
You can increase the execution time by changing max_execution_time directive in your php.ini file or calling ini_set(‘max_execution_time’, 300); //300 seconds = 5 minutes function at the top of your php script. - What is purpose of @ in Php ?
In PHP @ is used to suppress error messages.When we add @ before any statement in php then if any runtime error will occur on that line, then the error handled by PHP
- What are different types of errors available in Php ?
There are 13 types of errors in PHP, We have listed all below
• E_ERROR: A fatal error that causes script termination.
• E_WARNING: Run-time warning that does not cause script termination.
• E_PARSE: Compile time parse error.
• E_NOTICE: Run time notice caused due to error in code.
• E_CORE_ERROR: Fatal errors that occur during PHP initial startup.
(installation)
• E_CORE_WARNING: Warnings that occur during PHP initial startup.
• E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
• E_USER_ERROR: User-generated error message.
• E_USER_WARNING: User-generated warning message.
• E_USER_NOTICE: User-generated notice message.
• E_STRICT: Run-time notices.
• E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
• E_ALL: Catches all errors and warnings. - Is multiple inheritance supported in PHP ?
NO, multiple inheritance is not supported by PHP
- What are the encryption functions available in PHP ?
crypt(), Mcrypt(), hash() are used for encryption in PHP
- What are the various blunders in PHP?
There are 4 essentially sorts of blunder.
Parse Error – Commonly caused because of linguistic structure botches in codes, for example, missing semicolon, confuse sections.
Deadly Error – These are fundamentally run time mistakes which are caused when you attempt to get to what isn’t possible. For example, getting to a dead item, or attempting to utilize a capacity that hasn’t been proclaimed.
Cautioning Error – These happen when u attempt to incorporate a document that is absent or erase a record that isn’t on the server. This won’t end the content; it will give the notice and proceed with the following line of the content.
Notice Error – These blunders happen when u attempt to utilize a variable that hasn’t been proclaimed, this won’t end the content, It will give the notice and proceed with the following line of the content. - What is the distinction among detonate() and part() capacities?
Split capacity parts string into the exhibit by customary articulation. Detonate parts a string into the cluster by a string.
- How to strip whitespace (or different characters) from the earliest starting point and end of a string?
The trim() work evacuates whitespaces or other predefined characters from the two sides of a string.
- How to set a page as a landing page in a PHP based site?
index.php is the default name of the landing page in PHP based locales.
- How to discover the length of a string?
strlen() work used to discover the length of a string.
- What is the utilization of “ksort” in PHP?
It is utilized to sort a cluster by key backward request
- How would we be able to make a database utilizing PHP and MySQL?
We can make MySQL database with the utilization of mysql_create_db(“Database Name”)
- What is utilization of header() work in PHP?
The header() work sends a crude HTTP header to a client. We can utilize herder() work for redirection of pages. Notice that header() must be called before any genuine yield is seen.
- How would we be able to decimate the treat?
Set the treat in the past.
- Is various legacy upheld in PHP?
PHP incorporates just single legacy, it implies that a class can be stretched out from just one single class utilizing the catchphrase ‘expanded’.
- What is the importance of the last class and the last technique?
‘last’ is presented in PHP5. Last class implies that this class can’t be broadened and the last technique can’t be overridden.
- How examination of articles is done in PHP5?
We utilize the administrator ‘==’ to test is two articles are instanced from a similar class and have the same properties and equivalent qualities. We can test if two articles are refering to a similar occasion of a similar class by the utilization of the character administrator ‘===’.
- What does the PHP blunder ‘Parse mistake in PHP – surprising T_variable at line x’ signifies?
This is a PHP language structure blunder communicating that a slip-up at the line x quits parsing and executing the program
- Which capacity gives us the quantity of influenced sections by an inquiry?
mysql_affected_rows() return the number of passages influenced by a SQL inquiry.
- What does the disconnected() work implies?
The disconnected() work is devoted to variable administration. It will make a variable vague.
- What is the use of rand() in php?
It is used to generate random numbers. If called without the arguments it returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 6 and 12 (inclusive), for example, use rand(6, 12).This function does not generate cryptographically safe values, and should not be used for cryptographic uses. If you want a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.
- How is the ternary conditional operator used in PHP?
It is composed of three expressions: a condition, and two operands describing what instruction should be performed when the specified condition is true or false as follows:
- Any_Question_Returns_Boolean ? What_if_True : What_if_False;
Are Parent constructors called implicitly inside a class constructor?
No, a parent constructor have to be called explicitly as follows:
parent::constructor($value) - When sessions ends?
Sessions automatically ends when the PHP script finishs executing, but can be manually ended using the session_write_close().
- Why cause $_FILES may be empty when uploading files to PHP?
Following reason may be for empty of $_FILES
multipart/form-data is missing in form tag.
/tmp folder does not have enough permission. In this folder uploaded file moved temporary.
You have upload heavy files more than allowd in php.ini (post_max_size and upload_max_filesize)
file_uploads is off in php.ini - PHP Questions For Interview: What is mod_php?
Answer: mod_php means PHP installed as a module in Apache.
- PHP Questions For Interview: How to prevent form hijacking in PHP?
Answer: Make register_globals to off to prevent Form Injection with malicious data.
Make Error_reporting to E_ALL so that all variables will be intialized before using them.
Make practice of using htmlentities(), strip_tags(), utf8_decode() and addslashes() for filtering malicious data in php
SQL injection attacks by using mysql_escape_string().
User Input Sanitization-Never trust web user submitted data. Follow good clieint side data validation practices with regular expressions before submitting data to the serve.
Form Submision Key Validation: A singleton method can be used to generate a Session form key & validating form being submitted for the same value against hidden form key params. - PHP Questions For Interview: What’s the difference between AND and &&?
Answer: && has precedence over AND and it has precedence over =. AND, on the other hand does not have a precedence over =. That means that when using AND in an assignment operation, the assignment will execute before the comparison.
- PHP Questions For Interview: What are the extensions of PHP File?
Answer: .php, .phtml, .php3, .php4, .php5, .php7, .phps .
- PHP Questions For Interview: How to Print Fibonacci Series in PHP?
Answer: Fibonacci series is the one in which you will get your next term by adding previous two numbers. Here is the program to print the Fibonacci Series in PHP with try it editor in the end to test your logical ideas.
- PHP Questions For Interview: What are super global variables.
Answer: The superglobal variables as follows:
$_COOKIE – It Stores all the information in an associative array of variables passed to the current script via HTTP Cookies.
$_GET – Send data to the server which is visible in the URL of the browser. It is not safe to send sensitive using the GET method.
$_POST – Send data to the server which is not visible in the URL. When the user submits the form with the method set as the POST Method.
$_REQUEST – Its combined array containing values from the $_GET, $_POST and $_COOKIE global variables.
$_ENV – Get/Set an associative array of variables passed to the current script via the environment method…
$_FILES – Get an associative array of items uploaded to the current script via the HTTP POST method. Used to upload the file, image, and videos, etc on the server. It contains all the information i.e name, extension, temporary name, etc.
$_SERVER – It saves all information related to headers, paths, and script locations.
$_SESSION – It contains session variables available to the current script.
$GLOBALS – PHP super global variable which is used to access global variables from anywhere in the PHP script. Contains all the global variables associated with the current script. - PHP Questions For Interview: What are the advantages of PHP MySQL?
Answer: It is a stable, reliable and powerful solution with advanced features like the following:
Data Security
On-Demand Scalability
High Performance
Round-the-clock Uptime
Comprehensive Transactional Support
Complete Workflow Control
Reduced Total Cost of Ownership
The Flexibility of Open Source - PHP Questions For Interview: Is it possible for you to share a single instance when it comes to a Memcache between many PHP projects?
Answer: Yes, you can share a single instance when it comes to a Memcache between many PHP projects. It is essential to understand that Memcache is nothing but a memory storage space. In addition to that, you can also run Memcache on several servers if you want. It is also possible for you to configure your client so that you can speak to a specific set of instances.Therefore, it is possible for you to run two distinct Memcache processes on a similar host. Yet, they are both completely independent. That said, in case you have partitioned all your data, it becomes crucialto know the precise instance from which to get the data or to put into.
- PHP Questions For Interview: Describe how it is possible to update Memcached while making changes to PHP.
Answer: While making changes to PHP, you can update Memcache in two ways:
By clearing the cache proactively when an update or insert is made
By resetting the cachewhich is quite identical to the first method, only you reset the values after an update or insert instead of merely deleting the keys and then waiting for the subsequent request of data in order to refresh the cache. - PHP Questions For Interview: How is it possible to ascertain if a specific PHP variable belongs to an instantiated object coming from a certain class?
Answer: In order to determine if a specific PHP variable belongs to an instantiated object coming from a certain class, ‘instanceof’ is used.
- PHP Questions For Interview: State the difference between $a !== $b and $a != $?
Answer:
!== represents non-identity i.e. TRUE in the case of $a being unidentical to $b. != represents inequality i.e. TRUE in the case of $a being unequal to $b. - PHP Questions For Interview: Describe the two fundamental string operators?
Answer: Concatenation operator or (‘.’) is the first-string operator that returns the concatenation of its left and right arguments. The second-string operator is (‘.=’)that appends the right argument to the left argument.
- PHP Questions For Interview: Why is Facebook still using PHP?
Answer: Facebook technology stack consist of application written in many language, including PHP and many others. Facebook still using PHP but it has built a compiler for it so it can be turned into native code on. Facebook doesn’t use PHP for its core system, at Facebook, they uses C++ heavily on back end system.
- PHP Questions For Interview: Can you use PHP and Javascript together?
Answer: So, when we develop web pages, we can have a combination of HTML, Javascript, CSS and PHP in our pages. If you need to use a scripting language, such as PHP, once the page has been loaded into the browser, then you must either refresh the page or use Ajax to request more processing at the server side.
- PHP Questions For Interview: How do I install PHP?
Answer: Here ie the Manual Installation Procedure
Step 1: download the files. Download the latest PHP 5 ZIP package from www.php.net/downloads.php
Step 2: extract the files
Step 3: configure php.ini
Step 4: add C:php to the path environment variable
Step 5: configure PHP as an Apache module
Step 6: test a PHP file - PHP Questions For Interview: How do I update PHP?
Answer:
Changing the PHP Version:
Log into cPanel.
Click the PHP Configuration button in the Software section.
Select the version of PHP you want to use from the dropdown.
Click the Update button to save your php configuration.
Check your changes by viewing your settings in a phpinfo page. - PHP Questions For Interview: What is the difference between null and undefined?
Answer: undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value. Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
- PHP Questions For Interview: What is the use of callback in PHP?
Answer: PHP callback are functions that may be called dynamically by PHP. They are used by native functions such as array_map, usort, preg_replace_callback, etc. Here is a reminder of the various ways to create a callback function in PHP, and use it with the native functions.
- PHP Questions For Interview: What is encapsulation in PHP?
Answer: Encapsulation is an OOP (Object Oriented Programming) concept in PHP. Wrapping some data in single unit is called Encapsulation. Second advantage of encapsulation is you can make the class read only or write only by providing setter or getter method. Capsule is best example of Encapsulation.
- PHP Questions For Interview: What is boolean in PHP?
Answer: PHP Booleans. A Boolean value is one that is in either of two states. They are known as True or False values, in programming. True is usually given a value of 1, and False is given a value of zero.
- What is the use of Print_r function in PHP?
Answer: prinf : It is a function which takes atleast one string and format style and returns length of output string. print_r() is used for printing the array in human readable format. they both are language constructs. echo returns void and print returns 1.
- PHP Questions For Interview: What is the use of anonymous function in PHP?
Answer: Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.
- PHP Questions For Interview: What is polymorphism in PHP?
Answer: Polymorphism is a long word for a very simple concept. Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.
- PHP Questions For Interview: What is the use of die in PHP?
Answer: The die() function prints a message and exits the current script. This function is an alias of the exit() function.
- PHP Questions For Interview: How do you debug PHP?
Answer: To run a debugging session: Start the ide and open the file that contains the source code that you want to debug. Set a breakpoint at each line where you want the debugger to pause. To set a breakpoint, place the cursor at the beginning of a line and press Ctrl-F8/⌘-F8 or choose Debug > Toggle Line Breakpoint.
- PHP Questions For Interview: What is the meaning of xdebug?
Answer: Xdebug is a PHP extension which provides debugging and profiling capabilities. It uses the DBGp debugging protocol.
- PHP Questions For Interview: What is Chrome logger?
Answer: Chrome Logger is a Google Chrome extension for debugging server side applications in the Chrome console. Most languages include their own logging capabilities, but sometimes it is easier to see your logs right in the browser. Chrome Logger used to be known as ChromePHP.
- PHP Questions For Interview: What is the Phpstorm?
Answer: JetBrains PhpStorm is a commercial, cross-platform IDE for PHP built on JetBrains’ IntelliJ IDEA platform. PhpStorm provides an editor for PHP, HTML and JavaScript with on-the-fly code analysis, error prevention and automated refactorings for PHP and JavaScript code.
- PHP Questions For Interview: What is stdClass in PHP?
Answer: stdClass is a PHP generic empty class and stdClass is used to create the new Object. stdClass is a kind of Object in Java or object in Python but not actually used as universal base class.
- PHP Questions For Interview: What are soundex() and metaphone() functions in PHP?
Answer: soundex and metaphone can be used to find strings that sound similar when pronounced out loud.
soundex() function calculates the soundex key of a string. A soundex key is a four character long alphanumeric strings that represents English pronunciation of a word.
metaphone() the metaphone() function calculates the metaphone key of a string. A metaphone key represents how a string sounds if pronounced by an English person. - PHP Questions For Interview: What is $this?
Answer: It is the way to reference an instance of a class from within itself, the same as many other object-oriented languages. $this refers to the class you are in. In PHP, the pseudo-variable $this is available when a method is called from within an object context.
- PHP Questions For Interview: When to use self over $this?
Answer: Use $this to refer to the current object. Use self to refer to the current class.
- PHP Questions For Interview: What is input sanitization in PHP?
Answer: PHP filters are used to validate and sanitize external input. The PHP filter extension has many of the functions needed for checking user input, and is designed to make data validation easier and quicker.
- What is the use of Htmlspecialchars in PHP?
Answer: In many PHP legacy products the function htmlspecialchars($string) is used to convert characters like < and > and quotes a.s.o to HTML-entities.
- PHP Questions For Interview: What are the delimiters in PHP?
Answer: When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. Often used delimiters are forward slashes (/), hash signs (#) and tildes (~).
- PHP Questions For Interview: What is Warning – “Cannot modify header information – headers already sent”?
Answer: In PHP when you output something (do an echo or print) if has to send the HTTP headers at that time. If you turn on output buffering you can output in the script but PHP doesn’t have to send the headers until the buffer is flushed. This will turn output buffering out without the need to call ob_start().
- PHP Questions For Interview: Explain about getters and setters in PHP?
Answer: “Getters” and “Setters” are object methods that allow you to control access to a certain class variables / properties. Sometimes, these functions are referred to as “mutator methods”. A “getter” allows to you to retrieve or “get” a given property. A “setter” allows you to “set” the value of a given property.
- PHP Questions For Interview: What Is Autoloading Classes In PHP?
Answer: With autoloaders, PHP allows the last chance to load the class or interface before it fails with an error.
The spl_autoload_register() function in PHP can register any number of autoloaders, enable classes and interfaces to autoload even if they are undefined. - PHP Questions For Interview: How to fix “Headers already sent” error in PHP ?
Answer: No output before sending headers. there should not be any output (i.e. echo.. or HTML codes) before the header(…….);command. remove any white-space(or newline) before tags. After header(…); you must use exit;
- PHP Questions For Interview: How can we fix “Memory size Exhausted” errors ?
Answer: You can fix it at run time or can be set required size on the php.ini file