Tuesday, 30 June 2015

PHP Basic questions and answers for fresher and experienced

Top 25 PHP-Interview Questions and Answers


Question: How JSON.parse Works? Give few examples?
JSON.parse is method which is used parses a string as JSON. How to parse the string as JSON
JSON.parse('{}');              // {}
JSON.parse('null');            // null
JSON.parse('true');            // true
JSON.parse('"string"');           // "string"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]



Question: How to get the Data of any Public URL(HTML Contents)? Get the data of public URL is known as scrapping. You can use following method to get the data of public URL
  1. use file_get_contents function
  2. use CURL


Question: What is use of nl2br?
nl2br is used to insert the line break.


Question: What is .htaccess?
htaccess is configuration file for Apache Server which helps us to configure at base level configuration as well as directory level.


Question: How to get the URL of Referrer page?
echo $_SERVER['HTTP_REFERER'];


Question: How to extract seconds, minutes and hour from date?
$dateTime = strtotime("2015-06-30 12:25:60");
echo date('s',$dateTime); //seconds
echo date('i',$dateTime); //Minutes
echo date('h',$dateTime); //hour in 0-12 format
echo date('H',$dateTime); //hour in 0-24 format


Question: How to get current date and time?
echo date('Y-m-d H:i:s');



Question: How to change the timezone using PHP?
echo date_default_timezone_get(); //Default time zone

date_default_timezone_set('America/Los_Angeles'); //Chnage timezone to Los_Angeles



Question: Difference between unset and unlink?
unset is used to remove the variable from scope.
unlink is used to remove the file from server.


Question: How to increase max execution time?
Following are different ways to increase the execution time?
Change dynamically with PHPv
ini_set('max_execution_time', 300);

With htaccess
php_value max_execution_time 300

Change in php.ini (NEED server restart)
max_execution_time = 120


Question: How to check a variable have number OR String value?
$testvariable ='10';
if(is_number($testvariable)){
    echo "This is Number";
}else{
    echo "This is string";
}


Question: What is PEAR in php?
Full form of PEAR is PHP Extension and Application Repository. It 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 standard way to get the file type of an file.


Question: Can we change the value of constant variable?
No, we can't do this.


Question: How do we destroy a session?
session_destroy();



Question: What is a PDO classes?
PDO is an PHP extension which provides an interface to connect the database like mysql, mysqli, SQL etc.


Question: What is full form of Ajax? What is Ajax?
Full form of AJAX is Asynchronous JavaScript and XML.
Ajax is technique which is used to update the website contents without refreshing the page. Ajax get the contents from server.


Question: How to set and destroy the cookie?
setcookie("cookieName", "cookie value", time()+3600);  //Set the cookie
setcookie("cookieName", "cookie value", time()-3600);  //distroy the cookie


Question: Does PHP support multiple inheritances in PHP?
No, PHP Support only single level of inheritance.


Question: Can we achieve multiple inheritance in PHP?
PHP Does not support multiple inheritance but we can achieve multilevel inheritance in directly.
See Example below:
class a{}
class b extends a{}
class c extends b{}
class d extends c{}
class e extends d{}
class f extends e{}

As PHP Does not support multi level inheritance but we can extend mulitple classes one by one (As in Above).



Thursday, 25 June 2015

Braintree Questions and Answers - Javascript+PHP

Braintree Questions and Answers - Javascript+PHP


Question: What is use of custom fields? How to use custom fields to save the customer details?
When we create/update the customer details, you might need to add extra fields which are not supported by braintree APIs. In that case, you can use braintree custom fields, with use of custom fields you can save extra customer details like nick name, personal meeting date etc.
When you start save custom fields you will get following error:
Customer ID has already been taken.

Then means, you must have to set the custom fields name in cpanel of your account.
Following are simple instruction to set the custom fields in cpanel of merchant account.
01) Log into the Control Panel in braintree.
02) Go to Settings > Processing > Custom Fields.
03) Click on "New".
04) Fill the form. (Use API Name variable in custom field ).
05) Click Save.


Question: How to get the client token?
"Client token" are generated by Server, use following function to do the same.
$clientToken = Braintree_ClientToken::generate();
This token is used by braintree js and compulsory to process the transaction.
   braintree.setup(clientToken, "custom", {
        . 
        .
        .
      });



Question: How to get "noune payment method"?
When customer fill the credit card details and submit the form, Request goes to "Braintree".
All details are saved in "Braintree" Server.
and you get an unique string that is know as "noune payment method".
With use of this "noune payment method", you can charge the customer.

$result = Braintree_Transaction::sale(array(
    'amount' => '1.00',
    'paymentMethodNonce' => '699dc252-6388-464a-9712-5dd8fa2bb656',
    'options' => array(
      'submitForSettlement' => True
    )
  ));
$transactionId = $result->transaction->id;

 noune payment method will expired in 24 Hours.


Question: I am getting error "Unknown payment_method_nonce.". Why?
If you are getting above error message, It might have any of below Reason.
a) paymentMethodNonce is invalid.
b) paymentMethodNonce is already expired OR used.


Question: Give some test credit card numbers for braintree?
378282246310005
371449635398431
6011111111111117
3530111333300000
4111111111111111
4500600000000061

Use any CVV Number and Expiry date (Must future date)


Question: How to get Client Token from server using for Customer.
/** Include Library and set configuration**/
require_once '/braintree-php301/lib/Braintree.php';
Braintree_Configuration::environment('sandbox');
Braintree_Configuration::merchantId('xxxxxxxx');//update merchantId
Braintree_Configuration::publicKey('xxxxxxxxxx');//update public key
Braintree_Configuration::privateKey('xxxxxxxxxxxxxxxxxxxxxx'); //Private key
 
//Get the Client Token
$clientToken = Braintree_ClientToken::generate();

//Get the Client Token for Customer 
$clientToken = Braintree_ClientToken::generate(array('customerId'=>464654654));



Question: How to get Custom details using customerId?
/** Include Library and set configuration**/
.
.
.       
/** Include Library and set configuration**/
$customerId = 67222186;  
   try{
       $result = Braintree_Customer::find($customerId); 
      echo $result->id; echo "\n";
      echo $result->firstName; echo "\n";
      echo $result->lastName; echo "\n";
      echo $result->email; echo "\n";
      echo $result->phone; echo "\n";
   }  catch (Exception $e){
    echo $e->getMessage();die;
  }


Question: How to connect a customer with nonce (payment method)?
$customer = 66082493; //CustomerId of customer
$result = Braintree_PaymentMethod::create(array(
    'customerId' => $customer,
    'paymentMethodNonce' => 'be2d6271-c71f-46ae-96c4-3b1e471cc575'
));


Question: How to charge from Customer with customer_id?
$result = Braintree_Transaction::sale(
  array(
    'customerId' => 'the_customer_id',
    'amount' => '100.00'
  )
);

Question: How to charge from Customer with nonce token?
$result = Braintree_Transaction::sale(array(
  'amount' => '100.00',
  'paymentMethodNonce' => nonceFromTheClient
]));





Wednesday, 24 June 2015

Manage Customer Details in Braintree




Following are code snippet that are useful to mange the customer details in braintree. you must have an account in braintree to use below code.


Add Customer
You can ADD customer details in braintree server, after saving the customer detail you will get customerId which can use latter on.  You can also add custom fields.

Note: Each customer is bound to specific merchant.

/** Include Library and set configuration**/
require_once '/braintree-php301/lib/Braintree.php';
Braintree_Configuration::environment('sandbox');
Braintree_Configuration::merchantId('xxxxxxxxxxxxxxxx');
Braintree_Configuration::publicKey('xxxxxxxxxxxxxxxxx');
Braintree_Configuration::privateKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxx');
/** Include Library and set configuration**/

$result = Braintree_Customer::create(array(
    'firstName' => 'Ram   ',
    'lastName' => 'Kumar',
    'company' => 'web-technology-experts-notes',
    'email' => 'email@web-technology-experts-notes.in',
    'phone' => '281.330.8004',
    'fax' => '419.555.1235',
    'website' => 'http://www.web-technology-experts-notes.in',
    'customFields' => array(
            'custom_field_one' => 'custom value',
            'custom_field_two' => 'another custom value'
        )
));

if($result->success){
    $customerId = $result->customer->id; //New Customer Id
}



Update Customer
Using the customerId, You can UPDATE customer details in braintree server.

/** Include Library and set configuration**/
.
.
.
/** Include Library and set configuration**/


$customerId = 14983213;
$result = Braintree_Customer::update($customerId,array(
            'firstName' => 'Ram   ',
            'lastName' => 'Singh',
            'company' => 'web-technology-experts-notes',
            'email' => 'email@web-technology-experts-notes.in',
            'phone' => '281.330.8004',
            'fax' => '419.555.1235',
            'website' => 'http://www.web-technology-experts-notes.in'
));  
if($result->success){
    die("Customer Detail Updated Successfuly");
}



Find Customer
Using the customerId, You can SEARCH the customer detail from braintree server.

/** Include Library and set configuration**/
.
.
.
/** Include Library and set configuration**/

/** find customer detail **/
$customerId = 14983213;
try{
      $result = Braintree_Customer::find($customerId); 
     echo $result->id; echo "\n";
     echo $result->firstName; echo "\n";
     echo $result->lastName; echo "\n";
     echo $result->email; echo "\n";
     echo $result->phone; echo "\n";
  }  catch (Exception $e){

      echo $e->getMessage();die;
  }
/** find customer detail **/


Delete Customer
Using the customerId, You can DELETE customer detail from braintree server.

/** Include Library and set configuration**/
.
.
.
/** Include Library and set configuration**/

/** Delete a customer **/
$customerId = 14983213;
try{
      $result = Braintree_Customer::delete($customerId); 
      if($result->success){
        echo "Customer deleted successfully";
        }
      
  }  catch (Exception $e){

      echo $e->getMessage();die;
  }
/** Delete a customer **/



Tuesday, 23 June 2015

Hosted Field Integration - Braintree

Hosted Field Integration - Braintree


Question:What is Hosted Field in Braintree?
Hosted Fields are fields which are in another websites but displaying on your own website. It gives such a look, Customer will think its on your website but in actual its on braintree website. Payment Form files are in Iframe.
Following are the fields which can display in your website.
Credit card Number
Expiry Date
CVV Number



Question: What is purpose of hosted Fields?
If you want to accept the credit card/debit card in your website to charge from customer. You have to take the PCI compliance.
With using hosted field of braintree, you need not to worry about PCI Compliance.
Basically, Hosted Fields are developed to Solved the PCI 3.0..


Question: How hosted fields helps to solve the issue PCI Compliance?
Suppose you have payment page, where customer can fill credit card information.

Braintree create a payment-form dynamically in your website with use of java-script. This form is in iframe but and you can do lot of styling customization.

In this way, customer add the credit card info in your website but in actual its on braintree. that's why you need not to worry about PCI Compliance. Also when user submit the form, credit card information goes on braintree and use them & you will get a "nonce" variable.


Question:Explain Hosted Field in single line?
Hosted Fields are small, transparent iframes that replace the sensitive credit card inputs in your checkout flow/payment-form.


Question: What are two different ways to integrate the Hosted Fields?
Following are two different way.
1) Drop-in: It is quick way to integrate with braintree, In this payment form is pre-formated.
2) Custom with Hosted Fields: In this, you can do lot of styling customization.



Question: Which browser support the Hosted fields of braintree?
On web, Hosted Fields supports IE 8+ and Safari (OS X and iOS), Firefox, and Chrome (desktop, Android, and iOS).


Question: What is YOUR_CLIENT_TOKEN?
To process anything in client side like create transaction, create customer, update details etc you need a new YOUR_CLIENT_TOKEN.
YOUR_CLIENT_TOKEN is unique random token created from server side(in your application). Following function generate the token?
Braintree_ClientToken::generate();






Monday, 22 June 2015

How to Upgrade PHP 5.3 to PHP 5.4 in WAMP Server in window 7


Adding addons  PHP 5.4 in WAMP Server is quite easy, just you need to follow the following (Works for me).

Please take the backup of code and database before Start.

Please make the backup of php.ini files. When we add addons in wamp server then, we can access the new PHP (php5.4) and old php (php5.x). Both are easily accessible.

Just to need to change the PHP Version like Below:

How to Upgrade PHP 5.3 to PHP 5.4 in WAMP Server in window 7

Let Suppose following:
1) Addin 5.4.42
2) Wamp Server drive is E:


Follow the following steps to upgrade your PHP version.

  1. Download PHP5.4 From http://windows.php.net/download/#php-5.4 (Download Thread Safe)
  2. Go to PHP Folder Location (i.e E:\wamp\bin\php)
  3. Create a new folder with name php5.4.42.
  4. Extract the download files and save in E:\wamp\bin\php\php5.4.42.
  5. Copy the following files from your old PHP directory to your new PHP directory ().
        php.ini
        phpForApache.ini
        wampserver.conf
    
  6. Open new copied php.ini file.
  7. Update the extension_dir path in file.
  8. Open new phpForApache.ini file.
  9. Update the extension_dir path in file.
  10. Reboot your system.
  11. Start wamp Server
  12. Go to wampserver =>PHP=>Version=>PHP 5.4.42
  13. Now running PHP5.4.42
    Note: you might need to Re-enable the PHP extension like CURL, Openssl etc

Saturday, 20 June 2015

New features of PHP 5.5 with Examples


New features of PHP 5.5 with Examples


Following are 5.5 new features.

  1. Generators: has been added via the yield keyword.
    Generators provide an easy way to implement simple iterators.
    For Example:
     function xrange($start, $limit, $step = 1) {
        for ($i = $start; $i <= $limit; $i += $step) {
            yield $i;
        }
      }
      
      echo 'List of odd Numbers:';
      
      foreach (xrange(1, 9, 2) as $number) {
          echo "$number ";
      }
      
  2. finally: keyword added in try catch.
    In try catch, finally block will be called every time, regardless of whether an exception has been thrown or not.
    For Example:
        
        try {
        //write code here 
      }
      catch (Exception $e) {
          //Exception comes here
      }
      finally {
          echo "I am called everytime";
      } 
  3. New password hashing API
    Password hashing API that makes it easier to securely hash and manage passwords using the same crypt() in PHP has been added.
  4. foreach now supports list()
    Now in PHP5.5, You can use list function inside foreach function.
    See Example
     $listArray = [
        [10, 20],
        [30, 40],
        [50, 60],
    ];
    
    foreach($listArray as list($a, $b)) {
        echo "A: $a; B: $b";
    } 
  5. empty() supports expressions
    Now you can use expression in empty function.
    For Example:
      if(!empty(2*3)){
        echo "Its working";
        }
  6. Array and String literal dereferencing.
    String and Array can now be dereferenced directly to access individual elements OR characters.
    For Example
    echo 'Array dereferencing: ';
      echo [10, 02, 30][0];//10
      echo "\n";
      
      echo 'String dereferencing: ';
      echo 'Web Technology'[0]; //W
        
  7. Class name resolution via ::class
    ClassName::class to get a fully qualified name of class ClassName.
    For Example
    namespace Foo;
      class Bar {}
       
      echo Bar::class;
  8. OPcache extension added
    The Zend Optimiser+ opcode cache has been added to PHP5.5 as the new OPcache extension.
  9. foreach now supports non-scalar keys. For non-scalar keys, an Iterator must be used as they cannot occur in native PHP array.
  10. Apache 2.4 handler supported on Windows
  11. Improvements to GD Library.

Friday, 19 June 2015

New features of PHP 5.4 with Examples



Following are 5.4 new features.

  1. Traits has been added. For Example:
     //Create traits
    trait HttpRequest 
    { 
          public function getHttpResponse($url, $port) 
          { 
    
                return $response; 
          } 
    } 
    
    
    //Use the traits
    
    class ABC_API 
    { 
          use HttpRequest; // use our trait 
    
          public function getResponse($url) 
          { 
                return $this->getHttpResponse($url, 80); 
          } 
    } 
  2. Short array syntax has been added. For Example:
    $array = [1,2,3,'Web technology','Experts Notes'];
  3. Function array dereferencing has been added. For Example:
    function fruits(){
    return array(0=>'Apple', 1=>'Banana', 2=>'Mango',3=>'Orange');
    }   
    echo fruits()[2]; //Mango 
  4. Closures now support $this.
  5. Class member can access on instantiation has been added. For Example:
    class test{
      function fruits(){
      return array(0=>'Apple', 1=>'Banana', 2=>'Mango',3=>'Orange');
      }
    }
    print_r((new test())->fruits());
    
    Output:
    Array
    (
        [0] => Apple
        [1] => Banana
        [2] => Mango
        [3] => Orange
    )
  6. Class::{expr}() syntax is now supported. For Example:
    class test{
    static  function newMethod(){
    echo "called function";
    }
    }  
    
    $method = 'newMethod';
    // this works 
    test::$method(); 
    
    // and this works 
    test::{'newMethod'}();
    
  7. Binary number format has been added, e.g. 0b001001101.
  8. Improved parse error messages and improved incompatible arguments warnings.
  9. The session extension can now track the upload progress of files.
  10. Built-in development web server in CLI mode.




Following functions are deprecated in PHP 5.4.

  1. mcrypt_generic_end()
  2. mysql_list_dbs()



Wednesday, 17 June 2015

Braintree payment gateway integration

Braintree payment gateway integration


Braintree is an American company which helps online business by processing credit card for merchants. They have payment gateway which support normal payment, recurring billing and credit card storage. It is a Level 1 PCI-DSS(Payment Card Industry Data Security Standard) compliant service provider. Braintree was founded in 2007 by Bryan Johnson. Latter on it was acquired by eBay.

  Following are characteristics of Braintree.
01. Online payment with Web AND mobile application.
02. Streamlining the onboarding process for US merchants.
03. Venmo Touch which checkout with one touch across multiple mobile applications.
04. Marketplace product which manages the payouts, taxes, compliance and chargebacks.
05. Credit Card Data Portability.
06. Fast deposits to bank account.
07. Support over 40 countries and 130 currencies.
08. Sophisticated sales analytics.
09. No fees for failed transactions.
10. No inactivity fees.
11. Consistent pricing for all card brands.
12. 2.9% + $.30 per transaction.


What is Braintree Marketplace
Braintree Marketplace is part of Braintree that enable to split payment between seller and marketplace.

Following are characteristics of Braintree Marketplace.
01. Easy Compliance.
02. No Extra Fees.
03. Flexibility.
04. Splitting payments.
05. Works for both Web and Mobile.
06. No escrow is required, charge when you need.
07. Its free for merchants and charge only on transactions i.e (2.9% + $.30).
08. Braintree generate 1099-K tax forms required by the IRS.


How Braintree works? 
01. Your web requests a "client token" from your server in order to initialize the JS SDK.
02. Your server generates a token and sends back to your client.
03. Once the JS SDK is initialized, it communicates with Braintree, which returns a "payment method nonce" to your client code.
04. You then send the payment nonce to your server.
05. Your server code receives the "payment method nonce" from your client and then uses the PHP SDK to create a transaction.


Question: What are Payment Methods available in Braintree?
01. Paypal
02.Credit Cards
03. Venmo (With on touch)
04. Apple Pay


Question: What is Payment method nonce?
Payment method nonce: It is string returned by the client SDK (javascript) to represent a payment method.
It is reference to the customer payment method details that were provided in your payment form and used by PHP Server.
Note: Expired in 24 Hour


Question: How to get paymentMethodNonce?
1. Create an account in braintree.
2. Get the merchantId, PublicKey and private Key.
3. Update the merchantId, PublicKey and private Key in following code snippet.
4. Run the code.

A. First get the clientToken from your server
/** Include Library and set configuration**/
require_once '/braintree-php301/lib/Braintree.php';
Braintree_Configuration::environment('sandbox');
Braintree_Configuration::merchantId('xxxxxxxx');//update merchantId
Braintree_Configuration::publicKey('xxxxxxxxxx');//update public key
Braintree_Configuration::privateKey('xxxxxxxxxxxxxxxxxxxxxx'); //Private key

//Get the Client Token
$clientToken = Braintree_ClientToken::generate();

B. Add following following HTML Code.
<script src="https://js.braintreegateway.com/js/beta/braintree-hosted-fields-beta.17.js"></script>
<form action="/payment.php" id="my-sample-form" method="POST">
<label for="card-number">Card Number</label>
      <br />
<div id="card-number">
</div>
<label for="cvv">CVV</label>
      <br />
<div id="cvv">
</div>
<label for="expiration-date">Expiration Date</label>
      <br />
<div id="expiration-date">
</div>
<input type="submit" value="Pay" />
</form>


C. Update the clientToken in following javascript code.
braintree.setup(clientToken, "custom", {
        id: "my-sample-form",
        hostedFields: {
          number: {
            selector: "#card-number"
          },
          cvv: {
            selector: "#cvv"
          },
          expirationDate: {
            selector: "#expiration-date"
          }
        }
      });


OR - Custom Form with Custom URL to get payments
braintree.setup(clientToken, "custom", {
        id: "my-sample-form",
        hostedFields: {
          number: {
            selector: "#card-number",
            placeholder: "Card Number"
          },
          cvv: {
            selector: "#cvv",
            placeholder: "CVV"
          },
          expirationMonth: {
            selector: "#expiration-month",
            placeholder: "Expiration Month"
          },
          expirationYear: {
            selector: "#expiration-year",
            placeholder: "Expiration Year"
          }
        },onPaymentMethodReceived:function(response){
             $.ajax({
                url:'/ajax/braintree-nonce',
                data:'payment_method_nonce='+response.nonce+'&card_digits='+response.details.lastTwo+'&card_type='+response.details.cardType+'&user_id=',
                type:'POST',
                dataType:'json',
                success: function(response) {
                    
                    if(response.success == 1){
                        //write here Code
                    }else{
                       $('#mainSubmitBtn-help').html('Some payment method input fields are invalid. Please try again.').show();
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    //Error Handling
                }
            });
            return false;
            
        },onError:function(response){
              //Error Handling
            
        }
        }); 



Collect above code (A,B and C), In single page and click on "Pay" after filling the cc details

When customer add the credit card detail and submit the form, First request goes to braintree server they do the process and return an unique string with name "payment_method_nonce" to payment.php.
Once get the "payment_method_nonce" from payment.php. Use this token to charge the customer. It is valid upto 24 Hour


Question: How to charge the customer with use of payment_method_nonce token?
/** Include Library and set configuration**/
require_once '/braintree-php301/lib/Braintree.php';
Braintree_Configuration::environment('sandbox');
Braintree_Configuration::merchantId('xxxxxxxxxxxxxxxx');
Braintree_Configuration::publicKey('xxxxxxxxxxxxxxxxx');
Braintree_Configuration::privateKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxx');
/** Include Library and set configuration**/


$paymentMethodNonce ='699dc252-6388-464a-9712-5dd8fa2bb656';
try{ 
          $result = Braintree_Transaction::sale(array(
               'amount' => '1.00',
               'paymentMethodNonce' => paymentMethodNonce,
               'options' => array(
                 'submitForSettlement' => True
               )
             ));
          $transactionId = $result->transaction->id;
          echo "Transaction Id".$transactionId;die;

       }  catch (Exception $e){
           echo $e->getMessage();die;

       }




Tuesday, 16 June 2015

Redirect internal links to another file with .htaccess

Redirect internal links to another file with .htaccess


Requirement:
When someone open http://domain.com/projectone.html, User should be able to see the same URL in Browser(i.e. http://domain.com/projectone.html). But Internally, application should call a file http://domain.com/projectone.php. But user should not get to know this.

Solution:
This is 100% achievable by .htaccess in single line.
But your application must allow and support the .htaccess.
RewriteEngine On
RewriteRule ^(projectone\.html)$  projectone.php [R=301,NC,L]


Following are the means of htacess flag used above.
R 301- means permanent redirect.
NC- means this rule is case -insensitive.
L- mens stop processing to next set, if the rule matches, no further rules will be processed.

Monday, 15 June 2015

Linux and Unix rm command help and examples

rm (short-name for remove) is a command used to remove objects such as files, directories, device nodes, symbolic links etc from the file-system. rm also remove the reference of objects. It works on Linux as well on Unix.


Linux and Unix rm command help and examples

In Actual, rm does not remove any object (file, directories and nodes etc), It just unlink the object from filesystem. That's why file system space may still contain leftover data from the removed file.

Following are rm commands with example.
Delete a single file.
rm filename



Delete all files [USE WITH EXTENSIVE CARE].
rm *



Delete all files which have .txt extension.
rm *.txt 



Delete all files which start with "data" text.
rm data*



Delete a folder (folder must be empty).
rm -d foldername



Delete all recursively. (d-directory, r-recursive).
rm -dr foldername



Delete a file forcefully and will not prompt.
rm -f  filename



Delete the files with prompt (d-directory, r-recursive, i-Prompt before every removal).
rm -dri foldername



Delete the files  without prompt (d-directory, r-recursive, f-without prompt).
rm -drf foldername



Delete the files with without prompt (d-directory, r-recursive, f-without prompt)
rm -drf foldername



Delete the files with single prompt (d-directory, r-recursive, I-single prompt)
rm -drI foldername



Delete the files with details (d-directory, r-recursive, v-explaination)
rm -drv foldername



Delete a file which exist in another folder.
rm /mnt/data/home/project1/public_html/filename.txt 



When we are using multiple options in command, see following:
1) We can exchange the position of option  (Make no difference)
2) We can also give "-" again each option parameter.
3) To Delete a directory recusively, Following commands are valid and are same.
rm -dr foldername
rm -rd foldername
rm -d -r foldername
rm -r -d foldername




Thursday, 11 June 2015

How To Track the Real IP Address Behind the Proxy - PHP - REMOTE_ADDR

How To Track the Real IP Address Behind the Proxy - PHP - REMOTE_ADDR

IP Address: It is unique address of the client machine by which we track the user detail requesting for some request. Full Fom of IP Address is Internet Protocol Address. today, Almost all person know about the ITp Address. This is basically used for tracking.

For Example, If you send an email with your computer. Communication is done on the behalf of IP Address.

Get the Unique IP Address of client machine

function get_ip_address(){
 if ( !empty($_SERVER['HTTP_CLIENT_IP']) )  //check ip from share internet
 {
   $ip = $_SERVER['HTTP_CLIENT_IP'];

 }elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
 {
   $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];

 } else  {

   $ip=$_SERVER['REMOTE_ADDR'];
}

 return $ip;
}

echo get_ip_address();

Tuesday, 9 June 2015

Zend framework Disable the layout and Change the Layout in ZF1

 Zend framework Disable the layout and Change the Layout in ZF1


How to change layout from controller's action?
$this->_helper->layout->setLayout('newLayout');


How to change layout from view file?
$this->layout()->setLayout('newLayout'); 




How to disable the layout from controller's action?
$this->_helper->layout()->disableLayout(); 


How to disable the layout from view file?
$this->layout()->disableLayout(); 


How to disable the view from controller's action?
$this->_helper->viewRenderer->setNoRender(true);



Monday, 8 June 2015

Zend Framework How to delete a table row from foreach loop

Zend Framework How to delete a table row from foreach loop

Scenario: I have list of messages for each user. I want to delete all the messages for an particular user. Here important part is, I don't to do something with deleting each message of user.

Problem: I don't want to use the delete function which creating new query.
As I want to do something with deleting the messages, so i can't delete all record in single query.

Solution: When we list any data from model, there is inbuilt delete function which will delete the current message from foreach loop.

See Example Below
Controller Part here we write the logic
$messageObj = new Application_Model_Messages();
$id=5;
$conds = array('userId=?'=>$id, 'status=?'=>'1', );
$fields = array('id','text');
$messages=$messageObj->getMessages($conds,$fields);
foreach($messages as $message){
    $isDeleted=$message->delete(); //This will delete the current row
    if($isDeleted){
        //you can write here code when each message deleted successfully.
    }
}

here delete(), will delete the current message.

  Model Function which will list of messages of user where each message is an object (Include this function in model).
function getMessages($conds = array(),$fields=array()) {
    try {
        $select = $this->select();
        $select->from(array('m' => 'user_messages'), $fields);
        foreach ($conds as $conIndex => $condValue) {
            $select->where($conIndex, $condValue);
        } 
        $result = $this->fetchAll($select);
        if ($result) {
            return $result;
        } else {
            return FALSE;
        }
    } catch (Exception $e) {
        echo $e->getMessage();
        return FALSE;
    }
}
In this model, you can add condition and  fields dynamically. When calling you can add custom conditions and fields.

Question: How to delete one OR Multiple Record in ZF1.12?
     function deleteRecord($tourId=0) {
         return $this->delete(array('tour_id=?' => $tourId));
    }





Sunday, 7 June 2015

Load multiple javascript files asynchronously

load multiple javascript files asynchronously



In Every website, We have to include the JavaScript. We need to include multiple JavaScript file in single web page.

It's always prefer to include the javascript at the bottom of the page so that loading of content remain fast. So we should add at the bottom of the page.

We should also load the JavaScript files asynchronously, means load JavaScript file parallel.


There are two ways to load JavaScript file. Newer browsers have async attribute which load JavaScript asynchronously.
<scritp async="true" src="yourscript.js" type="text/javascript"></scritp>

Use custom JavaScript function to load javascript-file asynchronously.


<script type="text/javascript">
function loadScript (scriptpath){
    var s=document.getElementsByTagName('script')[0];
    var ss=document.createElement('script');
    ss.type='text/javascript';
    ss.async=true;
    ss.src= scriptpath;
    s.parentNode.insertBefore(ss,s);
}
</script>

Just call the loadScript function to load javascript file asynchronously. For Example.
<script type="text/javascript">
loadScript('/js/jQueryJSFIle1.js');
loadScript('/js/jQueryJSFIle2.js');
loadScript('/js/jQueryJSFIle3.js');
</script> 

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





Monday, 1 June 2015

Differences between Stored Procedures and Functions in MYSQL

Differences between Stored Procedures and Functions in MYSQL

  1. Stored Procedure can return zero or n values whereas function can return one value which is mandatory.
  2. Functions can be called from procedure whereas procedures cannot be called from function.
  3. Procedures can have input/output parameters for it whereas functions can have only input parameters.
  4. Procedure allows select as well as DML statement in it whereas function allows only select statement in it.
  5. Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
  6. We can go for transaction management in procedure whereas we can't go in function.
  7. Procedures can not be utilized in a select statement whereas function can be embedded in a select statement.