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

Wednesday 3 June 2015

PHP Mysql Interview Questions and Answers for fresher and experienced

PHP Mysql Interview Questions and Answers for fresher and experienced


Question: How many ways we can retrieve the data in the result set of MySQL using PHP?
Following are different ways
$sqlQuery = mysql_query("SELECT id, name FROM users");
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    //$row have results
}

$sqlQuery = mysql_query("SELECT id, name FROM users");
while ($row = mysql_fetch_assoc($sqlQuery)) {
    //$row have results
}

$sqlQuery = mysql_query("SELECT id, name FROM users");
while ($row = mysql_fetch_object($sqlQuery)) {
   //$row have results
}



Question: How can we create a database using PHP and MySQL?
mysql_create_db('db_name');



Question: How can we repair a MySQL table?
Use any of below as per requirement:
REPAIR tablename; 
REPAIR tablename quick;
REPAIR tablename extended;



Question: How can we find the number of rows in a result set using PHP?
$sqlQuery = mysql_query("SELECT id, name FROM users");
$num = mysql_num_rows($sqlQuery);



Question: How to update auto increment value for 100000?
ALTER TABLE table_name AUTO_INCREMENT = 100000;



Question: How to get the current version number of MYSQL?
SELECT VERSION();



Question: What is difference between between NOW() and CURRENT_DATE()?
Now gives the current date, hour and minutes
select NOW()
//2015-06-03 19:17:23  



CURRENT_DATE gives the current date only.
select CURRENT_DATE()
//2015-06-03

Question: List all databases?
SHOW DATABASES



Question: What is mysql query to show the first 100 records?
SELECT * FROM user LIMIT 0,100


Question: How many TRIGGERS allows per table in mysql?
Following are 6 triggers in mysql for table.
1. BEFORE INSERT,
2. AFTER INSERT,
3. BEFORE UPDATE,
4. AFTER UPDATE,
5. BEFORE DELETE
6. AFTER DELETE



Question: What is difference between COMMIT and ROLLBACK?
COMMIT: Mostly it is used in transaction and commit means all process are completed successfully. Once commit done you can not revert.
ROLLBACK: Mostly it is used in transaction and ROLLBACK means all process are NOT completed successfully. So revert the db changes automatically.


Question: What is SAVEPOINT?
The SAVEPOINT statement is used to set a savepoint with a name in transaction. used for roll back the transaction to the named savepoint specified instead of all the changes.


Question: How to find the number of days between two dates?
$now = time(); // or your date as well
$newDate = strtotime("2010-01-01");
$datediff = $now - $$newDate;
echo floor($datediff/(60*60*24));


Question: How to find the number of hours between two dates?
$now = time(); // or your date as well
$newDate = strtotime("2010-01-01");
$datediff = $now - $$newDate;
echo floor($datediff/(60*60));


Question: How to find the number of minutes between two dates?

$now = time(); // or your date as well
$newDate = strtotime("2010-01-01");
$datediff = $now - $$newDate;
echo floor($datediff/(60));


Question: How do I get random item from an array?

$array = array('','s','d');
echo $array[array_rand($array)];


Question: How to update the max_allowed_packet mysql variable?
You can check the value of max_allowed_packet with following query.
SHOW VARIABLES LIKE 'max_allowed_packet'; 

For Update, You have to change in configuration mysql.
File Location in My Wamp Server: D:\wamp\bin\mysql\mysql5.6.17\my.ini
Now search with max_allowed_packet and update, as per requirement.


Question: List all the tables whose engine is InnoDB?
SELECT table_name FROM INFORMATION_SCHEMA.TABLES  WHERE ENGINE = 'InnoDB'




Question: How to update the column where NULL value set?
update `users` set phone='000000000' where  phone is NULL





Friday 22 May 2015

PHP interview questions and answers for 5 year experienced

PHP interview questions and answers for 5 year experienced


Question: How array_walk function works in PHP?
Purpose: It is used to update the elements/index of original array.
How: in array_walk, two parameter are required.
1st: original array
2nd: An callback function, with use of we update the array.



Question: Difference Between Zend framework 2 VS Zend framework 1?
http://www.web-technology-experts-notes.in/2014/03/zend-framework-2-vs-zend-framework-1.html


Question: How to achieve Multilevel inheritance in PHP?
//base class
class grandParent{}

//parent class extend the base class
class parent extends grandParent{}

//chid class extend the parent class
class child extends parent{}



Question: What is Routing? How it works in Zend?
Routing is the process of taking a URI endpoint and decomposing it into parameters to determine which module, controller and action to that controller should receive the request.
This values of the module, controller, action and parameters are packaged into a Zend_Controller_Request_Http object which is then processed by Zend_Controller_Dispatcher_Standard.




Question: What is Zend_Controller_Front?
Front Controller is design pattern.
Zend framework use the Zend_Controller_Front which is based on Front controller design pattern. Zend_Controller_Front purpose is to initialize the request environment, route the incoming request and then dispatch any discovered actions.
It aggregates any responses and returns them when the process is complete.


Question: What is difference between TDD and BDD?
TDD is Test-driven development
BDD is Behaviour-driven development



Question: What is Zend_Translate? Where it is used?
It is component of Zend Framework. Responsible for converting the text data from one language to another languages.
It is used in multilingual website where we are showing content display in multilingual.


Question: What are different Adapter of zend_translate?
Following are main Adapter of zend translator
Zend_Translate_Adapter_Array
Zend_Translate_Adapter_Csv
Zend_Translate_Adapter_Gettext
Zend_Translate_Adapter_Ini
Zend_Translate_Adapter_Tbx
Zend_Translate_Adapter_Tmx
Zend_Translate_Adapter_Qt
Zend_Translate_Adapter_Xliff
Zend_Translate_Adapter_XmlTm


Question: How to get 2nd highest salary of employee, if two employee may have same salary?
select salary from employee group by salary order by salary limit 1,1



Question:How to find duplicate email records in users table?
SELECT u1.first_name, u1.last_name, u1.email FROM users as u1
INNER JOIN (
    SELECT email FROM users GROUP BY email HAVING count(id) > 1
    ) u2 ON u1.email = u2.email;



Question: How to pass data in header while using CURL?
$url='http://www.web-technology-experts-notes.in';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'headerKey: HeaderValue ',
  'Content-Type: application/json',
  "HTTP_X_FORWARDED_FOR: xxx.xxx.x.xx"
));
echo curl_exec($ch);
curl_close($ch);



Question: How to pass JSON Data in CURL?
$url='http://www.web-technology-experts-notes.in';
$jsonData='{"name":"Web Technology Experts","email":"contact@web-technology-experts-notes.in"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_close($ch);



Question: What is Final Keyword in PHP?
PHP introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final keyword.


Question: What are Properties of Object Oriented Systems?
Inheritance
Encapsulation of data
Extensibility of existing data types and classes
Support for complex data types
Aggregation
Association



Question: How can we prevent SQL-injection in PHP? Sanitize the user data before Storing in database.
While displaying the data in browser Convert all applicable characters to HTML entities using htmlentities functions.



Question: How to redirect https to http URL and vice versa in .htaccess?
Redirect https to http
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Redirect http to https
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]



Question: What are benefits of htaccess?
We can do following benefits stuff with htaccess.
Routing the URL
Mange Error Pages for Better SEO
Redirection pages
Detect OS (like Mobile/Laptop/Ios/Android etc)
Set PHP Config variable
Set Environment variable
Allow/Deny visitors by IP Address
Password protection for File/Directory
Optimize Performance of website
Improve Site Security

Question: What is Reference Transaction in Paypal?
In Reference transaction,
With use of first transaction done by customer, we can do mutiple transaction without need another approvel.
In this, we store the transaction_id(First transaction), and use this transaction_id as reference_id for net payments.

It has two methods.
1) DoDirect payment. (Accept the credit card by website)
2) Express Checkout. (website doesn't accept credit card in own website, customer pay on paypal.com)
Click to Know More



Question: What is the validate a credit card format in PHP?
MASTERCARD Prefix=51-55, Length=16
VISA Prefix=4, Length=13 or 16
AMEX Prefix=34 or 37, Length=15
Diners Club/Carte Prefix=300-305, 36 or 38, Length=14
Discover Prefix=6011,622126-622925,644-649,65, Length=16

PHP Function to validate
function validateCreditCardFormat($number) {
    //Only number will accept 
    $number = preg_replace('/\D/', '', $number);

    // Set the string length and parity
    $number_length = strlen($number);
    $parity = $number_length % 2;

    // Loop through each digit and do the maths
    $total = 0;
    for ($i = 0; $i < $number_length; $i++) {
        $digit = $number[$i];        
        if ($i % 2 == $parity) {
            $digit*=2;            
            if ($digit > 9) {
                $digit-=9;
            }
        }
        
        $total+=$digit;
    }
    if($total%10==0){
        return true;
    }else{
        return false;
    }    
}
var_dump(validateCreditCardFormat('5105105105105100')); //true
var_dump(validateCreditCardFormat('4111111111111111'));//true
var_dump(validateCreditCardFormat('4012888888881881'));//true
var_dump(validateCreditCardFormat('40128888'));//false



Question: Difference between Apache and Nginx?
Nginx is based on event-driven architecture.
Apache is based on process-driven architecture.

Nginx development started only in 2002.
Apache initial release was in 1995.

Nginx doesn't create a new process for a new request.
Apache creates a new process for each request.

In Nginx, memory consumption is very low for serving static pages.
Apache’s nature of creating new process for each request, that's why it  increases the memory consumption.

Nginx is extremely fast for serving static pages as compare to Apache.

In complex configurations apache can be configured easily as compare to Nginx.

Apache has excellent documentation as compare to Nginx.

Nginx does not support Operating Systems like OpenVMS and IBMi where as Apache supports much wider range of Operating Systems.

The performance and scalability of Nginx is not completely dependent on hardware resources.
The Performance and scalability of the Apache is dependent on underlying hardware resources like memory and CPU.


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.





Monday 11 May 2015

PHP Frequently asked Questions and Answer 2015

PHP Frequently asked Auestions and Answer 2015



Question: What is PHP?
PHP is a server-side scripting language which is used to create the dynamic web pages.


Question: Who is fater of PHP?
Rasmus Lerdorf


Question: Which language is used to Implementation?
C/C++


Question: What is offical website of PHP?
http://php.net/


Question: What is current statable version of PHP?
Version: 7.0.6 Dated April 29, 2016.


Question: What is extensions of PHP File?
.php, .phtml, .php4, .php3, .php5, .phps


Question: Describe how PHP Works with Browser?
Works in following Flow
1. Open website http://www.web-technology-experts-notes.in/
2. Request send to server of http://www.web-technology-experts-notes.in/
3. Call PHP Files.
4. PHP Scripts are loaded into memory and compiled into Zend opcode.
5. These opcodes are executed and the HTML generated.
6. Same HTML is send back to Browser.

Know more: http://www.web-technology-experts-notes.in/2012/07/what-is-zend-engine-in-php.html


Question: What are important things about php functions?
PHP function start with "function function-name()".
PHP Function name must be start with character and it accept alphanumeric and _.
In build functions are case in-sensitive.
User build functions are case sensitive.
We can pass upto 64 parameter as argument.
Anonymous function are user defined function which have "no-name" and also called closures.
PHP support variable functions. Means when you can call a function using variable.
In same file OR under same class, same function name can't be created.


Question: What is role of htmlentities?
htmlentities is used to convert all applicable characters to HTML entities.
It is used to stop the user from running malicious code in HTML.
With use of htmlentities, user can't run the html tags like h2, p, script etc. It helps to prevent you from XSS attack.
echo htmlentities($userData);



Question: How to use email with PHP?
Email functionality is inbuilt with PHP.
PHP provide mail() with use of this, we can sen an email to user or subscriber.
We can send html/text email.
We can send attachment with email.
We can also use option like cc, bc and bcc.
We can also set the values in header.
We can also use third party API like (gmail, yahoo etc) to send email.


Question: How session and cookie works together?
Create an session in PHP.
Session data is stored in Server.
Session data have unique name.
Session unique key with domain name is stored in browser cookie.
Now, Browser keep the login with use of unique key(in cookie) and session data (stored in server side).


Question: What is the difference between the functions unlink and unset?
unlink: delete the files from Server.
unset: delete the variable name and data from memory.


Question: How to create subdomain?
With use virtual host and htaccess, you can create sub domain.


Question: What are the various methods to pass data from one web page to another web page?
Session
Cookie
Database
URL parameters



Question: What are super global variables?
$_COOKIE – Stored information in Cookie.
$_GET – Send data in URL as paramter.
$_POST – Send data to server OR Page as POST Method.
$_REQUEST – Its combined array containing values from the $_GET, $_POST and $_COOKIES.
$_ENV – Get/Set varaible in environment.
$_FILES – Used to upload the file, image and videos etc.
$_SERVER – It have all server information.
$GLOBALS – Contains all the global variables associated with the current script.


Question: How to get a user's IP address of client.
echo $_SESSION['REMOTE_ADDR'];


Question: What type of inheritance supported by PHP?
Single inheritance.
Multiple Level inheritance.


Question: What is CMS?
CMS means Content Management System. It is web software who provide the website full fledged content management where owner can add/update/delete the html/files/images/videos etc. Today's CMS do much more as compare to its name.
For example. Joomla/Wordpress is CMS but you can create E-commererce website and can accpet all types of payment.
In Today's CMS, you can create many different types of website like Ecommerce website, Personal blogging and Forum etc.


Question: How to create unique random password?
echo md5(uniqid(rand(), true));


Question: What is the difference between echo and print?
echo constructor which is used to display the value in browser.
print is function which is used to display and return the value.


Question: What is the difference between characters \023 and \x23?
\023 is octal 23.
\x23 is hex 23.





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