PHP Interview Questions and Answers for 1 Year Experience

PHP developers are still in high demand for web application development. And there are more and more high-end enterprise-level websites getting created using PHP. Hence, we are adding 15 more PHP Interview Questions and Answers for 1 Year Experience web developers. In our last post, you might have seen that we’d published the 30 PHP questions for beginners.

PHP Interview Questions and Answers for 1 Year Experience



PHP Interview Questions for 1 Year Experience 


All of you might be aware of the fact that the Web development market is growing like anything. And especially the web programmers are the primary beneficiary of this growth. Hence, most of them tend to learn technologies like PHP, HTML/CSS, JavaScript, AngularJS, and NodeJS. To turn them into better programmers, we’d started this series of web developer PHP Interview Questions and Answers for 1 Year Experience.

PHP Interview Questions and Answers for 1 Year Experience PDF Free Download

Q-1. What is the difference between unlink and unset function in PHP?

Answer.
<unlink()> function is useful for file system handling. We use this function when we want to delete the files (physically).

Sample code:

<?php
$xx = fopen('sample.html', 'a');
fwrite($xx, '<h1>Hello !!</h1>');
fclose($xx);

unlink('sample.html');
?>
unset() function performs variable management. It makes a variable undefined. Or we can say that unset() changes the value of a given variable to null. Thus, in PHP if a user wants to destroy a variable, it uses unset(). It can remove a single variable, multiple variables, or an element from an array.

Sample code:

<?php
$val = 200;
echo $val; //Out put will be 200
$val1 = unset($val);
echo $val1; //Output will be null
?>
<?php
unset($val);  // remove a single variable
unset($sample_array&#91;'element'&#93;); //remove a single element in an array
unset($val1, $val2, $val3); // remove multiple variables
?>

Q-2. Explain PHP Traits?

Answer.

It is a mechanism that allows us to do code reusability in a single inheritance language, such as PHP. Its structure is almost the same as that of a PHP class, just that it is a group of reusable functions. Despite having the same name and definition, they appear in several classes, each one having a separate declaration leading to code duplicity. We can group these functions and create PHP Traits. The class can use this Trait to include the functionality of the functions defined in it.

Let’s take an example, where we create a Message class.

class Message
{
}
Let say there exists a class Welcome.

class Welcome
{
    public function welcome()
    {
        echo "Welcome","\n"
    }
}
To include its functionality in Message class, we can extend it as.

class Message extends Welcome
{
}

$obj = new Message;
$obj->welcome();
Let’s say there exists another class named Goodmorning.

class Goodmorning
{
    public function goodmorning()
    {
        echo "Good Morning","\n";
    }
}
We cannot include the functionality of the Goodmorning class in Message class, as PHP does not support Multiple Inheritance. Here, PHP Traits comes into the picture. Let’s see how Traits resolve the issue of Multiple Inheritance for Message class.

Example.
trait Goodmorning
{
    public function goodmorning()
    {
        echo "Good Morning","\n";
    }    
}

trait Welcome
{
    public function welcome()
    {
        echo "Welcome","\n";
    }
}    

class Message
{
    use Welcome, Goodmorning;
    public function sendMessage()
    {
        echo 'I said Welcome',"\n";
        echo $this->welcome(),"\n";

        echo 'and you said Good Morning',"\n";
        echo $this->goodmorning();
   }
}

$o = new Message;
$o->sendMessage();
It produces the following output.
I said Welcome
Welcome
and you said Good Morning
Good Morning

Q-3. How can we display the correct URL of the current webpage?

Answer.

<?php
echo $_SERVER['PHP_SELF'];
?>

Q-4. Why we use extract() in PHP?

Answer.

The extract() function imports variables into the local symbol table from an array. It uses variable names as array keys and variable values as array values. For each element of an array, it creates a variable in the current symbol table.

Following is the syntax.

extract(array,extract_rules,prefix)
Let’s see an example.

<?php
$varArray = array("course1" => "PHP", "course2"  => "JAVA","course3" => "HTML");
extract($varArray);
echo "$course1, $course2, $course3";
?>

Q-5. What is the default timeout for any PHP session?

Answer.

The default session timeout happens in 24 minutes (1440 seconds). However, we can change this value by setting the variable <session.gc_maxlifetime()> in [php.ini] file.

Q-6. 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
spl_autoload_register(function ($classname) {
    include  $classname . '.php';
});
$object  = new Class1();
$object2 = new Class2(); 
?>
In the above example, we do not need to include Class1.php and Class2.php. The spl_autoload_register() function will automatically load Class1.php and Class2.php.


Q-7. What are different ways to get the extension of a file in PHP?

Answer.

There are following two ways to retrieve the file extension.

1.  $filename = $_FILES[‘image’][‘name’];

$ext           =  pathinfo($filename, PATHINFO_EXTENSION);

2. $filename = $_FILES[‘image’][‘name’];

$array         = explode(‘.’, $filename);

$ext             = end($array);


Q-8. What is PDO in PHP?

Answer.

PDO stands for <PHP Data Object>.

It is a set of PHP extensions that provide a core PDO class and database, specific drivers.
It provides a vendor-neutral, lightweight, data-access abstraction layer. Thus, no matter what database we use, the function to issue queries and fetch data will be the same.
It focuses on data access abstraction rather than database abstraction.
PDO requires the new object-oriented features in the core of PHP 5. Therefore, it will not run with earlier versions of PHP.
PDO divides into two components.

The core provides the interface.
Drivers to access a particular driver.

Q-9. What does the presence of the operator ‘::’ represent?

Answer.

It gets used to access the static methods that do not require initializing an object.

Q-10. How to get the information about the uploaded file in the receiving Script?

Answer.

Once the Web server receives the uploaded file, it calls the PHP script specified in the form action attribute to process it.

This receiving PHP script can get the information of the uploaded file using the predefined array called $_FILES. PHP arranges this information in $_FILES as a two-dimensional array. We can retrieve it as follows.

$_FILES[$fieldName][‘name’] – It represents the file name on the browser system.
$_FILES[$fieldName][‘type’] – It indicates the file type determined by the browser.
$_FILES[$fieldName][‘size’] – It represents the size of the file in bytes.
$_FILES[$fieldName][‘tmp_name’] – It gives the temporary filename with which the uploaded file got stored on the server.
$_FILES[$fieldName][‘error’] – It returns the error code associated with this file upload.
The $fieldName is the name used in the <input type=”file” name=”<?php echo $fieldName; ?>”>.


Q-11. What is the difference between Split and Explode functions for String manipulation in PHP?

Answer.

Both of them perform the task of splitting a String. However, the method they use is different.

The split() function splits the String into an array using a regular expression and returns an array.

For Example.

split(:May:June:July);
Returns an array that contains May, June, July.

The explode() function splits the String using a String delimiter.

For Example.

explode(and May and June and July);
Also returns an array that contains May, June, July.


Q-12. What is the use of ini_set() in PHP?

Answer.

PHP allows the user to modify some of its settings mentioned in <php.ini> using ini_set(). This function requires two string arguments. The first one is the name of the setting to be modified and the second one is the new value to be assigned to it.

The given lines of code will enable the display_error setting for the script if it’s disabled.

ini_set('display_errors', '1');
We need to put the above statement, at the top of the script so that, the setting remains enabled till the end. Also, the values set via ini_set() are applicable, only to the current script. Thereafter, PHP will start using the original values from php.ini.

Before changing any settings via ini_set(), it’s necessary to determine that PHP allows modifying it or not. We can only change the settings that get listed as ‘PHP_INI_USER’ or ‘PHP_INI_ALL’ in the ‘Changeable’ column of PHP manual [http://www.php.net/manual/en/ini.list.php].

Let’s see an example where we are modifying the SQL connection timeout using ini_set() function and later on verify the configured value by using ini_get() function.

echo ini_get('mysql.connect_timeout');  // OUTPUT 60

ini_set('mysql.connect_timeout',100);

echo "<br>";

echo ini_get('mysql.connect_timeout');  // output 100

Q-13. How to change the file permissions in PHP?

Answer.

Permissions in PHP are very similar to UNIX. Each file has the following three types of permissions.

Read,
Write and
Execute.
PHP uses the <chmod()> function to change the permissions of a specific file. It returns TRUE on success and FALSE on failure.

Following is the Syntax.

chmod(file,mode)

- file 

Mandatory parameter. It indicates the name of the file to set the permissions.

- mode

Mandatory parameter. Specifies the new permissions. The mode parameter consists of four numbers.
File
Mandatory parameter. It indicates the name of the file to set the permissions.
Mode
Mandatory parameter. Specifies the new permissions. The mode parameter consists of four numbers.
The first number is always zero.
The second number specifies the permissions for the owner.
The third number specifies the permissions for the owner’s user group.
The fourth number specifies the permissions for everybody else.
Possible values are (add up the numbers to set multiple permissions)

1 = execute permissions
2 = write permissions
4 = read permissions
For Example.

To set read and write permission for the owner and read for everybody else, we use.

chmod("test.txt",0644);

Q-14. What is the use of urlencode() and urldecode() in PHP?

Answer.

The use of urlencode() is to encode a string before using it in a query part of a URL. It encodes the same way as posted data from a web page is encoded. It returns the encoded string.

Following is the Syntax.

urlencode (string $str )
It is a convenient way for passing variables to the next page.

The use of urldecode() function is to decode the encoded string. It decodes any %## encoding in the given string (inserted by urlencode.)

Following is the Syntax.

urldecode (string $str )

Q-15. Which PHP Extension helps to debug the code?

Answer.

The name of that Extension is Xdebug. It uses the DBGp debugging protocol for debugging. It is highly configurable and adaptable to a variety of situations.

Xdebug provides the following details in the debug information.

Stack and function trace in the error messages.
Full parameter display for user-defined functions.
It displays function name, file name, and line indications where the error occurs.
Support for member functions.
Memory allocation
Protection for infinite recursions
Xdebug also provides.

Profiling information for PHP scripts.
Code coverage analysis.
Capabilities to debug your scripts interactively with a front-end debugger.
Xdebug is also available via PECL.