Tuesday, 19 February 2019

Default .htaccess file for all sites

ErrorDocument 404 /404.php
<IfModule mod_rewrite.c>
 
   RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R] # <- for test, for prod use [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php




</IfModule>





Wednesday, 13 June 2018

Set cron job on cpanel

*/5 * * * * php -q /home/checkin/public_html/staging/webservices/cron-job.php

Tuesday, 24 April 2018

deny direct access to a folder and file by htaccess

<Files ~ "^.*">
  Deny from all
</Files>

<Files ~ "^index\.php|css|js|.*\.png|.*\.jpg|.*\.gif|.*\.JPG|.*\.jpeg">
  Allow from all
</Files>

Friday, 23 February 2018

How to redirect on http to https and www to no www

1.) Redirect http to https :-

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

2.) Redirect wwwto no www :-

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.com [NC]
RewriteRule ^(.*)$ https://domain.com/$1 [L,R=301]

Wednesday, 12 July 2017

Get city name from latitude longitude in php

function getcityname($latitude,$longitude) // get city name from lat long.
{
$geolocation = $latitude.','.$longitude;
$request = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false';
$file_contents = file_get_contents($request);
$json_decode = json_decode($file_contents);
if(isset($json_decode->results[0])) {
    $response = array();
    foreach($json_decode->results[0]->address_components as $addressComponet) {
        if(in_array('political', $addressComponet->types)) {
                $response[] = $addressComponet->long_name;
        }
    }

    if(isset($response[0])){ $first  =  $response[0];  } else { $first  = 'null'; }
    if(isset($response[1])){ $second =  $response[1];  } else { $second = 'null'; }
    if(isset($response[2])){ $third  =  $response[2];  } else { $third  = 'null'; }
    if(isset($response[3])){ $fourth =  $response[3];  } else { $fourth = 'null'; }
    if(isset($response[4])){ $fifth  =  $response[4];  } else { $fifth  = 'null'; }

    if( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth != 'null' ) {
         $city = $second;
    }
    else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth != 'null' && $fifth == 'null'  ) {
         $city = $second;
    }
    else if ( $first != 'null' && $second != 'null' && $third != 'null' && $fourth == 'null' && $fifth == 'null' ) {
        $city = $first;
    }
    else if ( $first != 'null' && $second != 'null' && $third == 'null' && $fourth == 'null' && $fifth == 'null'  ) {
       $city = $first;
     
    }
return $city;
  }

}

Friday, 26 May 2017

Magento fax field replace with mobile number

Open file app/locale/en_US/Mage_Page.csv 
Paste the below code at last line
"Fax","Mobile"

For changes in admin panel Go to admin->system->configuration-> customer configuration 
And open the address template tab. Then replace all F (Fax) With (Mobile) in all tabs
1. Text
2. HTML
3. PDF
4. JavaScript Template
The changes will be work on all order,invoice,shipment history and email all places.

Magento Set reviews limit on product page

Copy /app/code/core/Mage/Review/Block/Product/View/View.php to
 /app/code/local/Mage/Review/Block/Product/View.php. with following code :-

Find the function getReviewsCollection() and replce with below function.

public function getReviewsCollection()
    {
        if (null === $this->_reviewsCollection) {
            $this->_reviewsCollection = Mage::getModel('review/review')->getCollection()
                ->addStoreFilter(Mage::app()->getStore()->getId())
                ->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
                ->addEntityFilter('product', $this->getProduct()->getId())
                ->setDateOrder();
                $this->_reviewsCollection->getSelect()->limit(5);
        }
        return $this->_reviewsCollection;
    }

Add Payment Method Custom column in admin > sales > order

1.)  Copy /app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php to
 /app/code/local/Mage/Adminhtml/Block/Sales/Order/Grid.php. 

And replace with this function.

protected function _prepareCollection()
    {
         $collection = Mage::getResourceModel($this->_getCollectionClass());
         $collection->join(array('payment'=>'sales/order_payment'),'main_table.entity_id=parent_id','method');
         $this->setCollection($collection);
         return Mage_Adminhtml_Block_Widget_Grid::_prepareCollection();
         // end here //
    }

2.)  Search the function _prepareColumns() and add below code in this function
 

$payments = Mage::getSingleton('payment/config')->getActiveMethods();

        $methods = array();
        foreach ($payments as $paymentCode=>$paymentModel)
        {
                $paymentTitle = Mage::getStoreConfig('payment/'.$paymentCode.'/title');
                $methods[$paymentCode] = $paymentTitle;
        }

        $this->addColumn('method', array(
                'header' => Mage::helper('sales')->__('Payment Method'),
                        'index' => 'method',
                        'filter_index' => 'payment.method',
                        'type'  => 'options',
                        'width' => '70px',
                        'options' => $methods,
                ));
        // End here

Tuesday, 21 February 2017

how to change usps shipping method title in magento

First open the below directory file

app/code/core/Mage/Sales/Model/Quote/Address/Rate.php

Please replace


->setMethodTitle($rate->getMethodTitle())

with

->setMethodTitle(Mage::helper('shipping')->__($rate->getMethodTitle()))

And Make changes into the Mage_Shipping.csv file as you wish.

Thursday, 19 January 2017

New XAMPP security concept

Access forbidden!

Access to the requested directory is only available from the local network.

This setting can be configured in the file "httpd-xampp.conf".


This is an error mostly shows on xampp server. let’s discuss how to access Phpmyadmin when not accessible in network or using ip on xampp.

Error:- Access forbidden! New XAMPP security concept: Access to the requested object is only available from the local network.
This setting can be configured in the file httpd-xampp.conf.

This is because there are some new security issue applied so we can access it only on local pc not to full network or using ip. For access phpmyadmin using ip or on network you need to change some configuration.

1. Go to :- D:\xampp\apache\conf\extra\httpd-xampp.conf
2. Paste below code in the end of file

<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
 #       Require local
Require all granted
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Thursday, 5 January 2017

How to use Google reCAPTCHA in PHP

Google has discharged the new reCAPTCHA. Utilizing reCAPTCHA clients can demonstrate they are human without understanding a CAPTCHA. They require only a solitary snap to affirm they are not a robot. In this way, reCAPTCHA will shield your site from spam with better client encounter. You can without much of a stretch incorporate Google reCAPTCHA in PHP script.

We have made a contact frame with the new Google reCAPTCHA utilizing PHP. Investigate the demo of Google reCAPTCHA in PHP from the Demo connect. The reCAPTCHA joining procedure is given underneath.



Get reCAPTCHA api keys:

For adding reCAPTCHA to your site, you have to enlist your site and get reCAPTCHA API keys.

Enlist your site at Google from here – https://www.google.com/recaptcha/admin



Get your site key that's used to display the reCAPTCHA widget.

Get your Secret key helps authorizes communication between your site and the reCAPTCHA server.

Html Code :-

<script src="https://www.google.com/recaptcha/api.js" async defer></script>


<form action="" method="POST">
    <input type="text" name="name" value="" />
    <input type="text" name="email" value="" />
    <textarea type="text" name="message"></textarea>
    <div class="g-recaptcha" data-sitekey="9ABCGUTKOHdJnGhsKH--DDHD"></div>
    <input type="submit" name="submit" value="SUBMIT">

</form>

Php Code :- 

<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])):
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
        //your site secret key
        $secret = '6LeXrhAUAAAAAMnkNXY0S8AyUI0vklLR5jaSfK5L';
        //get verify response data
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
        $responseData = json_decode($verifyResponse);
        if($responseData->success):
            //contact form submission code
            $name = !empty($_POST['name'])?$_POST['name']:'';
            $email = !empty($_POST['email'])?$_POST['email']:'';
            $message = !empty($_POST['message'])?$_POST['message']:'';
         
            $to = 'yogi.lalit2391@gmail.com';
            $subject = 'New contact form have been submitted';
            $htmlContent = "
                <h1>Contact request details</h1>
                <p><b>Name: </b>".$name."</p>
                <p><b>Email: </b>".$email."</p>
                <p><b>Message: </b>".$message."</p>
            ";
         
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
         
            $headers .= 'From:'.$name.' <'.$email.'>' . "\r\n";
         
            @mail($to,$subject,$htmlContent,$headers);
         
            $succMsg = 'Your form have submitted successfully.';
        else:
            $errMsg = 'Invalid captcha value.';
        endif;
    else:
        $errMsg = 'Please click on the reCAPTCHA box.';
    endif;
else:
    $errMsg = '';
    $succMsg = '';
endif;

?>

Friday, 30 December 2016

How to disable dates in jQuery DatePicker

<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  /* create an array of days which need to be disabled */
var array = ["2016-12-14","2016-12-15","2016-12-16","2017-02-16"];

$(function() {
    $("#datepicker").datepicker({
        beforeShowDay: function(date){
        var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
        return [ array.indexOf(string) == -1 ]
    }
    });

});

  </script>
<body>
Date: <div id="datepicker"></div>
</body>

Wednesday, 23 November 2016

Magento remove shipping methods if free shipping available

The following code will hide the other shipping methods from the shopping cart page, the default magento checkout and one page checkout.

The file you need to adjust is:

app/ design/ frontend/ default/YOURTEMPLATE/ template/ checkout/ onepage/ shipping_method/ available.phtml

<?php if ( array_key_exists('freeshipping', $_shippingRateGroups )) { $_shippingRateGroups = array('freeshipping' => $_shippingRateGroups['freeshipping']); } ?>

place this code right before the <dl> tag that displays the different options.

Friday, 18 November 2016

Magento how to get first item or last item from the collection ?

$collection->getFirstItem() and $collection->getLastItem();

Magento how will you log current collection’s SQL query?

$collection->printLogQuery(true); OR $collection->getSelect()->__toString();

Magento where is the relation between configurable product and it’s simple product stored in database?

In the 2 tables:

1. catalog_product_relation
2. catalog_product_superlink_table

What can you do to optimize Magento performance?

Tweak .htaccess for performance optimization in Magento. It will not sky rocket your website, but will show notable improvement. The default Magento .htaccess comes with performance optimization, but commented by default. I will show you here which lines to uncomment and improve the performance.

Compressing web pages with mod_deflate

The mod_deflate module allows the Apache2 web service to compress files and deliver them to browser that can handle them. With mod_deflate you can compress HTML, text or XML files by upto 70% of their original sizes! Thus, saving you server traffic and speeding up page loads.

Check your .htaccess file for below code, I have removed hashes before few lines to uncomment them for performance.

<IfModule mod_deflate.c>

############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip

    # Insert filter on all content
    SetOutputFilter DEFLATE
    # Insert filter on selected content types only
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript

    # Netscape 4.x has some problems...
    BrowserMatch ^Mozilla/4 gzip-only-text/html

    # Netscape 4.06-4.08 have some more problems
    BrowserMatch ^Mozilla/4\.0[678] no-gzip

    # MSIE masquerades as Netscape, but it is fine
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

    # Don't compress images
    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary

    # Make sure proxies don't deliver the wrong content
    Header append Vary User-Agent env=!dont-vary

</IfModule>

Enabling expires header with mod_expires

<IfModule mod_expires.c>

############################################
## Add default Expires header
## http://developer.yahoo.com/performance/rules.html#expires
ExpiresActive On
    ExpiresDefault "access plus 1 year"

</IfModule>

What are the different design patterns used in Magento?

Factory:
It implement the concept of factories and deals with the problem of creating objects without specifying the exact class of object that will be created.

1 $product = Mage::getModel('catalog/product');

Singleton:

It restricts the instantiation of a class to one object. It will refer to same object each time called.
1 $category = Mage::getSingleton('catalog/session');

Registry:

It is a way to store information throughout your application.
Mage::register('key',$value); //stores
$currentCategory = Mage::registry('key'); //retrives

Prototype:

It determines the type of object to create. In Magento it can be Simple, Configurable, Grouped, Bundle, Downloadable or Virtual types.

Mage:getModel('catalog/product')->getTypeInstance();

Observer:

It is mainly used to implement distributed event handling systems. Here the subject maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

Mage::dispatchEvent('event_name', array('key'=>$value));
<config>
    <global>
        <events>
            <event_name>
                <observers>
                    <unique_name>
                        <class>Class_Name</class>
                        <method>methodName</method>
                    </unique_name>
                </observers>
            </event_name>
        </events>
    </global>
</config>

Object Pool:

It is used to reuse and share objects that are expensive to create.
$id = Mage::objects()->save($object);
$object = Mage::objects($id);

Iterator:

It is used to traverse a collection and access the collection’s items.
Mage::getModel('catalog/product')->getCollection();

Lazy Loading:

It is used to defer initialization of an object until the point at which it is needed.
$collection_of_products = Mage::getModel('catalog/product')
->getCollection();

Helper:

Multiple methods are available for use by other objects. Here you can use core’s helper methods from anywhere in the application.
Mage::helper('core');

Service Locator:

Allows overrides or renamed physical resources (e.g. Classes, DB tables, etc)
Mage::getModel('catalog/product') and $installer->getTable('customer/address_entity');

Magento what are the commonly used block types? What is the special in core/text_list block type.

Commonly used block types: core/template, page/html, page/html_head, page/html_header, page/template_links, core/text_list, page/html_wrapper, page/html_breadcrumbs, page/html_footer, core/messages, page/switch.

Some blocks like content, left, right etc. are of type core/text_list. When these blocks are rendered, all their child blocks are rendered automatically without the need to call getChildHtml() method.

Explain different types of sessions in Magento and the reason why you store data in different session types?

Customer sessions stores data related to customer, checkout session stores data related to quote and order. They are actuall under one session in an array. So firstname in customer/session will be $_SESSION['customer']['firstname'] and cart items count in checkout/session will be $_SESSION['checkout']['items_count']. The reason Magento uses session types separately is because once the order gets placed, the checkout session data information should get flushed which can be easily done by just unsetting $_SESSION['checkout'] session variable. So that the session is not cleared, just session data containing checkout information is cleared and rest all the session types are still intact.