Important PHP questions to help you before appearing in an interview

Author Jiwan Thapa         Posted on 31 Dec, 2018         7532 Views        

Working on a few blog sites and knowing some basics won't be enough, if you are dreaming about landing a top notch job in PHP. You show be well aware about the basics and should possess a great logical ability to deal with the challenges that you might face if you get qualified for the job.

So, here I present you with a good collection of theoritical, technical and tricky questions asked to PHP candidates on interviews around the world. Have a thorough look at them and try to get correct answers which is very important before you appear in an interview.

Before that, let's go through the facts you should know about PHP first.

Facts you should Know about PHP

PHP is a recursive acronym for PHP Hypertext Preprocessor. It is a widely used open-source programming language especially suited for creating dynamic websites and mobile API's.

  • Originally Known: Personal Home Page
  • Designed by: Rasmus Lerdorf
  • Written In: C and C++
  • Officially launched in: June 1998
  • Current Stable Version: 7.2.9

basic theoritical questions

  1. What is PHP ?
  2. What is T_PAAMAYIM_NEKUDOTAYIM (Scope Resolution Operator) ?
  3. What is session in PHP. How to remove data from a session?
  4. How to register a variable in PHP session ?
  5. What are PHP Magic Methods/Functions. List them.
  6. What is difference between include, require, include_once and require_once() ?
  7. What are constructor and destructor in PHP ?
  8. What are the data types in PHP ?
  9. Explain Type hinting in PHP ?
  10. What is purpose of @ in Php ?
  11. How can you get the length of an array in PHP ?
  12. Is multiple inheritance supported in PHP ?
  13. What are the difference between echo and print?
  14. What is namespaces in PHP?
  15. What are different types of Print Functions available in PHP?
  16. 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?
  17. What is PECL?
  18. Which Scripting Engine PHP uses?
  19. What is difference between session and cookie in PHP ?
  20. Where are sessions stored in PHP ?
    • PHP sessions are stored on server generally in text files in a temp directory of server. That file is not accessible from outside word. When we create a session PHP create a unique session id that is shared by client by creating cookie on clients browser.That session id is sent by client browser to server each time when a request is made and session is identified. The default session name is “PHPSESSID”.

  21. What are different types of errors available in Php ?
    • There are 13 types of errors in PHP which are listed 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.

      E_CORE_WARNING: Warnings that occur during PHP initial startup.

      E_COMPILE_ERROR: Fatal compile-time errors indicating 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.

  22. How to get number of arguments passed to a PHP Function?
    • func_get_args() function is used to get number of arguments passed in a PHP function.

  23. What are the encryption functions available in PHP ?
    • crypt(),Mcrypt(),hash() are used for encryption in PHP.

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

      Below are some features of mbstring

      » It handles the character encoding conversion between the possible encoding pairs.

      » Offers automatic encoding conversion between the possible encoding pairs.

      » Supports function overloading feature which enables to add multibyte awareness to regular string functions.

      » Provides multibyte specific string functions that properly detect the beginning or ending of a multibyte character.

      » For example, mb_strlen() and mb_split()

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

  26. Why should logs be stored 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.

  27. What is Pear in PHP?
    • PEAR stand for Php Extension and Application Repository.

      PEAR provides:

      » A structured library of code

      » maintain a system for distributing code and for managing code packages

      » promote a standard coding style

      » provide reusable components.

  28. What is the difference between runtime exception and compile time exception?
    • An exception that occurs at compile time is called a checked exception. This exception cannot be ignored and must be handled carefully. For example, if you use FileReader class to read data from the file and the file specified in class constructor does not exist, then a FileNotFoundException occurs and you will have to manage that exception. For the purpose, you will have to write the code in a try-catch block and handle the exception. On the other hand, an exception that occurs at runtime is called unchecked-exception. Note: Checked exception is not handled so it becomes an unchecked exception. This exception occurs at the time of execution.

  29. What are SQL Injections, how do you prevent them and what are the best practices?
    • SQL injections are a method to alter a query in a SQL statement send to the database server. That modified query then might leak information like username/password combinations and can help the intruder to further compromise the server.

      To prevent SQL injections, one should always check & escape all user input. In PHP, this is easily forgotten due to the easy access to $_GET & $_POST, and is often forgotten by inexperienced developers. But there are also many other ways that users can manipulate variables used in a SQL query through cookies or even uploaded files (filenames). The only real protection is to use prepared statements everywhere consistently.

      Do not use any of the mysql_* functions which have been deprecated since PHP 5.5 ,but rather use PDO, as it allows you to use other servers than MySQL out of the box. mysqli_* are still an option, but there is no real reason nowadays not to use PDO, ODBC or DBA to get real abstraction. Ideally you want to use Doctrine or Propel to get rid of writing SQL queries all together and use object-relational mapping which binds rows from the database to objects in the application.

  30. What is difference between strstr() and stristr() ?
    • In PHP both functions are used to find the first occurrence of substring in a string except stristr() is case-insensitive and strstr is case-sensitive, if no match is found then FALSE will be returned.

Basic Technical Questions

  1. What is default session time and path in PHP. How to change it ?
    • Default session time in PHP is 1440 seconds (24 minutes) and Default session storage path is temporary folder/tmp on server. You can change default session time by using below code.

    <?php
      ini_set('session.gc_maxlifetime', 3600);
      session_set_cookie_params(3600);
    ?>
    
  2. 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() function at the top of your php script.

          
    ini_set('max_execution_time’, 300); // 300 seconds = 5 minutes 
    
  3. Write a code to upload a file in PHP ?
    <?php
    if($_FILES['file']['name'])
    {
      //if no errors...
      if(!$_FILES['file']['error'])
      {
        //modify the file name and validate the file
        $new_file_name = strtolower($_FILES['file']['tmp_name']); //rename file 
        if($_FILES['file']['size'] > (1024000)) //constraint for max file size
        {
          $valid_file = false;
          $message = 'Oops!  Your file is too large.';
        }
        else
        {
          move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$new_file_name);
          $message = 'File uploaded successfully.';
        }
      }
      else
      {
        $message = 'Something got wrong while uploading file:  '.$_FILES['file']['error'];
      }
    }
    ?>
    
  4. Write the codes to open file download dialog in PHP ?
    <?php
    // outputting a PDF file
      header('Content-type: application/pdf');
    // Let's name it downloaded.pdf
      header('Content-Disposition: attachment; filename="downloaded.pdf"');
    // The PDF source is in original.pdf
      readfile('original.pdf');
    ?>
    
  5. How to Pass JSON Data in a URL using CURL in PHP ?
          
    <?php  
      $url='https://www.webtrickshome.com/get_data';
      $jsonData='{"name":"johnDoe","email":"mail@webtrickshome.com",'age':34}';
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
      curl_close($ch);
    ?>
    
  6. How to get number of days between two given dates using PHP ?
    <?php
      $tomorrow = mktime(0, 0, 0, date(“m”) , date(“d”)+1, date(“Y”));
      $lastmonth = mktime(0, 0, 0, date(“m”)-1, date(“d”), date(“Y”));
      echo ($tomorrow-$lastmonth)/86400;
    ?>
    

    Alternative Method

    <?Php 
      $date1 = date('Y-m-d');
      $date2 = '2015-10-2';
      $days = (strtotime($date1)-strtotime($date2))/(60*60*24);
      echo $days;
    ?>
    
  7. 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: /desired-url"); 
    exit();
    
  8. 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;
    
  9. What is GD in PHP?
    • GD is an open source library for creating dynamic images. PHP uses GD library to create PNG, JPEG and GIF images. It is also used for creating charts and graphics on the fly. GD library requires an ANSI C compiler to run.

      Sample code to generate an image in PHP

    <?php
      header("Content-type: image/png");
      $string = $_GET['text'];
      $im = imagecreatefrompng("images/button1.png");
      $mongo = imagecolorallocate($im, 220, 210, 60);
      $px = (imagesx($im) - 7.5 * strlen($string)) / 2;
      imagestring($im, 3, $px, 9, $string, $mongo);
      imagepng($im);
      imagedestroy($im);
    ?>
    
  10. How to get the IP address of the client/user in PHP?
    • You can use $_SERVER['REMOTE_ADDR'] to get IP address of user/client in PHP, But sometime it may not return the true IP address of the client at all time.

    function getTrueIpAddr(){
      if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
        {
          $ip=$_SERVER['HTTP_CLIENT_IP'];
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
        {
            $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        }
          else
        { 
          $ip=$_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
    
  11. How to create a text file in php?
    <?php 
      $filename = "/home/user/guest/newfile.txt";
      $file = fopen( $filename, "w" );
      if( $file == false )
      {
      echo ( "Error in opening new file" ); exit();
      }
      fwrite( $file, "This is a simple test\n" );
      fclose( $file );
    ?>
    

Advanced Technical Questions

  1. The output will be: yabadabadoo does not contain yaba Why? How can this code be fixed to work correctly?
    $str1 = 'yabadabadoo';
    $str2 = 'yaba';
    if (strpos($str1,$str2)) {
        echo "\" . $str1 . "\" contains \" . $str2 . "\";
    } else {
        echo "\" . $str1 . "\" does not contain \" . $str2 . "\";
    }
    
  2. What will be the output of the code below and why?
      $x = 5;
      echo $x;
      echo "<br>";
      echo $x+++$x++;
      echo "<br>";
      echo $x;
      echo "<br>";
      echo $x---$x--;
      echo "<br>";
      echo $x;
      
  3. What will be the values of $a and $b after the code below is executed? Explain your answer.
    $a = '1';
    $b = &$a;
    $b = "2$b";
    
  4. What will be the output of each of the statements below and why?
    var_dump(0123 == 123);
    var_dump('0123' == 123);
    var_dump('0123' === 123);
    
  5. What is the problem with the code below? What will it output? How can it be fixed?
    $referenceTable = array();
    $referenceTable['val1'] = array(1, 2);
    $referenceTable['val2'] = 3;
    $referenceTable['val3'] = array(4, 5);
    
    $testArray = array();
    
    $testArray = array_merge($testArray, $referenceTable['val1']);
    var_dump($testArray);
    $testArray = array_merge($testArray, $referenceTable['val2']);
    var_dump($testArray);
    $testArray = array_merge($testArray, $referenceTable['val3']);
    var_dump($testArray);
    
  6. What will this code output and why?
    $x = true and false;
    var_dump($x);
    
  7. What will $x be equal to after the statement?
    $x = 3 + "15%" + "$25"
    
  8. After the code below is executed, what will be the value of $text and what will strlen($text) return? Explain your answer.
    $text = 'John ';
    $text[10] = 'Doe';
    
  9. PHP_INT_MAX is a PHP constant that corresponds to the largest supported integer value (value is based on the version of PHP being run and the platform it is running on). Assume that var_dump(PHP_INT_MAX) will yield int(9223372036854775807). In that case, what will be the result of var_dump(PHP_INT_MAX + 1)? Also, what will be the result of var_dump((int)(PHP_INT_MAX + 1))?
  10. How would you sort an array of strings to their natural case-insensitive order, while maintaining their original index association? For example, the following array:
    array(
    	'0' => 'z1',
    	'1' => 'Z10',
    	'2' => 'z12',
    	'3' => 'Z2',
    	'4' => 'z3',
    )
    After sorting, should become:
    
    array(
    	'0' => 'z1',
    	'3' => 'Z2',
    	'4' => 'z3',
    	'1' => 'Z10',
    	'2' => 'z12',
    )
    
  11. Consider the following code:
    $x = NULL;
    
    if ('0xFF' == 255) {
        $x = (int)'0xFF';
    }
    
    What will be the value of $x after this code executes? Explain your answer.
  12. How can you tell if a number is even or odd without using any condition or loop?
  13. What does the follow code echo?
    $a = "PHP";
    $a = $a + 1;
    echo $a;
    
  14. Highlight all the Chinese characters in red and return the string.
    $str = 'drinking giving jogging 喝 喝 passing 制图 giving 跑步 吃';  
    
  15. What does the following code output?
    $i = 016;
    echo $i / 2;
    
  16. Swap the values of 2 given variables, without using a third one.
    $a = 4;
    $b = 13;
    … (your code here)
    echo $a; // 13
    echo $b; // 4
    * it should work for all data types of $a and $b
    
  17. Write a PHP function called my_strlen which will return the length of a string. Do this without using ANY PHP built-in functions (strpos(), explode(), strlen(), split() - note this includes the “syntactic sugar” null coalescing operator ? - etc.) or posting (or supressing) any PHP errors or notices.
  18. Using the function from 2 above (or otherwise), write a PHP function that will find a string inside another string and return the position where it was found. Do this without using ANY PHP built-in functions or posting (or supressing) any PHP errors or notices.
  19. Given the following function:
    function calculateHighestNumber(array $numbersArray, $numberOfSwitchesAllowed = 5)
    {
        // your code here....
        $maximumNumberObtained = implode('', $numbersArray);
        return $maximumNumberObtained;
    }
    an array of single digit numbers: $numbersArray = array(1,7,3,9,5,8);
    and a number of switches allowed ($numberOfSwitchesAllowed).
    
    Considering the fact that executing a switch means moving 2 adjacent items in the array to each other's positions (i.e. swapping them), complete the function in such a way, that by executing no more than the number of switches allowed, it will output the greatest possible number at the end.
  20. Optimise the following program:
    $a = array('bla' => 1, '2' => 0, 'test' => 'testVal', '3' => 3);
    $b = array();
    for ($i = 1; $i <= count($a); $i++) {
        $b[$i] = !empty($a[$i]) ? $a[$i] : 0;
    }
    print_r($b);
    
  21. Write an algorithm that will parse a multidimensional array with n rows and columns in a spiral starting from the centre. The n will always be an odd number. You can use any programming language to perform this task.

    Given n=5;

    For example, here we generate the multidimensional array, filling it with random numbers

    1 34 32 2 4
    3 32 13 11 89
    56 11 7 9 95
    14 90 333 23 1
    5 33 54 23 41
    Starting from the centre of the array which will be the number 7, after the execution of the program we will end up with: 7, 11, 32, 13, 11, 9, 23, 333, 90, 14, 56, 3, 1, 34, 32, 2, 4, 89, 95, 1, 41, 23, 54, 33, 5
  22. Build an API

    Task:

    • Build a web service providing information about books using dummy data.
    • It should be possible to ask that service for books by a given ISBN, author, title, between a given date range or by minimum rating.
    • We expect a good entity/model design where data entities and business logic are encapsulated.
    • We will be looking for design decisions that will allow the solution to be technology agnostic, modular, following OOP principles, for a solution that is tested against error conditions and bad returns. By technology agnostic we mean that without a major refactor it should be possible to introduce another transport layer (SOAP/XML/REST), storage layer or swap out any other of the components.
    • Your code should have functional tests as well as unit tests.
    • Feel free to use any readily available components, but remember that it's your code that will ultimately be checked.

Moreover, if you want to hire a php freelancer or apply as a php freelancer or any other software developers, designers, finance experts, product managers, and project managers in the world, you can join one of the fastest growing freelancing portal TOPTAL and get what you wanted easily. If you want to explore better ways to find a great php developer, please go through this link How to Hire a Great PHP Developer, this might prove handy.


0 Like 0 Dislike 0 Comment Share

Leave a comment