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

Wednesday 26 February 2014

Export to CSV File - PHP

Export to CSV File - PHP

CSV is a simple file format that is widely used by IT Professional, business, and all who are familar with computer. Those who use computer in day to day life, they know how to use CSV/Excel. Among its most common uses is to move tabular data between programs that naturally operate on a more efficient or complete proprietary format. This file is easily readable even in mobile with use of some basic apps.

In Web Technology fileld,  number of times we have the send Stats, Logs and detail to our client in Form of CSV files.  Event may times we got the Text in form of excel/CSV Fle.

Now, Export the PHP data into CSV is very simple. Just  you need to do few simple steps.
  1. Save into into PHP multidimensional array
  2. Set the header
  3. Now, render the rows and then render EOL (First Row)
  4. Now, render the rows and then render EOL (Second Row)
  5. Now, render the rows and then render EOL  (Third Row and so on)
 Here EOL is End of Line.

Code Snippet
$lists = array(
    array(
        'Web', 'Technology', 'Experts', 'Notes',
    ),
    array(
        'Web1', 'Technology1', 'Experts1', 'Notes1',
    ),
    array(
        'Web2', 'Technology2', 'Experts2', 'Notes2'
    ),
    array(
        'Web3', 'Technology3', 'Experts3', 'Notes3',
    ),
    array(
        'Web4', 'Technology4', 'Experts4', 'Notes4',
    ),
    array(
        'Web5', 'Technology6', 'Experts5', 'Notes5',
    )
);

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=csv.csv");
header("Pragma: no-cache");
header("Expires: 0");

//header
echo  "Title1, Title2,Title3, Title4 \n";

foreach ($lists as $list) {
    echo implode(',', $list);
    echo PHP_EOL;
}

Saturday 22 February 2014

htaccess code snippets example

htaccess code snippets example

.htaccess file is used for configuration on File Level/Directory Level and its supported by all webserver. Today all types of websites use htaccess technology.



Following are Benefits of .htaccess
  • Mange Error Pages for Better SEO
  • Set PHP Config variable
  • Set Environment variable
  • Password protection for File/Directory
  • Allow/Deny visitors by IP Address
  • Detect OS (like Mobile/Laptop/Ios/Android)
  • Redirection pages 
  • Optimize Performance of website
  • Improve Site Security


Following are Few Example of .htaccess

Redirect Home page to Another Website
Redirect / http://php-tutorial-php.blogspot.in/


Redirect Home page to Another another Directory(i.e newdir)
Redirect / /newdir


Redirect about.html to Another another Directory(i.e /pages/about)
Redirect /about.html /pages/about


Redirect old file to New Path
Redirect /oldfile.html /newfile.html


Set PHP Environment
SetEnv APPLICATION_ENV development


Set max_filesize in php
php_value upload_max_filesize 32M


Set off error in PHP
php_flag display_errors off
php_flag display_startup_errors off


Dedect mobile/laptop and redirect to mobile site
RewriteCond %{HTTP_USER_AGENT} android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|ipad|ipod|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ (ce|phone)|xda|xiino [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a\ wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r\ |s\ )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1\ u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp(\ i|ip)|hs\-c|ht(c(\-|\ |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac(\ |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt(\ |\/)|klon|kpt\ |kwc\-|kyo(c|k)|le(no|xi)|lg(\ g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-|\ |o|v)|zz)|mt(50|p1|v\ )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v\ )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-|\ )|webc|whit|wi(g\ |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-) [NC]
RewriteRule ^$ http://mobile.domain.com/ [R,L]


Block IP Address
order allow,deny
deny from xxx.xxx.xxx.xxx #specify a specific address
deny from xxx.xxx.xxx.xxx/30 #specify a subnet range
deny from xxx.xxx.* #specify an IP address wildcard
allow from all


Allow IP Address
order allow,deny
allow from xxx.xxx.xxx.xxx #specify a specific address
allow from xxx.xxx.xxx.xxx/30 #specify a subnet range
allow from xxx.xxx.* #specify an IP address wildcard
allow from all


Redirect to 400.html, If 400 error comes
ErrorDocument 400 /errorpages/400.html


Redirect to 403.html, If 403 error comes
ErrorDocument 403 /errorpages/403.html


Redirect to 404.html, If 404 error comes
ErrorDocument 404 /errorpages/404.html


Redirect to 500.html, If 500 error comes
ErrorDocument 500 /errorpages/500.html


Disable Directory Listing
Options ExecCGI Includes IncludesNOEXEC SymLinksIfOwnerMatch -Indexes


Enable Directory Listing
 Options All +Indexes


Password Protection
AuthName "Authentication Section"
AuthType Basic
AuthUserFile /home/username/.htpasswds #Here your password will be stored
#htpasswds file format username:password
Require valid-user


Password Protection but Google can Crawl
AuthName "Under Development"
AuthUserFile /home/website/.htpasswd
AuthType basic
Require valid-user
Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx w3.org htmlhelp.com googlebot.com
Satisfy Any


Set Timezone of the Server
SetEnv TZ America/Indianapolis


301 Redirect Old File
Redirect 301 /old/file.html http://php-tutorial-php.blogspot.in/2013/12/curl-example.html


301 Redirect Entire Directory
Redirect 301 /old/ /new/



301 redirect https to http
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


301 redirect https to http://www
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


301 redirect non www to www with htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]


Set Caching for javascript/image/css
ExpiresActive On
ExpiresByType application/javascript "now plus 3 day"
ExpiresByType application/x-javascript "now plus 3 day"
ExpiresByType image/jpg "now plus 1 week"
ExpiresByType image/jpeg "now plus 1 week"
ExpiresByType image/png "now plus 1 week"
ExpiresByType image/pjpeg "now plus 1 week"
ExpiresByType image/gif "now plus 1 week"
ExpiresByType text/css "now plus 3 day"


Error Codes - Defination
301 - Permanent movement(redirection)
302 - Temporary movement(redirection)
400 - Bad request
401 - Authorization Required
403 - Forbidden
404 - Page Not Found
500 - Internal Server Error


Saturday 14 December 2013

CURL Example

CURL
CURL is a library and command-line tool for transferring data using various protocols like HTTP, FTP, SCP, PUT, POST, POP3 & SMTP etc. It also used for scrapping the data from websites. We can scrap get the text as well as images with use of CURL.


It have two products libcurl and cURL.

cURL: Its command line tool for transferring information.
Libcurl: It is a free client-side URL transfer library.


CURL COMMAND-LINE EXAMPLE

Curl Example with "GET" Method (By Default GET)
curl http://www.web-technology-experts-notes.in/p/sitemap.html

Curl Example with "POST" Method
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html

Curl Example with "PUT" Method
curl --request PUT http://www.web-technology-experts-notes.in/p/sitemap.html

Curl Example with "DELETE" Method
curl --request DELETE http://www.web-technology-experts-notes.in/p/sitemap.html

Curl Example with "POST" Method and pass data (Data: username, password & logintype)
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html
--data 'username=user&password=****&logintype=normal' 

Curl Example with "POST" Method and pass data(data in text file)
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html --data @datafile.txt

Curl Example with "POST" Method, pass data and pass header
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html --data @datafile.txt --header 'sessionid:9874563211235884' 

Curl Example with "POST" Method, pass data and pass header (Get Header in response) --include
curl --request POST http://www.web-technology-experts-notes.in/p/sitemap.html --data @datafile.txt --header 'sessionid:9874563211235884' --include

CURL LIBCURL EXAMPLE

Mostly to get data from an REST API, we use following method in php
echo file_get_contents('http://www.web-technology-experts-notes.in/p/sitemap.html');
But if, "allow_url_fopen" is disable in php.ini file due to security reason then above will not work. You need to use below code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.co.in");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
echo $output;die;


CURL Example with Post Method with parameter
$url = "http://localhost/test/index2";
$post_data = array(
            "foo" => "bar",
            "foo1" => "testdata"
);
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;
}

File Upload with CURL in PHP
 $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;
        }
        
Transfer the File through FTP
curl_setopt_array($ch, array(
    CURLOPT_URL => 'ftp://ftp.example.com/test.txt',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERPWD => 'username:password'
));
 
$output = curl_exec($ch);

Set Header and Json data in Curl
$url='http://www.web-technology-experts-notes.in/';
$jsonData='{"name":"arun","email":"arun@gmail.com"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'X-API-Token: ' . X_API_TOKEN,
  'Content-Type: application/json',
  "HTTP_X_FORWARDED_FOR: xxx.xxx.x.xx"
));

curl_setopt($ch, CURLOPT_INTERFACE, "xxx.xxx.x.xx");
echo curl_exec($ch);
curl_close($ch);
Following are some Options which can be set be set in "curl_setopt" function


CURLOPT_REFERER - Set the Http Refer

CURLOPT_USERAGENT - Set the UserAgent

CURLOPT_HEADER - Include the header in response or not

CURLOPT_RETURNTRANSFER - Print the output or not

CURLOPT_URL - Set the URL (Uniform Resource Locator)

CURLOPT_POST - set 0 or 1 for post method

CURLOPT_POSTFIELDS - set the data which you want to post

CURLOPT_FOLLOWLOCATION - if set true, cURL will follow redirects

CURLOPT_CONNECTTIMEOUT -Total seconds to spend attempting to connect

CURLOPT_TIMEOUT - Total Seconds to allow cURL to execute






Zend Curl Example

$config = array(
    'adapter' => 'Zend_Http_Client_Adapter_Curl',
    'ssltransport' => 'tls',
    'strict' => false,
    'persistent' => true,
);
$url = 'http://www.example.com';
$client = new Zend_Http_Client($url, $config);
$postArray = array('name'=>'Georage','age'=>33);
$client->setParameterPost($postArray);
/** set Headers **/
$client->setHeaders(array(
    'Host: www.example.com',
    'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0',
    'Accept: text/javascript, application/javascript, */*',
    'Accept-Language: en-gb,en;q=0.5',
    'Accept-Encoding: gzip, deflate',
    'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
    'X-Requested-With: XMLHttpRequest',
    'Referer: http://example.com'
));

/** set cookie **/
$client->setCookie('__utma', '174057141.1507422797.1392357517.1392698281.1392702703.3');
$client->setCookie('__utmz', '174057141.1392357517.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)');
$client->setCookie('__atuvc', '58');
$client->setCookie('PHPSESSID', '0a12ket5d8d7otlo6uh66p658a5');
$response = $client->request('POST');

$data= $response->getBody();
echo $data; 

Zend CURL Ignore SSL_VERIFYPEER
$url='www.example.com';
$config = array(
    'adapter' => 'Zend_Http_Client_Adapter_Curl',
    'curloptions' => array(
        CURLOPT_FOLLOWLOCATION => TRUE,
        CURLOPT_SSL_VERIFYPEER => FALSE
    ),
);
 $client = new Zend_Http_Client($url, $config);
 $response = $client->request('GET');

Set CURL'S Timeout in Milli-seconds
 $ch = curl_init();
          //set the curl for crawl
          curl_setopt($ch, CURLOPT_URL, "http://www.web-technology-experts-notes.in/2014/03/captcha-code-example.html");
          //include the header in the output
          curl_setopt($ch, CURLOPT_HEADER, 0);
          //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
          curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
          //The maximum number of milliseconds to allow cURL functions to execute.
          curl_setopt($ch, CURLOPT_TIMEOUT_MS, 4000); //timeout in seconds
          $output = curl_exec($ch);
          curl_close($ch); 

Set Zend CURL'S Timeout in Milli-seconds
$config = array(
            'adapter' => 'Zend_Http_Client_Adapter_Curl',
            'curloptions' => array(
                CURLOPT_FOLLOWLOCATION => FALSE,
                CURLOPT_HEADER => false,
                //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
                CURLOPT_TIMEOUT_MS => 3000,
                //The maximum number of milliseconds to allow cURL functions to execute.
                CURLOPT_CONNECTTIMEOUT_MS => 3000
            )
        );
        $url = "http://www.web-technology-experts-notes.in/2014/03/captcha-code-example.html";
        $client = new Zend_Http_Client($url, $config);
        $response = $client->request('GET');
        $output = $response->getBody();



Question: How to Set the username/password in CURL?
curl -X POST -u "USERNAME":"PASSWORD" --header "Content-Type: audio/flac" --header "Transfer-Encoding: chunked"  "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" 



Question: How to pass binary data(file) in CURL ?
curl -X POST -u "USERNAME":"PASSWORD" --header "Content-Type: audio/flac" --header "Transfer-Encoding: chunked" --data-binary @audio.flac "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" 



Question: How to store linux command output in file?
curl -X POST -u "USERNAME":"PASSWORD" --header "Content-Type: audio/flac" --header "Transfer-Encoding: chunked" --data-binary @audio.flac "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize" > output1.txt



Friday 6 September 2013

PHP Interview Questions and Answers PDF

In the Web Development Field, PHP Play very vital roles. PHP Enable the developer to create the custom pages. In the custom pages they can add html, CSS, Photos and Videos. In PHP we can easily used third party compoments like Emailing, PDF creation, Connect to google analytics through the PHP etc.

To grow more in web development, PHP developer enhance their PHP skills daily for this they read "PHP Interview Questions and Answers". They do lot of with "PHP Interview Questions and Answers"

Some times due to any reason Internet is not available, They are not able to read the interview question.
To solve this problem our team has created a Link where they can download the "PHP Interview Questions and Answers" In PDF format. So that they can read / revise the question whenever Internet is not available.

After download you can upload this pdf in your mobile also. So that it is available all the time.
Our "PHP Interview Questions and Answers PDF" is not just only theory it also have practical parts because while developing website you need lot of practical skills as compare to theory.
Also in Interview, Interviewer focus on Practical Question because they know very well, Practical answer can be given only by a person who can done practical things.



Friday 21 June 2013

Stored Procedure - Advantage of Stored Procedure - Disadvantage of Stored Procedure

Advantage of  Stored Procedure

  • Stored procedures can be used to maintain data integrity and enforce database policy without relying on an external program to do so.
  • the DBA can add behavior that the application doesn't care about. For example, storing a modify date on each row.
  • You do not need to deploy to make a change.
  • Much faster than dynamic queries
  • Easier to expand a system
  • A small functionalists can be added in SP (Store Procedure)



Dis-Advantage of  Stored Procedure
  • Debugging is hard.
  • Source control can be a pain.
  • If you have a lot of functionality in store procedure it will making swapping between different database systems harder - It also creates more work if you want to support different database systems.
  • Developing stored procedures can be a fairly specialized task, especially as they get more complex.
  • Refactoring is harder. Renaming or changing where the store proc is might produce a bad effect.

Saturday 8 June 2013

Pending Interview Questions and Answers

Who is the Father of PHP?
Rasmus Lerdorf


Which programming language does PHP resemble to?
PHP resemble to pearl and C


How can we create a database using PHP and MySQL?
We can create MySQL database in php with the use of
mysql_create_db ("db_name");


Is variable name case sensitive?
Yes, In PHP variable name case sensitive. We cannot start a variable with number like $777name as a valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.


How can we execute a php script using command line?
Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, "php myScript.php", assuming "php" is the command to invoke the CLI program.


Differentiate between in_array() and array_search() in php?
in_array : Checks if a value exists in an array. array_search() : Searches an array for a given value and returns the corresponding key if successful.


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


How to delete file in PHP ?
unlink($filename);


How to delete variable in PHP ?
unset($variable);


What is the urlencode and urldecode in php ?
Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.


What is the use of the function htmlentities?
htmlentities Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.


Differentiate between strstr and stristr in php?
strstr() and stristr both are used to find the first occurence of the string only difference is stristr( ) is case insensitive.


How can we know the total number of elements of Array?
sizeof($array);
count($array);


How to secure your website?
  1. Validate Input.
  2. Use Auth & ACL.
  3. Protect my Session ID
  4. Preventing Cross Site Scripting (XSS) flaws
  5. SQL injection vulnerabilities
  6. Turning off error reporting and exposing to the site for hackers
  7. Protect secure data of website


What is PHP configuration file called?
php.ini.


What is a persistent cookie?
A persistent cookie is a cookie which is stored in a cookie permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased automatically.


What are non-key columsn in database?
Answer: A non key attribute in sql server is a columns which can not be used to identify a record uniquely for example name or age columns in customer table


Friday 7 June 2013

Cache in PHP - Speed Up your website

Follow the following steps to implement caching in Core PHP?
  • Create a folder with write permission where you store the output of page
  • At the start of file, check whether you have already stored the output of file or not
  • If you have already stored the output in cache, then get the contents from cache instead of executing the code
  • If Not, first prevent the php to send the output to the browser (ob_start php) and store the output in cache folder
  • Create the page in your application from where you can delete all the files, stored in cache folder (when website updates)



See Example
$fileName="xxxx.html";
$cacheFolder="/cache/";//must be writeable 

//check if file in cache
if(file_exists($cacheFolder.$fileName,'r'){
$output = file_get_contents($cacheFolder.$fileName);
}else{
ob_start(); //stop sending output to the browser
//do work
//do work
//do work
$output = ob_get_contents();
ob_end_flush();
$fp=fopen($cacheFolder.$fileName,'w');
fwrite($fp, $output);
fclose($fp);
}
echo $output;


Monday 3 June 2013

PHP interview questions and answers for 1 year experience

php interview questions and answers for 1 year experience

Question: What are the current versions of apache, php, and mysql?
Answer: 
PHP: 7.0.4 / March 3, 2016
Apache: 2.4.18 December 14, 2015
MySQL: 5.6.26 / July 24, 2015

Question: What are the different types of errors in php?
Answer:
E_ERROR: A fatal error that causes script termination
E_WARNING: Run-time warning that does not cause script termination
E_ALL: Catches all errors and warnings
E_PARSE: Compile time parse error.
E_NOTICE: Run time notice caused due to error in code
E_USER_WARNING: User-generated warning message.
E_USER_ERROR: User-generated error message.
E_USER_NOTICE: User-generated notice message.
E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error

Question: What is maximum size of a database in mysql?
Answer: Depend on Operating System

Question: What is meant by MIME?
Answer:
Multipurpose Internet Mail Extensions. 

WWW ability to recognize and handle files of different types is largely dependent on the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard provides for a system of registration of file types with information about the applications needed to process them. 

Question: What Is a Persistent Cookie?
Answer:

Persistent cookie is a cookie which is permanently stored on user’s computer in a cookie file. They are used for tracking the user information of the users who are browsing from a very long time. They also have the drawbacks of being unsecure, as user can see the cookies which are saved on the computer. 


Question: How to set persistent Cookie?
There is no special way to set persistent cookies. Setting Cookies with an expiration date become persistent cookie.
setcookie( "cookieName", 'cookieValue', strtotime( '+30 days' ) );



Question: Can we send ajax request to other domain?
Answer: No, You can't send Ajax request if different protocal OR different host.
For Example, the following table gives an overview of typical outcomes for checks against the URL"http://www.example.com/directory/about-us.html".

Compared URLOutcomeReason
httpː//www.example.com/dir/page2.htmlSuccessSame protocol and host
httpː//www.example.com/dir2/other.htmlSuccessSame protocol and host
httpː//www.example.com:81/dir/other.htmlFailureSame protocol and host but different port
https://www.example.com/dir/other.htmlFailureDifferent protocol
http://en.example.com/dir/other.htmlFailureDifferent host
http://example.com/dir/other.htmlFailureDifferent host (exact match required)
http://v2.www.example.com/dir/other.htmlFailureDifferent host (exact match required)
httpː//www.example.com:80/dir/other.htmlDon't usePort explicit. Depends on implementation in browser.


Question: How can PHP read the hash portion of the URL?
Answer: PHP can't read the hash portion of the URL
index.php?page=group#birthday
Here, PHP can not read the birthday

There is some by which you can get this value
get the value by javascript and then set to cookie or pass in ajax. See Example
var query = location.href.split('#'); 
document.cookies = 'hasValue=' + query[1];

Question: What Is difference between array_combine and array_merge?
Answer:
array_combine give an array by combining two arrays($keyArray, $valueArray) and both $keyArray & $valueArray must have same number of elements. $keyArrays become keys of returning Array, $valueArray become values of returning Arrays.

array_merge gives an array by merging two array ($array1, $array2) and both can have different number of elements. $array1 and $array2 are added in returning array.


Question: What Is difference between Cookie and Session?
Answer:
Cookie are stored in client side (e.g Browser) where as Session are stored in server side (tmp file of web server). Cookie can be added/update/delete from browser but session can't delete from browser. 
Session is depended on cookie. For example: When user login in website then session is created in webserver. To communicate the webserver with user, an cookie is created by the application. with use of this cookie-key, Server get to know that user is login OR not.

http://www.web-technology-experts-notes.in/2014/11/angularjs-interview-questions-and-answers-for-experienced.html




Question: What are encryption functions in PHP? 
CRYPT(), MD5()



Question: How to store the uploaded file to the final location? move_uploaded_file( string filename, string destination)


Question: Explain mysql_error(). The mysql_error() message will tell us what was wrong with our mysql query.



Question: What is stdClass?
It is PHP generic empty class.
stdClass is used to create the new Object. For Example
$newObj = new stdClass();
$newObj->name='What is your name?';
$newObj->description='Tell me about yourself?';
$newObj->areYouInIndia=1;
print_r($newObj);

Output
stdClass Object
(
    [name] => What is your name?
    [description] => Tell me about yourself?
    [areYouInIndia] => 1
)




Friday 31 May 2013

PHP Interview Questions and Answers for Experienced

PHP Interview Questions and Answers for Experienced

Question: What is Difference between local variable and data members or instance variable?
Answer: 1. A data member belongs to an object of a class whereas local variable belongs to its current scope. 
2. A local variable is declared within the body of a function and can be used only from the point at which it is declared to the immediately following closing brace.
3. Data members are accessible to all member function of the class. Local variable are not accessible in any another function or class.


Question: What are static method? How its different from normal method?
Answer: 1. Static methods are that can be accessed by using the scope resolution operator (i.e ::) and object reference operator ( i.e.-> ).

For example HelloClass::mystatic(); $helloClass->mystatic();
class MyClass{             
    static function mystatic() {                           
        echo "this was declared static!\n";  
    }  
}              
 
$obj = new MyClass();                                                                                 

MyClass::mystatic();
$obj->mystatic();

2. The only rule is that static methods or properties are out of object context.
3. Public function of class can be access by scope resolution operator (i.e ::) and Object Reference Operator (i.e ->) but public data member can't be access through scope resolution operator.




Question: When and Why we use static variable/ functions?
Answer: 1. You use static when you want to use a method / variable that is not tied to an instance.
2. When you want to persistent value throughout multiple call of function.
3. For singleton pattern, we use static method/variable.
4. it is very usefull for caching if a method will be called very often and do just the same thing. For example see below
protected function is_logged_in() {
    static $logged_in = null;
    if($logged_in != null) {
        return $logged_in;
    }

    //Check shibboleth headers
    if (!empty($_SERVER['HTTP_SHIB_IDENTITY_PROVIDER']) || !empty($_SERVER['Shib-Identity-Provider'])) {
        if (!empty($_SERVER[$this->core->dbconfig("shib_auth", self::SHIB_AUTH_CONFIG_UID)])) {
            $logged_in = true;
            return true;
        }
    }
    $logged_in = false;
    return false;
}


Question: What is Persistent Database Connections?
Answer: Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link.
Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably.



Question:Server Start/Stop/Restart unix command
Restart Apache web server over the SSH
/etc/init.d/apache2 restart

Stop Apache web server over the SSH
/etc/init.d/apache2 stop

Start Apache web server over the SSH
/etc/init.d/apache2 start

httpd Server restart command
service httpd restart

httpd Server Stop command
service httpd stop

httpd Server Stop command
service httpd start


Question: What is ORM?
Answer: Full form of ORM is Object Relation Mapper.
 ORM is programming technique for converting data between incompatible type systems in object-oriented programming languages.


Data management tasks in object-oriented programming(OOP) are typically implemented by manipulating objects that are almost always non-scalar values.
For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a "Person object" with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain "PhoneNumber objects" and so on. The address book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance)

Question: What is Exception Handling in PHP?
Answer: Exception Handling is used to handle the error. It can handle all types of error like Warning, Notice, User defined Error message etc but unfortunately it can not handle fatal error. read more...



Question: What is dispatcher in Zend?
Answer: Dispatching is the process of taking the request object,  Zend_Controller_Request_Abstract, extracting the module, controller, action name, and optional parameters contained in it, and then instantiating a controller and calling an action of that controller. If any of the module name, controller name, or action are not found, it will use default values for them.
Zend_Controller_Dispatcher_Standard specifies index for each of the controller and action defaults and default for the module default value, but allows the developer to change the default values for each using the setDefaultController(), setDefaultAction(), and setDefaultModule() methods, respectively.


Question: What is Bootstrap in Zend?
Answer: In Zend Framework, bootstrapping is the process that loads your application. This includes, but is not limited to the Session. Any resources needed by your application to process the request (the dispatch) to the application is bootstrapped/loaded/initialized before the request is fulfilled, e.g. before the controller delegates any input to the model and creates a response that is send back to the client.


Question: What are the advantages and disadvantages of Store procedure.
Answer: Following are the advantage / disadvantage of SP.
Advantage
You do not need to deploy to make a change.
Faster
Easier to expand a system

Disadvantages
Refactoring is harder. Renaming or changing where the store proc is might produce a bad effect.
Unit testing stored proc require code assistance outside the DB



Question : What is difference between array_combine and array_merge?
Answer: array_merge merges the elements of one or more arrays. array_combine  Creates an array by using one array as its keys and another for its values.


Question: How to import database from desktop to server with use of command line?
1) Make a zip of sql dump file and upload the zip file to server through FTP.
2) Login to Putty/Console
3) Go the directory with use of cd command, the location where you have upload the zip file.
4) unizip that zip file, with following command
unzip zipfilename.zip
3)Import the sql dump file with use of following command.
mysql -u username -p databasename < sqlfilename.sql 

(It will for prompt password)


Question: How to copy file from one server to another?
1) Login to Putty/Console
2) Go to the directory where your file exist (suppose file name is file.zip)
3) Use the following command to copy the file frome current server to another server
scp file.zip username@hostname:/foldername
(It will prompt password)
(username, hostname is another server)


Question: How to export database to sql file with use of command line?
1) Login to Putty/Console
2) Execute following commands to export the sql dump into server.
mysqldump –u username –p databasename tablename > sqlfilename.sql
(It will prompt password)


Question: Import database from sql file to mysql
mysql –u username –p databasename tablename < sqlfilename.sql
(It will prompt for password)


Question: What is Responsive web design? 
Responsive web design (RWD) is a web design approach aimed at crafting sites to provide an optimal viewing experience, easy navigation and reading with a minimum of scrolling, resizing and  panning. across a wide range of devices (all mobiles, desktop, laptop, ipad etc).


Question:  What is www1?
World Wide Web
The number(eg 1,2,3,4,5....) that follows the "WWW" indicates that the data being retrieved by the Web browser is gathering the information from a different Web server than the one that serves the typical "WWW" address.
Web sites, especially dynamic Web sites, that handle large amounts of traffic often need more than one server to accommodate the many requests they receive as one server often cannot handle the multitude of requests.
Examples
https://www1.pearsonvue.com/
https://www2.pearsonvue.com/
https://www3.pearsonvue.com/
https://www4.pearsonvue.com/
https://www5.pearsonvue.com/
https://www6.pearsonvue.com/

Here all above websites have same data.


Question: Create a php script that output following.

Answer:
$totalRows =5;
$totalStar=1;
for($rows=1; $rows<=$totalRows; $rows++){
if($rows!=1){
$totalStar+=2;
}
$cols=$totalStar;
$space = $space1 = $totalRows-$rows; 
 
 /** create first space **/ 
  while($space>0){
       echo ' ';
      $space--;
  }
  /** create star **/
    while($cols>0){
       echo "* ";
   $cols--;
  }
  /** create second space **/ 
    while($space1>0){
       echo ' ';
      $space1--;
  }
  
   echo "";

}

Question: What is New Relic. What is benefits of this software?
Answer: New Relic is software as a service (SaaS) that monitors your Website and mobile applications(Android, iOS) in real-time that run in different environments like cloud, on-premise and hybrid. 

Following are few benefits of New Relic
1. Monitoring your website regularly.
2. Downtime Notification by email.
3. Custom Error recording and then report you in email & also can view in newrelic website.
4. Key Transaction tracking: 
You will be able to see where your application is spending most of its time (e.g. in the controller, model OR database).
5. External Service Call Recording (Webservices)



Question: What is Apdex?
Answer: Apdex means Application Performance Index.
It is standard method for reporting & comparing the performance of software.

Purpose:  Analyse the performance, user satisfaction & expectation then Convert into percentage.

Formula
Apdex = (Satisfied + Tolerating / 2) / Total 
Satisfied: Response time is less than or equal to T.
Tolerated: Response time is more than T and (Less than OR Equal to 4T);
Frustrated: Response time is greater than 4T.
T: It is threshold time define by  application owner.

Example: https://docs.newrelic.com/docs/assets/apdex.pdf


Question: Execute a php script using command line in wampserver server in window7.
Answer: Follow  simple steps
1. login to command prompt (CMD)
2. Go to path where "php.exe" exist in wamp folder.
"C:\wamp\bin\php\phpx.x.x";
2. Execute the file with php, for example
php c:/wamp/www/arun/test.php


Question: What is meant by urlencode and urldocode?
Answer: URL coding converts special characters into % signs followed by two hex digits.
For example, urlencode("10.00%") will return "10%2E00%25?
urldocode is just opposite to urlencode


Question: What is difference between unlink and unset?
Answer: unlink: It unlink(remove) the file.
unset: It unlink(remove) the variable from scope.


Question: How to get the image type, size,width and height
Answer: 
type: exif_imagetype()
size: use getimagesize()
width: use imagesx()
height: use imagesy()


Question: What are formating functions in PHP?     
Answer: 
Function                     Description
printf()    :                 Displays a formatted string
sprintf()   :                 Saves a formatted string in a variable
fprintf()   :                 Prints a formatted string to a file
number_format()  :   Formats numbers as strings


Question: How to import Text File in database?
LOAD DATA LOCAL INFILE 'C:/Users/Vijay/Desktop/SQL/image.txt' INTO TABLE images FIELDS TERMINATED BY '|' LINES TERMINATED BY '\n';



Question: How to include a file to a php page?
We can include a file using include() or require() function with file path as its parameter. For Example
include "myfile.php";
require "myfile.php";//use this OR ABOVE



Question: How to detecting request type in PHP (GET, POST, PUT)?
echo $_SERVER['REQUEST_METHOD']; //get/post/put/delete



Question: How to get the full path of php.ini?
You can check php.ini path in phpinfo();
Search with Loaded Configuration File .