PHP Interview Questions and Answers

PHP Interview Questions and Answers

Last updated on 17th Sep 2020, Blog, Interview Question

About author

Vishali ( (Sr Technical Project Manager, TCS ) )

She is Possessing 9+ Years Of Experience in PHP. Her Passion lies in Developing Entrepreneurs & Activities. Also, Rendered her intelligence to the Enthusiastic JOB Seekers.

(5.0) | 16547 Ratings 1114

       PHP is an acronym for “PHP: Hypertext Preprocessor”. PHP is a widely-used, open source scripting language. PHP scripts are executed on the server. PHP is free to download and use. PHP is an amazing and popular language!. It is powerful enough to be at the core of the biggest blogging system on the web (WordPress)!. It is  easy enough to be a beginner’s first server side language!

Below we have listed the top 100 PHP interview questions & answers for fresher and experienced candidates to clear the job interview. 

1.Draw a comparison between the compile-time exception and the runtime exception. What are they called?

Ans:

Checked exception is the exception that occurs at the compile time. As it is not possible to ignore this type of exception, it needs to be handled cautiously. An unchecked exception, on the other side, is the one that occurs during the runtime. If a checked exception is not handled, it becomes an unchecked exception.

2.Explain Path Traversal?

Ans:

  • Path Traversal is a form of attack to read into the files of a web application. ‘../’ is known as dot-dot-sequences. It is a cross-platform symbol to go up in the directory. To operate the web application file, Path Traversal makes use of the dot-dot-slash sequences.
  • The attacker can disclose the content of the file attacked using the Path Traversal outside the root directory of a web server or application. It is usually done to gain access token, secret passwords, and other sensitive information stored in the files.
  • Path Traversal is also known as Directory Traversal. It enables the attacker to exploit vulnerabilities present in the web file under attack.

3.Explain the difference between GET and POST requests.

Ans:

Any PHP developer needs to have an adequate understanding of the HTTP protocol. The differences between GET and POST are an indispensable part of the HTTP protocol learning. Here are the major differences between the two requests:

    Subscribe For Free Demo

    • GET allows displaying the submitted data as part of the URL. This is not the case when using POST as during this time, the data is encoded in the request.
    • The maximum number of characters handled by GET is limited to 2048. No such restrictions are imposed on POST.
    • GET provides support for only ASCII data. POST, on the other hand, allows ASCII, binary data, as well as other forms of data.
    • Typically, GET is used for retrieving data while POST is used for inserting and up

    4.Is PHP a strongly typed language?

    Ans:

    No. PHP is a weakly typed or loosely typed language.This means PHP does not require to declare data types of the variable when you declare any variable like the other standard programming languages C# or Java. When you store any string value in a variable, then the data type is the string and if you store a numeric value in that same variable then the data type is an Integer.

    Sample code:

    • $var = “Hello”; //String
    • $var = 10; //Integer

    5.How is the comparison of objects done in PHP?

    Ans:

    The operator ‘==’ is used for checking whether two objects are instanced using the same class and have the same attributes as well as equal values. To test whether two objects are referring to the same instance of the same class, the identity operator ‘===’ is used.

    6.What are some common error types in PHP?

    Ans:

    PHP supports three types of errors:

    • Notices – Errors that are non-critical. These occur during the script execution. Accessing an undefined variable is an instance of a Notice.
    • Warnings – Errors that have a higher priority than Notices. Like with Notices, the execution of a script containing Warnings remains uninterrupted. An example of a Notice includes a file that doesn’t exist.
    • Fatal Error – A termination in the script execution results as soon as such an error is encountered. Accessing a property of a non-existing object yields a Fatal Error.

    7.What is meant by variable variables in PHP?

    Ans:

    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:

    • $str = “PHP”;$$str = ” Programming”; //declaring variable variablesecho “$str ${$str}”; //It will print “PHP programming”echo “$PHP”; //It will print “Programming”

    8.What are the differences between echo and print?

    Ans:

    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 the boolean value after printing the output.

    Sample code:

    • echo “PHP Developer”;$n = print “Java Developer”;

    9.How can you execute PHP script from the command line?

    Ans:

    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

    10.How can you declare the array in PHP?

    Ans:

    You can declare three types of arrays in PHP. They are numeric, associative and multidimensional arrays.

    Sample code:

    • //Numeric Array$computer = array(“Dell”, “Lenavo”, “HP”);
    • //Associative Array$color = array(“Sithi”=>”Red”, “Amit”=>”Blue”, “Mahek”=>”Green”);//Multidimensional Array$courses = array ( array(“PHP”,50), array(“JQuery”,15), array(“AngularJS”,20) );

    11.What are the uses of explode() and implode() functions?

    Ans:

    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:

    • $text = “I like programming”;print_r (explode(” “,$text));$strarr = array(‘Pen’,’Pencil’,’Eraser’);echo implode(” “,$strarr);

    12.Which function can be used to exit from the script after displaying the error message?

    Ans:

    You can use exit() or die() function to exit from the current script after displaying the error message.

    Sample code:

    • if(!fopen(‘t.txt’,’r’))
    • exit(” Unable to open the file”);

    Sample code:

    • if(!mysqli_connect(‘localhost’,’user’,’password’))die(” Unable to connect with the database”);

    13.Which function is used in PHP to check the data type of any variable?

    Ans:

    gettype() function is used to check the data type of any variable.

    Sample code:

    • echo gettype(true).”; //booleanecho gettype(10).”; //integerecho gettype(‘Web Programming’).”; //stringecho gettype(null).”; //NULL

    14.How can you increase the maximum execution time of a script in PHP?

    Ans:

    You need to change the value of the max_execution_time directive in the php.ini file for increasing the maximum execution time.

    For Example,

    if you want to set the max execution time for 120 seconds, then set the value as follows,

    • max_execution_time = 120

    15.What is meant by ‘passing the variable by value and reference’ in PHP?

    Ans:

    When the variable is passed as value then it is called pass variable by value. Here, the main variable remains unchanged even when the passed variable changes.

    Sample code:

    • function test($n) {$n=$n+10;} $m=5;test($m);echo $m;

    When the variable is passed as a reference then it is called pass variable by reference. Here, both the main variable and the passed variable share the same memory location and & is used for reference.

    So, if one variable changes then the other will also change.

    Sample code:

    • function test(&$n) {    $n=$n+10;}$m=5;test($m);echo $m;

    16.Explain type casting and type juggling.

    Ans:

    The way by which PHP can assign a particular data type for any variable is called typecasting. The required type of variable is mentioned in the parenthesis before the variable.

    Sample code:

    • $str = “10”; // $str is now string$bool = (boolean) $str; // $bool is now boolean

    PHP does not support datatype for variable declaration. The type of the variable is changed automatically based on the assigned value and it is called type juggling.

    Sample code:

    • $val = 5; // $val is now number$val = “500” //$val is now string

    17.How can you make a connection with MySQL server using PHP?

    Ans:

    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:

    • $mysqli = mysqli_connect(“localhost”,”username”,”password”);$mysqli = new mysqli(“localhost”,”username”,”password”);

    18.How can you retrieve data from the MySQL database using PHP?

    Ans:

    Many functions are available in PHP to retrieve the data from the MySQL database.

    Few functions are mentioned below:

    a) mysqli_fetch_array() – It is used to fetch the records as a numeric array or an associative array.

    Sample code:

    • // Associative or Numeric array$result=mysqli_query($DBconnection,$query); $row=mysqli_fetch_array ($result,MYSQLI_ASSOC);echo “Name is $row[0]”;echo “Email is $row[’email’]”;

    b) mysqli_fetch_row() – It is used to fetch the records in a numeric array.

    Sample code:

    • //Numeric array$result=mysqli_query($DBconnection,$query); $row=mysqli_fetch_array($result);printf (“%s %s\n”,$row[0],$row[1]);

    c) mysqli_fetch_assoc() – It is used to fetch the records in an associative array.

    Sample code:

    • // Associative array$result=mysqli_query($DBconnection,$query); $row=mysqli_fetch_array($result);printf (“%s %s\n”,$row[“name”],$row[“email”]);

    d) mysqli_fetch_object() – It is used to fetch the records as an object.

    Sample code:

    • // Object$result=mysqli_query($DBconnection,$query); $row=mysqli_fetch_array($result);printf (“%s %s\n”,$row->name,$row->email);

    19.What are the differences between mysqli_connect and mysqli_pconnect?

    Ans:

    mysqli_pconnect() function is used for making a persistent 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.

    Sample code:

    • $DBconnection = mysqli_connect(“localhost”,”username”,”password”,”dbname”);// Check for valid connectionif (mysqli_connect_errno()){echo “Unable to connect with MySQL: ” . mysqli_connect_error();}

    mysqli_pconnect() function is depreciated in the new version of PHP, but you can create a persistence connection using mysqli_connect with the prefix p.

    20.Which function is used in PHP to count the total number of rows returned by any query?

    Ans:

    mysqli_num_rows() function is used to count the total number of rows returned by the query.

    Sample code:

    • $mysqli = mysqli_connect(“hostname”,”username”,”password”,”DBname”); $result=mysqli_query($mysqli,”select * from employees”);$count=mysqli_num_rows($result);

    21.How can you create a session in PHP?

    Ans:

    session_start() function is used in PHP to create a session.

    Sample code:

    • session_start(); //Start session$_SESSION[‘USERNAME’]=’Fahmida’; //Set a session valueunset($_SESSION[‘USERNAME’]; //delete session value

    22.What is the use of imagetypes() method?

    Ans:

    image types() function returns the list of supported images of the installed PHP version. You can use this function to check if a particular image extension is supported by PHP or not.

    Sample code:

    • //Check BMP extension is supported by PHP or notif (imagetypes() &IMG_BMP) {    echo “BMP extension Support is enabled”;}

    23.Which function you can use in PHP to open a file for reading or writing or for both?

    Ans:

    You can use fopen() function to read or write or for doing both in PHP.

    Sample code:

    • $file1 = fopen(“myfile1.txt”,”r”); //Open for reading
    • $file2 = fopen(“myfile2.txt”,”w”); //Open for writing
    • $file3 = fopen(“myfile3.txt”,”r+”); //Open for reading and writing

    24.What is the difference between include() and require()?

    Ans:

    Both include() and require() function are used for including PHP script from one file to another file. But there is a difference between these functions.

    If any error occurs at the time of including a file using include() function, then it continues the execution of the script after showing an error message. require() function stops the execution of a script by displaying an error message if an error occurs.

    Sample code:

    • if (!include(‘test.php’)) echo “Error in file inclusion”;if (!require(‘test.php’)) echo “Error in file inclusion”;

    25.Which function is used in PHP to delete a file?

    Ans:

    unlink() function is used in PHP to delete any file.

    Sample code:

    • unlink(‘filename’);
    Course Curriculum

    Best PHP Training & Certification Course and Upgrade Your Skills

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

    26.How can you send an HTTP header to the client in PHP?

    Ans:

    The header() function is used to send raw HTTP header to a client before any output is sent.

    Sample code:

    • header(‘Location: http://www.your_domain/’);

    27.Which functions are used to count the total number of array elements in PHP?

    Ans:

    count() and sizeof() functions can be used to count the total number of array elements in PHP.

    Sample code:

    • $names=array(“Asa”,”Prinka”,”Abhijeet”);
    • echo count($names);
    • $marks=array(95,70,87);
    • echo sizeof($marks);

    28.What is the difference between substr() and strstr()?

    Ans:

    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.

    Sample code:

    • echo substr(“Computer Programming”,9,7); //Returns “Program”
    • echo substr(“Computer Programming”,9); //Returns “Programming”

    Sample code:

    • echo strstr(“Learning Laravel 5!”,”Laravel”); //Returns Laravel 5!
    • echo strstr(“Learning Laravel 5!”,”Laravel”,true); //Returns Learning

    29.How can you upload a file using PHP?

    Ans:

    To upload a file by using PHP, you have to do the following tasks.

    (i) Enable file_uploads directive

    Open php.ini file and find out the file_uploads directive and make it on.

    • file_uploads = On

    (ii) Create an HTML form using enctype attribute and file element for uploading the file.

    • <form action=”upload.php” method=”post” enctype=”multipart/form-data”>
    • <input type=”file” name=”upd” id=”upd”>
    • <input type=”submit” value=”Upload” name=”upload”>
    • </form>

    (iii) Write a PHP script to upload the file

    • if (move_uploaded_file($_FILES[“upd”][“tmp_name”], “Uploads/”)) {
    • echo “The file “. basename( $_FILES[“upd”][“name”]). ” is uploaded.”;
    • } else {
    • echo “There is an error in uploading.”;
    • }

    30.How can you declare a constant variable in PHP?

    Ans:

    define() function is used to declare a constant variable in PHP. Constant variable declares without the $ symbol.

    Sample code:

    • define(“PI”,3.14);

    31.Which function is used in PHP to search a particular value in an array?

    Ans:

    in_array() function is used to search a particular value in an array.

    Sample code:

    • $languages = array(“C#”, “Java”, “PHP”, “VB.Net”);
    • if (in_array(“PHP”, $languages)) {
    • echo “PHP is in the list”;
    • }
    • else {
    • echo “php is not in the list”;
    • }

    32.What is the meaning of PEAR in PHP?

    Ans:

    PEAR stands for PHP Extension and Application Repository. It is one of the frameworks and acting repositories that host all of the reusable PHP components. Alongside containing some of the PHP libraries, it also provides you with a simple interface to automatically install packages.

    33.How is a PHP script executed?

    Ans:

    PHP scripts can be easily executed from the command-line interface (CLI). The syntax is as follows:

    • php filename.php

    Here, filename refers to the file that contains scripts. The extension .php is needed alongside the filename.

    34.What are the types of variables present in PHP?

    Ans:

    There are eight primary data types in PHP as shown below:

    • Array: A named and ordered collection of data
    • Boolean: A logical value (True or False)
    • Double: Floating point numbers such as 5.1525
    • Integer: Whole numbers without a floating point
    • Object: An instance of classes, containing data and functions
    • NULL: A special data type, supporting only the NULL data
    • Resource: Special variables that hold references to external resources
    • String: A sequence of characters such as, “Hello learners!”

    35.What are the variable-naming rules you should follow in PHP?

    Ans:

    There are two main rules that you have to follow when naming a variable in PHP. They are as follows:

    • Variables can only begin with letters or underscores.
    • Special characters such as +, %, -, &, etc. cannot be used.

    36.What are the main characteristics of a PHP variable?

    Ans:

    Following are some of the most important aspects of the usage of variables in PHP:

    • Variables can be declared before the value assignment.
    • A variable value assignment happens using the ‘=’ operator.
    • Every variable in PHP is denoted with a $ (dollar) sign.
    • The value of a variable depends on its latest assigned value.
    • PHP variables are not intrinsic. There is no explicit declaration.

    Next up on these PHP interview questions for freshers, you need to understand what NULL is.

    37.What is NULL in PHP?

    Ans:

    NULL is a special data type in PHP used to denote the presence of only one value, NULL. You cannot assign any other value to it.

    NULL is not case sensitive in PHP and can be declared in two ways as shown below:

    • $var = NULL:
    • Or
    • $var = null;

    Both of the above syntaxes work fine in PHP.

    38.How are constants defined in PHP?

    Ans:

    Constants can be defined easily in PHP by making use of the define() function. This function is used to define and pull out the values of the constants easily.

    Constants, as the name suggests, cannot be changed after definition. They do not require the PHP syntax of starting with the conventional $ sign.

    39.What is the use of the constant() function in PHP?

    Ans:

    The constant() function is used to retrieve the values predefined in a constant variable. It is used especially when you do not know the name of the variable.

    40.What are the various constants predefined in PHP?

    Ans:

    PHP consists of many constants, and following are some of the widely used ones:

    • _METHOD_: Represents the class name
    • _CLASS_: Returns the class name
    • _FUNCTION_: Denotes the function name
    • _LINE_: Denotes the working line number
    • _FILE_: Represents the path and the file name

    41.What does the phrase ‘PHP escape’ mean?

    Ans:

    PHP escape is a mechanism that is used to tell the PHP parser that certain code elements are different from PHP code. This provides the basic means to differentiate a piece of PHP code from the other aspects of the program.

    42.What is the meaning of break and continue statements in PHP?

    Ans:

    Break: This statement is used in a looping construct to terminate the execution of the iteration and to immediately execute the next snippet of code outside the block of the looping construct.

    Continue: This statement is used to skip the current iteration of the loop and continue to execute the next iteration until the looping construct is exited.

    43.What are some of the popular frameworks in PHP?

    Ans:

    There are many frameworks in PHP that are known for their usage. Following are some of them:

    • CodeIgniter
    • CakePHP
    • Laravel
    • Zend
    • Phalcon
    • Yii 2

    44.What is the use of the final class and the final method in PHP?

    Ans:

    The ‘final’ keyword, if present in a declaration, denotes that the current method does not support overriding by other classes. This is used when there is a requirement to create an immutable class.

    45.How does JavaScript interact with PHP?

    Ans:

    JavaScript is a client-side programming language, while PHP is a server-side scripting language. PHP has the ability to generate JavaScript variables, and this can be executed easily in the browser, thereby making it possible to pass variables to PHP using a simple URL.

    Course Curriculum

    Best PHP Training & Certification Course and Upgrade Your Skills

    Weekday / Weekend BatchesSee Batch Details

    46.Does PHP interact with HTML?

    Ans:

    Yes, HTML and PHP interaction is the core of what makes PHP what it is. PHP scripts have the ability to generate HTML mode and move around information very easily.

    PHP is a server-side scripting language, while HTML is a client-side language. This interaction helps bridge the gaps and use the best of both languages.

    47.What are the types of arrays supported by PHP?

    Ans:

    There are three main types of arrays that are used in PHP.

    • Indexed arrays: These are arrays that contain numerical data. Data access and storage are linear.
    • Associative arrays: There are arrays that contain strings for indexing elements.
    • Multidimensional arrays: These are arrays that contain more than one index and dimension.

    48.How does the ‘foreach’ loop work in PHP?

    Ans:

    The foreach statement is a looping construct used in PHP to iterate and loop through the array data type. The working of foreach is simple; with every single pass of the value, elements get assigned a value and pointers are incremented. This process is repeated until the end of the array.

    The following is the syntax for using the foreach statement in PHP:

    • foreach(array)
    • {
    • Code inside the loop;
    • }

    49.Who is the father of PHP ?

    Ans:

    Rasmus Lerdorf is known as the father of PHP.

    50.What is the difference between $name and $$name?

    Ans:

    $name is variable where as $$name is reference variable like $name=sonia and $$name=singh so $sonia value is singh.

    51.What are the method available in form submitting?

    Ans:

    GET and POST

    52.How can we get the browser properties using PHP?

    Ans:

    • <?php
    • echo $_SERVER[‘HTTP_USER_AGENT’].”\n\n”;
    • $browser=get_browser(null,true);
    • print_r($browser);
    • ?>

    53.What is a composer?

    Ans:

    Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. It is a dependency manager

    • It enables you to declare the libraries you depend on.
    • Finds out which versions of which packages can and need to be installed, and installs them (meaning it downloads them into your project).
      • composer init – to launch a wizard
      • composer require – to add a dependency, also creates a composer.json to manage dependencies
      • composer.lock – this file ensures that everyone in the project uses the same version of the packages by not allowing newer versions to be downloaded

    54.What is PSR?

    Ans:

    PSR Stands for PHP Standard Recommendations. These are some guidelines created by the community to bring a standard to projects/Libraries and have a common language which everyone can speak and understand.

    • Basic coding standard
    • Coding style. Guide
    • Logger interface
    • Autoloading standard
    • Caching interface
    • HTTP Message interface
    • Container interface
    • Hypermedia links
    • Http Handlers
    • Simple cache
    • HTTP Factories
    • HTTP CLIENT

    55.What is PHP-FPM?

    Ans:

    PHP-FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features useful for sites of any size, especially busier sites. These features include:

    • Adaptive process spawning (NEW!)
    • Basic statistics (ala Apache’s mod_status) (NEW!)
    • Advanced process management with graceful stop/start
    • Ability to start workers with different uid/gid/chroot/environment and different php.ini (replaces safe_mode)
    • Stdout & stderr logging
    • Emergency restart in case of accidental opcode cache destruction
    • Accelerated upload support
    • Support for a “slowlog”
    • Enhancements to FastCGI, such as fastcgi_finish_request() – a special function to finish request & flush all data while continuing to do something time-consuming (video converting, stats processing, etc.)

    56.How to do request profiling in PHP?

    Ans:

    Xdebug is an extension for PHPto assist with debugging and development. It contains a single step debugger to use with IDEs; it upgrades PHP’s var_dump() function; it adds stack trace for Notices, Warnings, Errors and Exceptions; it features functionality for recording every function call and variable assignment to disk; it contains a profiler; and it provides code coverage functionality for use with PHPUnit.

    Xhprof: Xhprof was created by Facebook and includes a basic UI for reviewing PHP profiler data. It aims to have a minimum impact on execution times and requires relatively little space to store a trace. Thus, you can run it live without a noticeable impact on users and without exhausting the memory.

    57.What are the various ways to execute PHP with Apache/Nginx?

    Ans:

    Web Servers themselves cannot understand and parse PHP files, the external programs do it for them. There are many ways how you can do this, both with its pros and cons. Various ways:

      1. 1.Mod_php: means PHP, as an Apache module
      2. 2.FastCGI: a PHP process is launched by Apache, and it is that PHP process that interprets PHP code — not Apache itself
      3. 3.PHP-FPM: PHP-FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features useful for sites of any size, especially busier sites

    58.What are Array_map, Array_reduce and Array_walk?

    Ans:

    • Array_map: Applies the callback to the elements of the given arrays
    • Array_reduce: Iteratively reduce the array to a single value using a callback function
    • Array_walk: Apply a user supplied function to every member of an array

    59.Differentiate between static and dynamic websites.

    Ans:

    Static WebsiteDynamic Website
    The content cannot be manipulated after the script is executed.The content can be changed even at the run time.
    No way to change the content as it is predefined.The content can be easily changed by manipulation and reloading.

    60.Differentiate between variables and constants in PHP.

    Ans:

    VariablesConstants
    Variables can be changedConstants cannot be changed.
    The Default scope is the current access scope.Constants can be accessed throughout without any scoping rules.
    The $ assignment is used for definitionConstants are defined using the define() function.
    It is compulsory to use $ sign at startNo need for the $ sign for constants.
    PHP Developer Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    61.Differentiate between PHP4 and PHP5.

    Ans:

    PHP4PHP5
    No support for static methodsAllows the usage of static methods
    Abstract classes cannot be declaredAbstract classes can be declared.
    The method call-by-value is usedThe method call-by-reference is used.
    Constructors can have class namesConstructors have seperate names 

    62.Differentiate between require() and require_once() functions.

    Ans:

    require()require_once()
    The inclusion and evaluation of files.Includes files if they were not included before.
    Preferred for files with fewer functionsPreferred when there are a lot of functions.

    63.How can we submit from without a submit button?

    Ans:

    We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form.

    64.What is the functionality of the function htmlentities?

    Ans:

    htmlentities Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

    65.What is meant by urlencode and urldecode?

    Ans:

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

    66.What is the difference between the functions unlink and unset?

    Ans:

    Unlink() deletes the given file from the file system.

    Unset() makes a variable undefined.

    67.How can we register the variables into a session?

    Ans:

     We can use the session_register ($ur_session_var) function.

    68.How can we get the properties (size, type, width, height) of an image using php image functions?

    Ans:

    • 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

    69.What is the maximum size of a file that can be uploaded using php and how can we change this?

    Ans:

    You can change maximum size of a file set upload_max_filesize variable in php.ini file.

    70.How can we increase the execution time of a php script?

    Ans:

    Set max_execution_time variable in php.ini file to your desired time in second

    71.What is the difference between ASP.NET and PHP?

    Ans:

    ASP.NETPHP
    A programming frameworkA scripting language
    Compiled and executedInterpreted mode of execution
    Desgined for use on windowsPlatform independent

    72.What is the most used method for hashing passwords in PHP?

    Ans:

    The crypt() function is widely used for this functionality as it provides a large amount of hashing algorithms that can be used. These algorithms include md5, sha1 or sha256.

    73.What is Zend Engine?

    Ans:

    Zend Engine is used internally by PHP as a compiler and runtime engine. PHP Scripts are loaded into memory and compiled into Zend OPCodes.

    These OPCodes are executed and the HTML generated is sent to the client.

    The Zend Engine provides memory and resource management and other standard services for the PHP language. Its performance, reliability, and extensibility have played a significant role in PHP’s increasing popularity.

    74.What library is used for PDF in PHP?

    Ans:

    The PDF functions in PHP can create PDF files using PDFlib version 6. PDFlib offers an object-oriented API for PHP5 in addition to the function-oriented API for PHP4.

    There is also the » Panda module.

    FPDF is a PHP class, which allows generating PDF files with pure PHP (without using PDFlib). F from FPDF stands for Free: we may use it for any requirement and modify it to suit our needs. FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5.

    75.What are the new features introduced in PHP7?

    Ans:

    • Zend Engine 3 performance improvements and 64-bit integer support on Windows
    • Uniform variable syntax
    • AST-based compilation process
    • Added Closure::call()
    • Bitwise shift consistency across platforms
    • (Null coalesce) operator
    • Unicode codepoint escape syntax
    • Return type declarations
    • Scalar type (integer, float, string, and Boolean) declarations

    76.What is htaccess? Why do we use it and where?

    Ans:

    The .htaccess files are configuration files of Apache Server that provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory; the directives apply to that directory and all subdirectories thereof.

    These .htaccess files are used to change the functionality and features of the Apache web server.

    For instance:

    • The .htaccess file is used for URL rewrite.
    • It is used to make the site password-protected.
    • It can restrict some IP addresses so that on these restricted IP addresses, the site will not open.

    77.What are magic methods?

    Ans:

    Magic methods are member functions that are available to all the instances of a class. Magic methods always start with ‘__’, for example, __construct(). All magic methods need to be declared as public.

    To use a method, it should be defined within the class or the program scope. Various magic methods used in PHP5 are:

    • __construct()
    • __destruct()
    • __set()
    • __get()
    • __call()
    • __toString()
    • __sleep()
    • __wakeup()
    • __isset()
    • __unset()
    • __autoload()
    • __clone()

    78.Do you think multiple inheritance support in PHP?

    Ans:

    PHP supports only particular inheritance; it means that a class can be comprehensive from only one single class using the keyword ‘extended’.

    79.How can it be possible to set an infinite execution time for PHP script?

    Ans:

    The set_time_limit (0) new at the beginning of a script sets to unlimited the execution time to not have the PHP error ‘maximum implementation time exceeded.’ We can also specify this in the php.ini file.

    80.What is the way export data into an excel file?

    Ans:

    The most frequent and used way is to get data into a format supported by Excel. For example, it is likely to write a .csv file, to prefer, comma as a partition between fields and then to open the file with Excel.

    81.What is the way to handle the result set of MySQL in PHP?

    Ans:

    The effect set can be handled using mysqli_fetch_array, mysqli_fetch_assoc, mysqli_fetch_object or mysqli_fetch_row.

    82.What is the method to check the value of a given variable is a number?

    Ans:

    It is likely to use the enthusiastic function, is numeric () to make sure whether it is a number or not.

    83.How can we automatically escape incoming data?

    Ans:

    We have to allow the Magic quotes entry in the configuration file of PHP.

    84.How can a variable be passed by reference?

    Ans:

    To be able to exceed a variable by position, we use an ampersand in front of it, as follows $var1 = &$var2

    85.When a conditional statement end with endif?

    Ans:

     When the unique if was followed by: and then the code block without braces.

    86.What does accessing a class via means?

    Ans:

    It is used to contact static methods that do not need object initialization.

    87.How can you propagate a session id?

    Ans:

    You can spread a session-id via cookies or URL parameters.

    88.When do sessions end?

    Ans:

    Sessions automatically end when the PHP script ends executing but can be physically ended using the session_write_close().

    89.What does the scope of variables mean?

    Ans:

    The range of a variable is the context within which it is clear. Mostly, all PHP variables only have a particular scope. This specific scope spans built-in and required files as well.

    90. What is the full form of PHP ?

    Ans:

    PHP is the abbreviation of Hypertext Preprocessor and earlier it was abbreviated as Personal Home Page.

    91.What are the uses of PHP ?

    Ans:

    • It is a server-side scripting language used to design dynamic websites or web applications.
    • It receives data from forms to generate the dynamic page content.
    • It can work with databases, sessions, send and receive cookies, send emails, etc.
    • It can be used to add, delete, modify content within the database.
    • It can be used to set the restriction to the user to access the web page.

    92.What are the popular Content Management Systems (CMS) in PHP ?

    Ans:

    • WordPress: WordPress is a free and open-source Content Management System(CMS) framework. It is the most widely used CMS framework of recent time.
    • Joomla: It is a free and open-source content management system (CMS) for distributing web content. It follows the model-view-controller web application framework that can be used independently.
    • Magento: It is an open-source and e-commerce platform to develop online business.
    • Drupal: It is a content management system (CMS) platform developed in PHP and distributed under the GNU (General Public License).

    93.How to make single and multi-line comments in PHP ?

    Ans:

    Comments are used to prevent the execution of the statement. It is ignored by the compiler. In PHP, there are two types of comments: single-line comments and multi-line comments.

    • Single-line comment: The comment is started with double forward-slash (//).
    • Multi-line comment: The comments are enclosed within /* comment section */

    94.What are the different types of loop in PHP ?

    Ans:

    PHP supports four different types of loop which are listed below:

    • for loop
    • while loop
    • do-while loop
    • foreach loop

    95.What is the difference between for and foreach loop in PHP ?

    Ans:

    • The for loop is considered to be openly executing the iteration whereas the foreach loop hides the iteration and is visibly simplified.
    • The performance of foreach loop is considered better in comparison with for loop.
    • The foreach loop iterates over an array of elements, the execution is simplified and finishes the loop in less time compared with for loop.
    • The foreach loop allocates temporary memory for index iterations which makes the overall system redundant its performance in terms of memory allocation.

    96.What are the three access specifiers Public, Private and Protected in PHP ?

    Ans:

    • Public Access modifier: This modifier is open to use inside as well as outside the class.
    • Protected Access modifier: This modifier is open to use within the class in which it is defined and its parent or inherited classes.
    • Private Access modifier: This modifier is open to use within the class that defines it. ( It can’t be accessed outside the class means in inherited class).

    97.How to remove line breaks from the string ?

    Ans:

    The line break can be removed from string by using str_replace() function. The str_replace() function is an inbuilt function in PHP which is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.

    98.How to remove extension from string ?

    Ans:

    There are three ways of removing an extension from the string. They are as follows

    • Using an inbuilt function pathinfo
    • Using an inbuilt function basename
    • Using a string functions substr and strrpos

    99.How to check if the value of a variable is  alphanumeric or empty ?

    Ans:

    You can use The ctype_alnum() function to check whether it is an alphanumeric value or not and use the empty() function to check variable is empty or not.

    100.Is it possible to remove the HTML tags from data ?

    Ans:

    Yes it is possible by using the strip_tags() function. This function is an inbuilt function in PHP which is used to strips a string from HTML, and PHP tags. This function returns a string with all NULL bytes, HTML and PHP tags stripped from a given $str.

    These are some of the popular questions that are asked in PHP interviews. Always be prepared to answer all types of questions — technical skills, interpersonal, leadership or methodology. If you are someone who has recently started your career in this field, you can always get certified to understand the industry-related terminology, skills and methodologies.

    Are you looking training with Right Jobs?

    Contact Us

    Popular Courses