Showing posts with label PHP Interviews Questions. Show all posts
Showing posts with label PHP Interviews Questions. Show all posts

Wednesday 15 April 2015

PHP problem solving interview questions and answers for Fresher and Experienced

PHP problem solving interview questions and answers for Fresher and Experienced


Question: How to save image in directory from URL?
In Below code, Just update the  $savePath and$ downloadImagePath.Script is Ready.
try {    
    $downloadImagePath='http://www.aboutcity.net/images/aboutcity.png';
    $savePath = $_SERVER['DOCUMENT_ROOT'];
    $ch = curl_init($downloadImagePath);
    $fp = fopen($savePath . '/aboutcity.png', 'wb');
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    echo "Image Downloaded Successfully in ".$savePath.' Folder.';
} catch (Exception $e) {
    echo $e->getMessage();
}



Question: How to remove empty elements from array?
Below script will remove all the elements which have null values and empty data including space.
$array = array(
'key1'=>'value1',
'key2'=>'value2',
'key3'=>'value3',
'key4'=>' ',
'key5'=>' ',    
'key6'=>null,    
);
$filterArray = array_map('trim',$array);
$filterArray = array_filter($filterArray);

print_r($filterArray);//Array ( [key1] => value1 [key2] => value2 [key3] => value3 ) 



Question: How to convert object data to array?
It will convert an object to array.
$obj = new stdClass();
$obj->key1 ='Value1';
$obj->key2 ='Value3';
$obj->key3 ='Value3';
$obj->key4 ='Value4';
$array = (Array)$obj;
print_r($array);//Array ( [key1] => Value1 [key2] => Value3 [key3] => Value3 [key4] => Value4 ) 



Question: Is it possible a function with name?
Yes, that known as Anonymous functions.
Anonymous functions, also known as closures, allow the creation of functions which have no specified name.
$greet = function($name)
{
    printf("Hello %s", $name);
};
$greet('Hello');
$greet('Web Technology experts Notes');



Question: What is PHP_EOL in PHP?
End Of Line
PHP_EOL is used, when you want a add new line in cross-platform. It will work DOS/Mac/Unix issues.


Question: What are reserved constants in PHP?
http://php.net/manual/en/reserved.constants.php


Question: How to store array in Constants?
You can not store array in php constants.
Because php constant can store single string only.
BUT if you serialize an array to string then you can store it constants in constnats.
See Examples:
define ("MY_FRUITS", serialize (array ("apple", "cherry", "banana","mango")));



Question: Where to do PHP Practise online?
https://codeanywhere.net/
http://ideone.com/
http://writecodeonline.com/php/
http://codepad.org/
http://sandbox.onlinephpfunctions.com/
http://codepad.viper-7.com/
https://eval.in/


Question: How to start session, if already not started?
If session is started, session_id() will return the string else empty string.
if(session_id() == '') {
    session_start();
}



Question: Create a folder if it doesn't already exist?
file_exists is used to check directory exist OR NOT.
mkdir is used to create the new directory.
$path="/path/to/dir";
if (!file_exists($path)) {
    mkdir($path, 0755, true);
}



Question: How to convert date to timestamp in PHP?
strtotime function is used to convert the full date time into timestamp.
$timestamp = strtotime('22-09-2008');



Question: What is Difference between isset and array_key_exists?
isset: It is used to check, variable is defined OR NOT.
array_key_exists: it is used to check, an key is available in array or not.
bool array_key_exists ( mixed $key , array $array );



Question: How to return JSON from a PHP Script?
$array = array(
'key1'=>'value1',
'key2'=>'value2',
'key3'=>'value3',
'key4'=>' ',
'key5'=>' ',    
'key6'=>null,    
);
header('Content-Type: application/json');
echo json_encode($array);



Question: How to change the maximum upload file size to 60MB?
open php.ini file
//This is max file size
upload_max_filesize = 60M 

//this is form size including file size, that's why its greater 1 MB
post_max_size = 61M



Question: When to use self over $this?
Use $this to refer to the current object.
Use self to refer to the current class.

Example of use of $this
class MyClass1 {
    private $nonStaticMember = 'nonStaticMember  member Called.';        
    
    public function funcName() {
        return $this->nonStaticMember;
    }
}

$classObj = new MyClass1();
echo $classObj->funcName();//nonStaticMember  member Called.


Example of use of self
class MyClass2 {
    private static $staticMember = 'staticMember  member Called.';        
    
    public function funcName() {
        return $this::$staticMember;
    }
}

$classObj = new MyClass2();
echo $classObj->funcName(); //staticMember  member Called.





Friday 10 April 2015

PHP Interview Questions and Answers for 2 year Experience

PHP Interview Questions and Answers for 2 year Experience



Question: What is use of header() function in php?
1. Header is used to redirect from current page to another:
header("Location: newpage.php");

2. Header is used to send HTTP status code.
header("HTTP/1.0 404 Not Found");

3. Header is used to send Send a raw HTTP header
header('Content-Type: application/pdf');



Question: What type of inheritance supports by PHP?
There are following type of inheritance
Single Inheritance - Support by PHP
Multiple Inheritance - Not support
Hierarchical Inheritance - Support by PHP
Multilevel Inheritance - Support by PHP


Question: How do you call a constructor for a parent class?
parent::constructor($value);



Question: What is the difference between the functions unlink and unset?
unlink: It is used to remove the file from server.
unlink('/path/file.phtml');

unset: It is used to remove the variable.
unset($variableName);



Question: What are default session time and path?
Session Time: 1440 seconds
Session Path: /tmp folder in server


Question: What is PEAR?
PHP Extension and Application Repository (PEAR) is a framework and repository for reusable PHP components.


Question: What is MIME?
Full form of MIME is "Multi-purpose Internet Mail Extensions".
It is extension of e-mail protocol helps to exchanges the different kids of data files over the internet.
Data files may be audio, video, images, application programs and ASCII etc.


Question: How to scrape the data from website using CURL?
To scrap the data from website, Website must be public and open for scrapable.
In the blow code, Just update the CURLOPT_URL to which websites data you want to scrap.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.web-technology-experts-notes.in/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
echo $output;



Question: How to upload the file using CURL?
You can upload a file using CURL.
See following points.
1. Uploading file size must be less than allowed file by Server.
2. If file size is heady, May take more time.
3. replace "uploadFile.zip" with file which you want to upload WITH full path.
4. replace "http://localhost/test/index2" with URL where server has given functionality to upload file.
$file_name_with_full_path = realpath('uploadFile.zip');        
       $url = "http://localhost/test/index2";
       $post_data = array(
           "foo" => "bar",
           "upload" => "@".$file_name_with_full_path
       );
       try {
           $ch = curl_init();
           curl_setopt($ch, CURLOPT_URL, $url);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
           curl_setopt($ch, CURLOPT_POST, 1);
           curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
           $output = curl_exec($ch);
           curl_close($ch);
       } catch (Exception $e) {
           echo $e->getMessage();
           die;
       }



Question: Can I set the header in CURL?
Yes, you can set the header in CURL using CURLOPT_HEADER.
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); 



Question: How can i execute PHP File using Command Line?
For this, you need PHP CLI(Commnd line interface)
Just login to you command line interface.
You have to prepend the "PHP" and need to mention the full-path/relative of file
Execute the file in following way.
php E://wamp/www/project/myfile.php



Question: How can we get the current session id?
echo session_id();

You can also set the session_id using same above function.


Question: What are different type of sorting functions in PHP?
sort() - sort arrays in ascending order. asort() - sort associative arrays in ascending order, according to the value.
ksort() - sort associative arrays in ascending order, according to the key.
arsort() - sort associative arrays in descending order, according to the value.
rsort() - sort arrays in descending order.
krsort() - sort associative arrays in descending order, according to the key.
array_multisort() - sort the multi dimension array.
usort()- Sort the array using user defined function.


Question: How to save the session data into database?
To maintain the session data, we can use session_set_save_handler function.
session_set_save_handler ( 'openFunction' , 'closeFunction', 'readFunction' , 'writeFunction' , 'destroyFunction', 'gcFunction' )

In this function, we provide 6 callback functions which call automatically.
For Example
openFunction will be called automatically when session start.
closeFunction will be called automatically when session end.
readFunction will be called automatically when you read the session.
writeFunction will be called automatically when you write in the session.
destroyFunction will be called automatically when you destroy in the session.
gcFunction will be called automatically when session inactive for long time.







Question: What are different type of errors?
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's initial startup.
E_CORE_WARNING: Warnings that occur during PHP's initial startup.
E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
E_USER_ERROR: User-generated error message.
E_USER_WARNING: User-generated warning message.
E_USER_NOTICE: User-generated notice message.
E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error E_ALL: Catches all errors and warnings



Tuesday 17 March 2015

What is stdClass? and How to create stdClass class?

What is stdClass class?
stdClass is Generic empty class in PHP.
OR
stdClass is universal base class in PHP.



Question: Why stdClass class is used?
stdClass is used to create anonymous objects with properties.



Question: Where it is used?
When we need to create an object without having new class. then we used stdClass class which is inbuilt in PHP.
After create object, we can add properties.



Question: How to create stdClass class?
$object=new stdClass();



Question: Can we set different variables in StdClass?
Yes, We can do both get and set.
See Example Below:
//First, create an object with use of stdClass
$object=new stdClass();

//Set new variables in $object 
$object->name='Web Technology Experts Notes';
$object->url='web-technology-experts-notes.in';

//Get the variables values
echo $object->name;
echo $object->url;



Wednesday 14 January 2015

SPDY Protocol - Improve the Speed of web page

SPDY Protocol - Improve the Speed of web page

SPDY (pronounced as speedy) is an application-layer protocol developed at Google for transporting web content.
It is not replacement of HTTP. Just modifies the way HTTP requests and responses are sent over the wire.


Why it is used?
SPDY is used to reduce the load time of web page by multiplexing and compresion.


What are problem with HTTP?
  • HTTP does not have multiplexing HTTP pipelining is susceptible to head of line blocking verbose headers Requirement to use SPDY.
  • SPDY requires the SSL/TLS (with TLS extension ALPN required).



How its works?
When request sent over SPDY, HTTP requests are processed, tokenized, simplified and compressed.
SPDY prioritizing and multiplexing the transfer of web page so that only one connection per client is required.


How it reduced the load time of website?
  • Avoid multiple request by concatenate the JS, CSS files
  • Image spriting
  • Resource inlining
  • It simplified and compress the request.



Who Use/Support the SPDY?
  • Firefox supports SPDY 2 from version 11.
  • Opera browser added support for SPDY as of version 12.10.
  • Internet Explorer 11 added support for SPDY version 3.
  • Google Chrome/Chromium
  • Amazon's Silk browser for the Kindle Fire uses the SPDY protocol to communicate
  • Facebook Makes Itself a Bit More SPDY


See Features of SPDY http://www.chromium.org/spdy/spdy-whitepaper

Monday 12 January 2015

PHP Technical Interview Questions and Answers for Fresher and Experienced

PHP Technical Interview Questions and Answers for Fresher and Experienced



Question: How to convert string to array in php?
$string="cakephp and zend";
$array =explode('and',$string);
print_r($array);


Question: How to convert array to string in php?
$array = array('cakephp','zend');
$string =implode(' and ',$array);
echo $string;


Question: How to connect mysqli with php using Object-Oriented Way?
$host = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($host, $username, $password);
//connect to server
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";


Question: How to connect mysqli with php using Procedural Way?
$host = "localhost";
$username = "root";
$password = "";
$conn = mysqli_connect($host, $username, $password);
//connect to server
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";


Question: How to connect mysqli with php using PDO?
$host = "localhost";
$username = "root";
$password = "";
 $conn = new PDO("mysql:host=$host;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";


Question: Give Curl example using post method?
$postData = array(
   "site" => "web technology experts notes",
   "dailyuser" => "1000",
   "location" => "India"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output = curl_exec($ch);
curl_close($ch);
echo $output;




Question: How to destroy one session?
unset($_SESSION['object']);


Question: How to Destroys all data registered to a session?
session_destroy();


Question: How to delete a php file from server?
$file="full_path/filename.php"
unlink($file); //make sure you have enough permission to do delete the file.


Question: How to convert string to uppercase in php?
$string="cakephp and zend";
echo strtoupper($string);


Question: How to convert string to lowercase in php?
$string="CAKEPHP AND ZEND";
echo strtolower($string);


Question: How to convert first letter of string to uppercase in php?
$string="cakephp and zend";
echo ucwords($string);


Question: Difference between array_merge and array_combine in php?
array_merge example
$array1 = array('one','two');
$array2 = array(1,2);
$result = array_merge($array1,$array2);
print_r($result);

array_combine example
$array1 = array('one','two');
$array2 = array(1,2);
$result = array_combine($array1,$array2);
print_r($result);


Question: How to convert array to json in php?
$array = array('one','two');
echo json_encode($array); //use json_decode for decode 


Question: How to serialize an array in php?
$array = array('one','two');
echo serialize($array);//use unserialize for convert serialized string to array


Question: How to get ip address in php?
$_SERVER['REMOTE_ADDR']


Question: How to count the number of elements in an array?
$array = array('cakephp','zend');
sizeof($array);
count($array);


Question: How to call constructor of parent class?
parent::constructor()


Question: What is use of var_dump?
It is used to display the data-type and values of variable. For Example.
$name='WTEN';
var_dump($name);



Question: What is final class
It is class which can not be inherited.
Following are example of final class
final class baseclass{
        public function testmethod()  {
            echo  "base class method";
        }
}


Question: How can we define constants in PHP?
define('WTEN','Web Technology Experts Notes'); //How to define constants
echo WTEN;//How to use constants




Question: How to start displaying errors in PHP application ? Add following code in PHP.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

OR
Add following code in .htacess
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag  log_errors on



Friday 9 January 2015

How to stop parsing the HTML tags?

How to stop parsing the HTML tags?

There are couples Method to avoid the parsing of HTML tags, I used following two ways.


How to use XMP Tag for avoid HTML parsing, See Example
Method No 1

<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOZoBT5-0tL8iOdoHHiqqLgQxwtOtbtLHJp2MaanGJK2BhQOSjIh1FyTgN9uYuCam5kOfUN3NixaLcT7sf46MKGEn7p1PKXJpKG79jMtCZHH4xroHX9AzlQqC97Jbu54Q8pN_H4DLHE9jL/s1600/wordpress.jpg" />

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>



How to use script Tag for avoid HTML parsing, See Example
Method No 2

<script type="text/plain">
<img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOZoBT5-0tL8iOdoHHiqqLgQxwtOtbtLHJp2MaanGJK2BhQOSjIh1FyTgN9uYuCam5kOfUN3NixaLcT7sf46MKGEn7p1PKXJpKG79jMtCZHH4xroHX9AzlQqC97Jbu54Q8pN_H4DLHE9jL/s1600/wordpress.jpg" />
<meta content='jX6W4C5R1HdrWqp91JMBxHzxqBM' name='alexaVerifyID'/>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' type='text/javascript'></script>



Monday 5 January 2015

Difference between Notice and warning and fatal error

Difference between Notice and warning and fatal error


Notice
  • A notice is an advisory message like "You probably shouldn't be doing what you're doing"
  • Execution of the script is not halted
  • Example
    echo $undefinedVariable;



Warning
  • A warning is a message like "You are doing something wrong and it is very likely to cause errors in the future, so please fix it." Execution of the script is not halted;
  • Example
    echo 1/0;



Fatal Error
  • Fatal run-time errors
  • Execution of the script is not halted
  • Example  
    require_once "notexistfile.php"

Sunday 14 December 2014

Object Oriented Programming in PHP

Object Oriented Programming in PHP

Following concept are used in Object Oriented Programming in PHP.

  1. Introduction
  2. The Basics
  3. Properties
  4. Class Constants
  5. Autoloading Classes
  6. Constructors and Destructors
  7. Visibility
  8. Object Inheritance
  9. Scope Resolution Operator (::)
  10. Static Keyword
  11. Class Abstraction
  12. Object Interfaces
  13. Traits
  14. Overloading
  15. Object Iteration
  16. Magic Methods
  17. Final Keyword
  18. Object Cloning
  19. Comparing Objects
  20. Type Hinting
  21. Late Static Bindings
  22. Objects and references
  23. Object Serialization
  24. OOP Changelog


Wednesday 10 December 2014

Htaccess RewriteRule Flags by Code Example

Htaccess RewriteRule Flags by Code Example

A RewriteRule can be modified by flag. Flags are included in square brackets at the end of the rule. We can also and multiple flags are separated by commas.

For Example:
[Flag1] //for 1 flag
[Flag1,Flag2] //for 2 flags
[Flag1,Flag2,Flag3 ] //for multiple flags

Following are most commonly htaccess flag:
1. htacces B(escape backreferences) Flag
Escape non-alphanumeric characters before applying the transformation


2. htaccess C(Chain) Flag
First htaccess Rule will be applied to next htaccess rule. Means if the rule matches, then control moves on to the next rule.


3. htaccess CO(Cookie) Flag
you can set a cookie when a particular RewriteRule matches
RewriteRule ^search/(.*)$ /search.php?term=$1[CO=variable:variableValue]
Set the variable=variableValue in cookie


4. htaccess DPI(discardpath) Flag
PATH_INFO portion of the rewritten URI to be discarded.


5. htaccess E (env) Flag
You can set the value of an environment variable. For example:
RewriteRule ^search/(.*)$ /search.php?term=$1[E=variable:variableValue]
Set the variable=variableValue in environment variable.


6. htaccess END Flag
This flag terminates not only the current round of rewrite but also prevents any subsequent rewrite from occurring in per-directory.


7. htaccess F(forbidden) Flag
This flag causes the server to return a 403 Forbidden status code to the client. For Example
RewriteRule \.exe - [F]
If anyone trying to open any file with .exe, he will get Forbidden error.



8. htaccess G(gone) Flag
This flag causes the server to return a 410 Gone status with the response code to the client. For Example
RewriteRule old_url - [G]
If old_url called, 410 gone status will be shown in the browser.



9. htaccess H(handler) Flag
This flag causes Forces the request to be handled with the specified handler. For example
RewriteRule !\. - [H=application/x-httpd-php]
Force all files without a file extension to be parsed by the php handler.



10. htaccess L(Last) Flag
This flag causes to stop processing the rule set, if the rule matches, no further rules will be processed.
RewriteRule ^(.*) /index.php?req=$1 [L]



11. htaccess N(Next) Flag
This flag causes ruleset to start over again from the top.
RewriteRule ^(.*) /index.php?req=$1 [N]


12. htaccess NC(nocase) Flag
This flag causes RewriteRule to be matched in a case-insensitive manner.
RewriteRule ^(.*) /index.php?req=$1 [NC]



13. htaccess NE(noescape) Flag
By default, special characters, such as & and ?, are converted to their hexcode equivalent. By Using NE flag prevents we can prevent this.


14. htaccess NS(nosubreq) Flag
This flag causes prevents the rule from being used on subrequests.



15. htaccess P(proxy) Flag
This flag causes the request to be handled by proxy request. For example, if you wanted all image requests to be handled by a image server
RewriteRule /(.*)\.(jpg|gif|png)$ http://images.mysite.com/$1.$2 [P]
Extension having jpg, gif, and png will be handled by images.mysite.com



16. htaccess PT(passthrough) Flag
This flag causes the result of the RewriteRule to be passed back through URL mapping.



17. htaccess QSA(qsappend) Flag
When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined.

18. htaccess S(Skip) flag
htaccess S flag is used to skip rules that you don't want to run. The syntax of the skip flag is [S=N], where N means the number of rules to skip. For Example
# Does the file exist?
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Create an if-then-else construct by skipping 3 lines if we meant to go to the "else" stanza.
RewriteRule .? - [S=3]

# IF the file exists, then:
    RewriteRule (.*\.gif) images.php?$1
    RewriteRule (.*\.html) docs.php?$1
    # Skip past the "else" stanza.
    RewriteRule .? - [S=1]
# ELSE...
    RewriteRule (.*) 404.php?file=$1
# END


19. htaccess T(type) flag
htaccess T flag cause sets the MIME type with which the resulting response will be sent. For Example
RewriteRule IMG - [T=image/jpg]


20. htaccess R(Redirect) flag
htacces R flag causes a HTTP redirect to be issued to the browser. Normally Redirect does not occur but if we use R Flag, then redirection will be happened to the browser. For Example
RewriteRule (.*\.gif) images.php?$1 [R]