Home | About | Web Stories | View All Posts

5 Jul 2022

PHP interview questions

PHP is the most popular server side programming language due to Open source availability, wide online community and php based free development tools or technology like Wordpress etc. Job scopes are also comparatively wide in php. To handle interview easily one should know basic and advance use and aspect of php.

Following interview questions have been prepared to help job seeker to face interview easily.
  1. What is PHP?
  2. How one can include a file at PHP page?
  3. What is difference between include() and require()?
  4. Which type of file path will you use in include() or require()- absolute path or dynamic path and why?
  5. What do you know about PHP error types – Fatal error, Warning, Notice?
  6. What do you know about error_reporting() function?
  7. How to use form variable direct at script page irrespective of on/off register_globals setting?
  8. How to change a variable outside of the function?
  9. Write simple file upload script?
  10. How to pass form variable into popup window in PHP?
  11. What is Ternary Operator?
  12. What is difference between serialize() and unserialize() function?
  13. How to suppress "Header already sent" error?
  14. How to suppress "mysqli_fetch_object() expects parameter 1 to be mysqli_result boolean given in" error?

  1. What is PHP?
    PHP stands for Hypertext Preprocessor. It is a programming language devised by Rasmus Lerdorf in 1994 for building dynamic and interactive Web sites.
  2. How one can include a file at PHP page?
    Using "include(‘filepath’) " or "require(‘filepath’)" function one can include a file at PHP page.
  3. What is difference between include() and require()?
    Both are identical and produce error on failure.
    Include only emits a warning (E_WARNING) which allows the script to continue.
    Require will also produce a fatal E_COMPILE_ERROR level error and halt the script to continue.
  4. Which type of file path will you use in include() or require()- absolute path or dynamic path and why?
    Dynamic path option -
    <?php
    define('__ROOT__', dirname(dirname(__FILE__)));
    require_once(__ROOT__.'/config.php');
    ?>
    Absolute path option -
    <?php require_once('/var/www/public_html/config.php'); ?>
    Dynamic path option is applicable because it uses independent of server path environment.
  5. What do you know about PHP error types – Fatal error, Warning, Notice?
    Fatal Error: Completely shuts down script processing.
    Warning: Script will go on processing even on error condition.
    Notices: Shows advisory message that should follow in the script.
  6. What do you know about error_reporting() function?
    It produces which errors are reported on script processing and uses syntax as error_reporting(report_level)
    For example:
    <?php
    //Disable error reporting
    error_reporting(0);
    //Report runtime errors
    error_reporting(E_ERROR | E_WARNING | E_PARSE);
    //Report all errors
    error_reporting(E_ALL);
    ?>
  7. How to use form variable direct at script page irrespective of on/off register_globals setting?
    As we know register_globals is set to off by default in php.ini due to security reason. So we cannot use form variable(like $name, $email, $message etc. for input boxes having name as ‘name’, ‘email’, ‘message’) directly at script page.
    Generally we use form variables as like below –
    $name = $_POST[‘name’], $email =$_POST[‘email’], $message = $_POST[‘message’]
    It is good, if you are using a few number of form element.
    We can use form variable directly at page as like below technique –
    foreach($_POST as $key => $value){
    echo $$key = $value;
    }
    Now you form posted variable $_POST[‘name’] is accessible as $name. Thus we can use $_POST[‘name’] as $name regardless of the register_globals setting in php.ini. Thus you can cheat php.ini using above loop code for register_globals setting.
  8. How to change a variable outside of the function?
    Variable value can be changed outside of the function using 'passing value by reference' technique(using '&' symbol as prefix in function argument).
    For example -
    function customFunction(&$customVariable)
    {
    $customVariable = 100;
    }
    $customValue = 0;
    customFunction($customValue);
    print($customValue);

    Output -
    100

    Due to passing value via reference parameter we get '100' instead of '0' as output. Just remove '&' and see what happen. Output value will be '0' instead of '100'.

    Here is real world example -
    function bonus($totalsales, &$salary){
    $bonus = $totalsales * 0.5;
    $salary = $salary + $bonus;
    return $salary;
    }
    $totalsales = 4000;
    $salary = 10000;
    bonus($totalsales,$salary);
    echo "Your Total Salary:" .$salary;

    Output -
    Your Total Salary: 1200

    In the above example, you don't need to set any variable to the value resulting from calling the bonus() function. You set $salary to 10000 then pass it by reference into the bonus() function and when the function is executed, it passes the value directly back into the $salary variable by reference.
  9. Write simple file upload script?
    Following script gets parameter from superglobal variable $_FILES and shift upload file at custom localtion :
    //index.html, contains upload form
    <html>
    <body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file"><br>
    <input type="submit" name="submit" value="Submit">
    </form>
    </body>
    </html>

    //upload.php, contains upload script
    <?php
    move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
    echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    ?>
  10. How to pass form variable into popup window in PHP?
    Form variable is passed to popup window page by collecting post variable. Below a sample code has been written for this. There is a form for searching mobile number via database, in this small code snippets.

    Take a precaution to use "target" attribute in form tag. The target attribute value must match with second parameter of "window.open" pop up function. Otherwise form variable will not rendered at popup page.
    <script type="text/javascript">
    function resultbox(){
    if(document.searchform.q.value=="Search Name or Mobile Number")
    {
    alert("Please enter search term - Number or Name.");
    document.searchform.q.focus();
    return false;
    }else {
    var w = 795;
    var h = 495;
    var left = (screen.width/2)-(w/2);
    var top = (screen.height/2)-(h/2);
    resultWindow=window.open('results.php?q=<?php echo $_REQUEST['q']; ?>','resultbox','width='+w+',height='+h+',top='+top+', left='+left);
    resultWindow.focus();
    document.searchform.submit();
    }// else
    }// end of function resultbox();
    </script>
    <p class="addnumberlink">
    <a href="addnumber.php">Add Number</a></p>
    <form action="results.php" method="get" name="searchform" target="resultbox" onSubmit="return resultbox(this);" >
    <input type="text" class="searchbox" name="q" onblur="if (this.value == &quot;&quot;) {this.value = &quot;Search Name or Mobile Number&quot;;}" onfocus="if (this.value == &quot;Search Name or Mobile Number&quot;) {this.value = &quot;&quot;;}" value="Search Name or Mobile Number" />
    <input type="submit" name="submit" value="Search" class="search_btn" />
    </form>
  11. What is Ternary Operator?
    The ternary operator(?:) is used for conditional or comparison operations. It is called the ternary operator because it takes three operands - a condition, a result for true, and a result for false. General syntax is used as below :
    [expression]?[execute if TRUE]:[execute if FALSE];
    The ternary operator work in a very simple way and can be compared to a IF-ELSE structure. For example -
    Ternary Operator Format (uses only one line) -
    is_numeric($searchterm) ? $tablename = 'number' : $tablename = 'person';

    IF-ELSE Format (uses five lines)-
    if(is_numeric($searchterm)){
    $tablename = 'number';
    }else{
    $tablename = 'person';
    }
  12. What is difference between serialize() and unserialize() function?
    The function serialize() is used to convert storable form(in file, memory buffer, transmission packet) of a value in sequence of bits.

    The function unserialize() is just opposite of serialize() function. It converts storable form of a data into a value in different element like array, float, integer, string or boolean type.
    <?php
    $subject = array('Math', 'Economics', 'Science');
    $serializeData = serialize($subject);
    $unserializeData = unserialize($serializeData);
    echo $serializeData;
    echo "<br />";
    var_dump($unserializeData);
    ?>

    OUTPUT -
    a:3:{i:0;s:4:"Math";i:1;s:9:"Economics";i:2;s:7:"Science";}
    array(3) { [0]=> string(4) "Math" [1]=> string(9) "Economics" [2]=> string(7) "Science" }
  13. How to suppress "Header already sent" error?
    Every developer face the header sent error while working with PHP session and cookies. This error occur if someone try to set them after HTML code sent to the server.

    We can avoid(cheating the system) the header error by using the output buffer suppression. It can be done by placing the code block between ob_start() and ob_end_flush() function as example below -
    ob_start();
    include('top.php');//performs a mysql query to determine which page the user is supposed to view
    if($logged_status){
    $udf->udf_redirect('addnumber.php');//custom header redirect function.
    }
    ob_end_flush();
  14. How to suppress "mysqli_fetch_object() expects parameter 1 to be mysqli_result boolean given in" error?
    You need to check and verify the database connectivity for avoiding this error using "mysql_error()" function. This error also comes as - "mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given". The code sample has been written below as solution using mysqli_error() function -
    $con = mysqli_connect($hostname, $username, $password);
    mysqli_select_db($con, $database);
    $sql = "select * from employeesdetail order by 'firstname'";
    $result = mysqli_query($con, $sql);
    if (!$result) {
    die(mysqli_error($con));
    }

Best Books for Web Development in PHP


1

Programming PHP : Creating Dynamic Web Pages

Programming PHP : Creating Dynamic Web Pages

Book Description

It's the new and updated version of this book - Fourth Edition - that teaches you everything you need to know to build effective web applications using the latest features in PHP 7.4.

The book explains language syntax, programming techniques, and other details using examples that illustrate both correct usage and common idioms.

For those with a working knowledge of HTML, the book contains many style tips and practical programming advice in a clear and concise manner to help you become a top PHP programmer.

The book teaches about fundamentals of the language including data types, variables, operators and flow control statements. It explores about functions, strings, arrays and objects.

It teaches to apply common web application techniques, such as form processing, data validation, session tracking, and cookies.

It teaches to interact with relational databases such as MySQL or NoSQL databases such as MongoDB. It also teaches to generate dynamic images, creating PDF files, and parsing XML files.

You can learn about secure scripts, error handling, performance tuning and other advanced topics in this book.

You can get a quick reference to PHP core functions and standard extensions in this book.

Book details

Format: Kindle Edition, Paperback
Rating: 4.6 out of 5
Author: Kevin Tatroe, Peter Macintyre
Print Length: 540 pages
Publication Date: 27 March 2020
Publisher: O′Reilly, 4th edition
Kindle Price: Rs. 1,567.50*
Paperback Price: Rs. 3,614.00*
*Price and stock are correct and available at the time of article publication.

Get it here from Amazon


2

PHP Web Development with Laminas

PHP Web Development with Laminas

Book Description

This book teaches how to build fully secure and functional e-commerce applications with PHP using the next generation Zend Framework-Laminas. You can learn to develop modern object-oriented applications with PHP by using Test-Driven Development (TDD) and Behavior-Driven Development (BDD) aided by mature reusable components.

This book provides a practical approach to equip you with the knowledge of the Laminas framework needed to start building web applications based on reuse of loosely coupled components.

You will learn how to build the basic structure of a PHP web application divided into layers. You can understand the MVC components of Laminas and be able to take advantage of the Eclipse platform as a method to develop with Laminas.

Books teach to explore how object-relational mapping is implemented with Laminas-DB, behavior-driven development concepts to sharpen your skills, how to build complete models and reusable components, practice testing How to Create HTML Forms With Laminas-Forms.

By the end of this web development book, you will be able to build completely secure MVC applications in PHP language using Laminas.

Book details

Format: Kindle Edition
Author: Flávio Gomes da Silva Lisboa
Text-to-Speech: Enabled
Enhanced typesetting: Not Enabled
X-Ray: Not Enabled
Word Wise: Not Enabled
Publication Date: 9 December 2022
Publisher: Packt Publishing
Kindle Price: Rs. 750.74*
*Price and stock are correct and available at the time of article publication.

Get it here from Amazon


3

Getting started with Laravel 9, master the most popular PHP framework

Getting started with Laravel 9, master the most popular PHP framework

Book Description

This book is for all those who want to build their first application in Laravel 9. This book provides a step-by-step introduction to the writing framework, gets to know its most relevant aspects and focuses above all on practice.

Using this book you will be able to build any basic application with the framework. There are total 19 chapters in this book. Using this book, you will be able to know what are the required software to install Laravel for different operating systems.

In this book you can learn - project creation, database configuration, routing, view controllers, redirection, directive and templating engines in the form of blades, model building, CRUD applications etc.

You can learn to perform common eloquent operations that can be applied to databases using query builders. You can learn how to generate test data using classes.

You can also learn the file upload process. You can learn how to use REST APIs through CRUD type applications in VU3 using Axios requests and web components with Oruga UI.

You can also learn how to configure Browsersync with Laravel to automatically reload applications. You can learn how to protect an app in Vue with the login required to access its various modules using SPA authentication or Laravel Sanctum tokens.

Book details

Format: Kindle Edition
Rating: 1 out of 5
Author: Andrés Cruz Yoris
Print Length: 453 pages
Publication Date: 8 May 2022
Text-to-Speech: Enabled
Screen Reader: Supported
Enhanced typesetting: Enabled
X-Ray: Not Enabled
Word Wise: Not Enabled
Kindle Price: Rs. 449.00*
*Price and stock are correct and available at the time of article publication.

Get it here from Amazon


4

Learning Drupal as a framework: Your guide to custom Drupal 9. Full code included

Learning Drupal as a framework: Your guide to custom Drupal 9. Full code included

Book Description

This book uses PHP> 7.4. This course teaches you about the advanced concepts of Drupal 9, object-oriented PHP and Symfony components.

After the course, you will be able to build a variety of robust and scalable software solutions.

This book discusses advanced topics such as custom entities, entity forms, access controls, events, caching, workflows, and more when building real software.

It gives you powerful and ready-to-use snippets for your next Drupal project with +2400 lines of custom code.

Book details

Format: Kindle Edition
Rating: 5 out of 5
Author: Stef Van Looveren
Print Length: 282 pages
Publication Date: 17 July 2022
Text-to-Speech: Enabled
Screen Reader: Supported
Enhanced typesetting: Enabled
X-Ray: Not Enabled
Word Wise: Not Enabled
Kindle Price: Rs. 449.00*
*Price and stock are correct and available at the time of article publication.

Get it here from Amazon


5

Getting started with CodeIgniter 4

Getting started with CodeIgniter 4

Book Description

This book is for anyone who wants to build their first applications in CodeIgniter 4 a popular PHP framework, this writing offers a step-by-step introduction to the framework, knowing the most relevant aspects of it, and is focused above all on practice.

The book is aimed at those people who want to learn something new, learn about a framework that has very little documentation, who want to improve a skill in web development, who want to grow as a developer, and who want to continue scaling their path with other frameworks superior to this one.

This book has a total of 15 chapters and consists of explanations and practices. It teaches you how to run the framework, how to configure a database, how to create the first components, how to use of migrations for table management, working with the MVC, how to prepare CRUD application, how to use the routes, grouped routes, their options, and the different types.

You can learn about the use of the session and also of the flash session to save data and present it to the user. You can learn to manage views in a reusable way. You can learn about how to work with HTML forms and apply validations from the server side in CodeIgniter. You can learn about the authentication module with the login interface, and how to build a Rest Api type CRUD that can be consumed with JSON or XML.

You can also learn about generating test data with seeders, how to handle the relational schema of the database, how to do uploading files in the application, how to use libraries and help functions, how to integrate the PayPal platform, etc.

Book details

Format: Kindle Edition
Author: Andres Cruz
Print Length: 328 pages
Publication Date: 13 May 2022
Text-to-Speech: Enabled
Screen Reader: Supported
Enhanced typesetting: Enabled
X-Ray: Not Enabled
Word Wise: Not Enabled
Kindle Price: Rs. 319.00*
*Price and stock are correct and available at the time of article publication.

Get it here from Amazon


Tags : , ,
Aashutosh Kumar Yadav

By Aashutosh Kumar Yadav

He is a PHP-based UI/Web designer and developer by profession and very interested in technical writing and blogging. He has been writing technical content for about 10 years and has proficient in practical knowledge and technical writing.
@www.infotokri.in

0 comments:

Post a Comment