Thursday, 23 April 2015

Php Interview Questions and Answers

1) What is PHP?

PHP: Hypertext Preprocessor is open source server-side scripting language that is widely used for web development. PHP scripts are executed on the server. PHP allows writing dynamically generated web pages efficiently and quickly.

2) Echo vs. print statement.

echo() and print() are language constructs in PHP, both are used to output strings. The speed of both statements is almost the same.
echo() can take multiple expressions whereas print cannot take multiple expressions.
Print return true or false based on success or failure whereas echo doesn't return true or false.

3) $var vs $$var in PHP.

$var is a variable with a fixed name. $$var is a variable whose name is stored in $var.
If $var contains "var", $$var is the same as $var.

4) Errors in PHP.

Notices, Warnings and Fatal errors are the types of errors in PHP
Notices:
Notices represents non-critical errors, i.e. accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all but whenever required, you can change this default behavior.

Warnings:
Warnings are more serious errors but they do not result in script termination. i.e calling include() a file which does not exist. By default, these errors are displayed to the user.

Fatal errors:
Fatal errors are critical errors i.e. calling a non-existent function or class. These errors cause the immediate termination of the script.

5) What is MIME?

MIME - Multi-purpose Internet Mail Extensions.
MIME types represents a standard way of classifying file types over Internet.
Web servers and browsers have a list of MIME types, which facilitates files transfer of the same type in the same way, irrespective of operating system they are working in.

6) What's the difference between include and require?

If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

7) Differences between GET and POST methods ?

We can send 1024 bytes using GET method but POST method can transfer large amount of data and POST is the secure method than GET method .


8) How to declare an array in php?

Eg :  $arr = array('apple', 'grape', 'lemon');

9) What is use of in_array() function in php ?

in_array used to checks if a value exists in an array

10) What is use of count() function in php ?

count() is used to count all elements in an array, or something in an object

11) What is the difference between Session and Cookie?

The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user’s computers in the text file format. Cookies can not hold multiple variables,But Session can hold multiple variables.We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking.


12) How to set cookies in PHP?

Setcookie("sample", "lipu", time()+3600);
Retrieve - echo $_COOKIE["sample"];

13) How to create a session? How to set a value in session ? How to Remove data from a session?

Create session : session_start();
Set value into session : $_SESSION['USER_NAME']="LIPU";
Remove data from a session : unset($_SESSION['USER_NAME'];

14) what types of loops exist in php?

for,while,do while and foreach

15) How to create a mysql connection?

mysql_connect(servername,username,password);

16) How to select a database?

mysql_select_db($db_name);

17) How to execute an sql query? How to fetch its result ?

$my_qry = mysql_query("SELECT * FROM 'users' WHERE 'u_id'='1';");
$result = mysql_fetch_array($my_qry);
echo $result['table_column_name'];

18) Write a program using while loop

$my_qry = mysql_query("SELECT * FROM 'users' WHERE 'u_id'='1';");
while($result = mysql_fetch_array($my_qry))
{
echo $result['table_column_name'.]."<br/>";
}


19) How we can retrieve the data in the result set of MySQL using PHP?
1. mysql_fetch_row
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc


20) What is the difference between explode() and split() functions?

Split function splits string into array by regular expression. Explode splits a string into array by string.

21) What is the use of mysql_real_escape_string() function?

It is used to escapes special characters in a string for use in an SQL statement

22) Write down the code for save an uploaded file in php.

if ($_FILES["file"]["error"] == 0)
{
move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}

23) How to create a text file in php?

$filename = "newfile.txt";
$file = fopen($filename, "w");
if( $file == false )
{
echo ( "Error in opening new file" ); exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );


24) How to strip whitespace (or other characters) from the beginning and end of a string ?

The trim() function removes whitespaces or other predefined characters from both sides of a string.

25) What is the use of header() function in php ?

The header() function sends a raw HTTP header to a client browser.Remember that this function must be called before sending the actual out put.For example, You do not print any HTML element before using this function.

26) How to redirect a page in php?

The following code can be used for it, header("Location:index.php");

27) How stop the execution of a php scrip ?

exit() function is used to stop the execution of a page


28) How to set a page as a home page in a php based site ?

index.php is the default name of the home page in php based sites

29) How to find the length of a string?

strlen() function used to find the length of a string

30) what is the use of isset() in php?

This function is used to determine if a variable is set and is not NULL

31) What is the difference between mysql_fetch_array() and mysql_fetch_assoc() ?

mysql_fetch_assoc function Fetch a result row as an associative array, While mysql_fetch_array() fetches an associative array, a numeric array, or both

32) How do you define a constant?

Using define() directive, like define ("MYCONSTANT",150)

33) How send email using php?

To send email using PHP, you use the mail() function.This mail() function accepts 5 parameters as follows (the last 2 are optional). You need webserver, you can't send email from localhost. eg : mail($to,$subject,$message,$headers);

34) How to find current date and time?

The date() function provides you with a means of retrieving the current date and time, applying the format integer parameters indicated in your script to the timestamp provided or the current local time if no timestamp is given. In simplified terms, passing a time parameter is optional - if you don't, the current timestamp will be used.

35) What is the use of "ksort" in php?

It is used for sort an array by key in reverse order.

36) What are the encryption techniques in PHP

MD5 PHP implements the MD5 hash algorithm using the md5 function,
eg : $encrypted_text = md5 ($msg);
mcrypt_encrypt :- string mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] );
Encrypts plaintext with given parameters

37) 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.

38) How to delete a file from the system?

Unlink() deletes the given file from the file system.

39) How to get the value of current session id?

session_id() function returns the session id for the current session.

40) what is sql injection ?

SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications.



Enjoy........................

Friday, 3 April 2015

php back button confirm form resubmission

If you are able to see confirm form re-submission message when hit the back button then write the following code on the page header, That will solve the issues.

<?php
header("Expires: Mon, 26 Jul 2010 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header('Cache-Control: max-age=900');
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

Wednesday, 4 March 2015

magento Call to a member function setProductFilter() on a non-object

It is a Major Problem in Magento 1.9.xx
I found the cause.

If your Problem  is - magento Call to a member function setProductFilter() on a non-object in app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php on line 294


Go to -
app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/

And see there are the Collection.php file exist or not.
I thing there are Collection.php file exist but the file extension is not correct format.

You can change the extension only, Make it Collection.php


Thanks

Wednesday, 17 December 2014

Show product discount percent in Magento

Open app/design/frontend/yourpackage/yourtheme/template/catalog/product/price.phtml


Find

<?php endif; /* if ($_finalPrice == $_price): */ ?>


Add above it:

<?php // Discount percents output start ?>
    <?php if($_finalPrice < $_price): ?>
    <?php $_savePercent = 100 - round(($_finalPrice / $_price)*100); ?>
        <p class="special-price yousave">
            <span class="label"><?php echo $this->__('You Save:') ?></span>
            <span class="price">
                <?php echo $_savePercent; ?>%
            </span>
        </p>
    <?php endif; ?>
<?php // Discount percent output end ?>

Friday, 28 November 2014

magento set shipping estimate on cart page and get the shipping rates

<?php
$zipcode = '2000'; // Your zipcode
$country = 'GB'; // Your country Id
$cart = Mage::getSingleton('checkout/cart');
$address = $cart->getQuote()->getShippingAddress();
$address->setCountryId($country)->setPostcode($zipcode)->setCollectShippingrates(true);
$cart->save();

$rates = $address->collectShippingRates() ->getGroupedAllShippingRates();
if($rates) {
?>
<form id="co-shipping-method-form" action="<?php echo $this->getUrl('checkout/cart/estimateUpdatePost') ?>" >
<?php
foreach ($rates as $carrier) {
    foreach ($carrier as $rate) {
//echo '<pre>';   print_r($rate->getData()); echo '</pre>';
if($rate->getCode() == "express_express") {  // Only show your custom shipping module
?>
<input name="estimate_method" type="checkbox" value="<?php echo $rate->getCode(); ?>" id="s_method_express_express" onclick="getShipppingCost();"  <?php if($rate->getCode()===$address->getShippingMethod()) echo ' checked="checked"' ?> class="radio">
             <label for="s_method_express_express"><?php echo $this->escapeHtml($rate->getMethodTitle()) ?>
<span class="price"> <?php echo  Mage::helper('core')->currency($rate->getPrice()); ?></span>
</label>
<?php  
}
    }
}

?>
<script>
function getShipppingCost()
{
var methodid= document.getElementById("s_method_express_express");
if(methodid.checked == true)
{ document.getElementById('co-shipping-method-form').submit(); }
else { methodid.value="freeshipping_freeshipping"; methodid.checked = true; document.getElementById('co-shipping-method-form').submit(); }

}

</script>

</form>
<?php } ?>

Thursday, 30 October 2014

magento set all image to thumbnail image

UPDATE catalog_product_entity_media_gallery AS mg,
       catalog_product_entity_media_gallery_value AS mgv,
       catalog_product_entity_varchar AS ev
SET ev.value = mg.value
WHERE  mg.value_id = mgv.value_id
AND mg.entity_id = ev.entity_id
AND ev.attribute_id IN (85,86,87)
AND mgv.position = 1;

Friday, 24 October 2014

php create word document from html

<html
    xmlns:o='urn:schemas-microsoft-com:office:office'
    xmlns:w='urn:schemas-microsoft-com:office:word'
    xmlns='http://www.w3.org/TR/REC-html40'>
    <head>
        <title>My Word Document</title>
       
    <xml>
        <w:WordDocument>
            <w:View>Print</w:View>
            <w:Zoom>100</w:Zoom>
            <w:DoNotOptimizeForBrowser/>
        </w:WordDocument>
    </xml>
 
    <style>
        p.MsoFooter, li.MsoFooter, div.MsoFooter{
            margin: 0cm;
            margin-bottom: 0001pt;
            mso-pagination:widow-orphan;
            font-size: 12.0 pt;
            text-align: right;
        }


        @page Section1{
            size: 29.7cm 21cm;
            margin: 2cm 2cm 2cm 2cm;
            mso-page-orientation: landscape;
            mso-footer:f1;
        }
        div.Section1 { page:Section1;}
    </style>
</head>
<body>
    <div class="Section1">
        <h1>Hello World! This My First</h1>
 
    </div>
</body>
</html>
<?php
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=myfirst.doc");
?>