Monday 30 December 2019

How to solve product changes not reflecting on frontend after updating from admin in Magento 2

Please execute below queries if you are not able to fix the issue using bin/magento indexer:reindex command

Please note : this is only tested for single stores

DELETE FROM catalog_product_entity_text where store_id != 0;
DELETE FROM catalog_product_entity_datetime where store_id != 0;
DELETE FROM catalog_product_entity_decimal where store_id != 0;
DELETE FROM catalog_product_entity_int where store_id != 0;
DELETE FROM catalog_product_entity_varchar where store_id != 0;

Wednesday 25 December 2019

How to get product Review star in phtml in magento 2

<?php

namespace Custom\Cmenu\Block;

use Magento\Catalog\Api\CategoryRepositoryInterface;

class Category extends \Magento\Framework\View\Element\Template
{

    protected $_productRepository;
    protected $_reviewFactory;
    protected $_ratingCollection;


    public function __construct(
        \Magento\Catalog\Model\ProductRepository $productRepository,
        \Magento\Review\Model\ReviewFactory $reviewFactory,
        \Magento\Review\Model\ResourceModel\Review\Summary\Collection $ratingCollection,
        \Magento\Framework\View\Element\Template\Context $context,
        array $data = []
    ) {
        $this->_productRepository = $productRepository;
        $this->_reviewFactory = $reviewFactory;
        $this->_ratingCollection = $ratingCollection;
        parent::__construct($context);
    }


    public function getRatingSummary($product)
    {

       
        //$product = $this->_productloader->create()->load($id); // follow the link for this
       
        $this->_reviewFactory->create()->getEntitySummary($product, 1);
       
        $ratingSummary = $product->getRatingSummary()->getRatingSummary();

        return $ratingSummary;
    }
}

----------------- PHTML page --------------------------------------

    <?php
    $category = $block->getLayout()->createBlock('Custom\Cmenu\Block\Category'); ?>

 <?php
        //pass $product object as argument...
        $_ratingSummary = $block->getRatingSummary($product);
       
    ?>
    <?php if($_ratingSummary){ ?>
    <div class="product-reviews-summary short">
        <div class="rating-summary">
            <div title="<?php echo (int)$_ratingSummary; ?>%" class="rating-result">
                <span style="width:<?php echo (int)$_ratingSummary; ?>%"><span><?php echo (int)$_ratingSummary; ?>%</span></span>
            </div>
        </div>
     
    </div>
    <?php } ?>

Monday 23 December 2019

How to create Multi Website/Stores simlinks in magento 2



1) Create a new folder in magento root and copy the index.php and .htaccess files from magento root to new folder.

2) Edit the index.php which is in new folder

Replace:

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

/** @var \Magento\Framework\App\Http $app */

$app = $bootstrap->createApplication('Magento\Framework\App\Http');

$bootstrap->run($app);

Created multi website in magento, Steps to create a multistore in admin panel is same as like in magento1.x. Don't forget to change the base url and secure url for new website/store. Once made changes in admin panel follow the below steps,

1) Create a new folder in magento root and copy the index.php and .htaccess files from magento root to new folder.

2) Edit the index.php which is in new folder

Replace:

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

/** @var \Magento\Framework\App\Http $app */

$app = $bootstrap->createApplication('Magento\Framework\App\Http');

$bootstrap->run($app);
With:

$params = $_SERVER;

$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = 'newstore'; //Webite code as same in admin panel

$params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = 'website';

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);

/** @var \Magento\Framework\App\Http $app */

$app = $bootstrap->createApplication('Magento\Framework\App\Http');

$bootstrap->run($app);

And also update bootstrap.php include path as below,

Replace:

require __DIR__ . '/app/bootstrap.php';
With:

require __DIR__ . '/../app/bootstrap.php';


3) Create a simlinks inside the new folder

ln -s from path/app to path/app

ln -s from path/lib to path/lib

ln -s from path/pub to path/pub

ln -s from path/var to path/var

For example /var/www/html/app cnsv/app

Saturday 21 December 2019

Coupon is always re-added during checkout in magento 1.9


I encountered the following bug

Add a product to cart
Apply a coupon code
Remove coupon code
Coupon code is not shown anymore / remove successful
Go in checkout
Continue billing and shipping step
Go back in cart
Coupon code of step #2 is active again
magento magento-1.9


I solved it by event/observer

<events>
        <controller_action_predispatch_checkout_cart_couponPost>
            <observers>
                <remove_session_coupon_code>
                    <type>singleton</type>
                    <class>yourmodule/observer</class>
                    <method>removeCoupon</method>
                </remove_session_coupon_code>
            </observers>
        </controller_action_predispatch_checkout_cart_couponPost>
    </events>


public function removeCoupon(Varien_Event_Observer $observer)
{
    $controller = $observer->getControllerAction();
    if ($controller->getRequest()->getParam('remove') == 1) {
        Mage::getSingleton("checkout/session")->unsetData('cart_coupon_code');
    }
    return $this;
}

Tuesday 17 December 2019

how to connect ssh by pem file aws server

1. Requirement : .ppk or .pem key file
2. If you have .ppk file. It is required to change it to .pem file as it is the key format supported by Linux.
You need putty tools for generating .pem file from .ppk.
Install putty tools : sudo apt-get install putty-tools
Go to the directory of the .ppk file and run the following command : puttygen [filename].ppk -O private-openssh -o [filename].pem
3. Now you have the .pem file. It is needed to be added to the linux known hosts.
Run the following command : ssh-add [filename].pem
4. Now connect to AWS using linux in built 'Connect to Server' -> Type(SSH). You don't need to add password.

Friday 6 December 2019

How to show address field in registration form in magento 2?

Hi first find magento root folder then vendor\magento\module-customer\view\frontend\layout customer_account_create.xml.
Then copy the file and related theme folder. For example path /app/design/frontend/vendor name /Theme Name/Magento_Customer/layout/customer_account_create.xml
then go to line no 13 check this code and put billow section on line no


 <referenceContainer name="content">
            <block class="Magento\Customer\Block\Form\Register" name="customer_form_register" template="form/register.phtml">
                <container name="form.additional.info" as="form_additional_info"/>
                <container name="customer.form.register.fields.before" as="form_fields_before" label="Form Fields Before" htmlTag="div" htmlClass="customer-form-before"/>
                <action method="setShowAddressFields">
                    <argument name="show.address.fields" xsi:type="boolean">true</argument>
                </action>
            </block>
            <block class="Magento\Cookie\Block\RequireCookie" name="require-cookie" template="Magento_Cookie::require_cookie.phtml">
                <arguments>
                    <argument name="triggers" xsi:type="array">
                        <item name="registerSubmitButton" xsi:type="string">.action.submit</item>
                    </argument>
                </arguments>
            </block>
        </referenceContainer>

Monday 2 December 2019

Function mcrypt_module_open() is deprecated in Magento 2

Function mcrypt_module_open() is deprecated from PHP version 7.1. If you are using PHP 7.1 or higher for your Magento 2 website then you might face this error.
NOTE: This error is already solved by Magento in 2.2 and higher version.

Solution: Add @ sign before all below functions.

Below is one example.
$this->_handle = mcrypt_module_open($cipher, '', $mode, '');
Becomes
$this->_handle = @mcrypt_module_open($cipher, '', $mode, '');

Sunday 24 November 2019

How to Call CMS Static Block in Phtml File in magento 2

Display CMS Static Block In Phtml File:
<?php
    echo $block->getLayout()
               ->createBlock('Magento\Cms\Block\Block')
               ->setBlockId('block_identifier')
               ->toHtml();
?>

Tuesday 19 November 2019

Magento2 cannot load some transaction emails

error : main.CRITICAL: Zend_Json_Exception: Decoding failed: Syntax error in /home/forge/domain.com/vendor/magento/zendframework1/library/Zend/Json.php:97

This is a bug in Magento 2 and here is the solution:
This will fixed the invalid json objects in the order email templates.

See this on vendor/magento/module-sales/view/frontend/email/order_new.html file.

<!--@vars { "var formattedBillingAddress|raw":"Billing Address", "var order.getEmailCustomerNote()":"Email Order Note", "var order.increment_id":"Order Id", "layout handle=\"sales_email_order_items\" order=$order area=\"frontend\"":"Order Items Grid", "var payment_html|raw":"Payment Details", "var formattedShippingAddress|raw":"Shipping Address", "var order.getShippingDescription()":"Shipping Description" "var shipping_msg":"Shipping message" } @-->

Take a look at this line:

"var order.getShippingDescription()":"Shipping Description"

It needs comma (,) at the end of this line to make it work. So it goes with the other files or template files.

So it should be like this:

<!--@vars { "var formattedBillingAddress|raw":"Billing Address", "var order.getEmailCustomerNote()":"Email Order Note", "var order.increment_id":"Order Id", "layout handle=\"sales_email_order_items\" order=$order area=\"frontend\"":"Order Items Grid", "var payment_html|raw":"Payment Details", "var formattedShippingAddress|raw":"Shipping Address", "var order.getShippingDescription()":"Shipping Description", "var shipping_msg":"Shipping message" } @-->

Monday 18 November 2019

Discount not applied to Grand Total in magento 1.9

We fixed this by adding the following into /app/code/core/Mage/Sales/etc/config.xml sales/quote section.

<discount>
   <class>sales/order_invoice_total_discount</class>
    <after>subtotal</after>
</discount>

This is a terrible solution, obviously, and I have no idea why it is needed. We will have to research it further to come up with a better solution than editing a core file!

Tuesday 12 November 2019

Creating profile image module in magento 2



  1. Create folders under magento root
<magento root>/code/<vendor>/<module>/

  1. Create a file ‘registration.php’ and put the below contents in it
\Magento\Framework\Component\ComponentRegistrar::register(\Magento\Framework\Component\ComponentRegistrar::MODULE,'<vendor>_<module>',__DIR__);

  1. Create folder ‘etc’ and create file ‘module.xml’ in it,, and put the below content in it.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="<vendor>_<module>" setup_version="1.0.0">
</module>
</config>

  1. Create a route for the controllers which are needed to be made. Create e folder ‘frontend’ in etc folder and create file ‘routes.xml’ in it, and enter the following details in it.
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route frontName="<route_path>" id="<route_path>">
<module name="<vendor>_<module>"/>
</route>
</router>
</config>

  1. Create folder ‘Controller’ and create two folder in it.
Delete’ and ‘Index’. Create Index.php in both of it.

  1. In Delete -> Index.php , paste the following code

namespace <vendor>\<module>\Controller\Delete;

use Magento\Framework\App\Filesystem\DirectoryList;

class Index extends \Magento\Framework\App\Action\Action
{
protected $_filesystem;
protected $image;
protected $_file;

public function __construct(
\Magento\Framework\App\Action\Context $context,
\<vendor>\<module>\Block\Imageprofile $image,
\Magento\Framework\Filesystem\Driver\File $file,
\Magento\Framework\Filesystem $fileSystem
) {
parent::__construct($context);
$this->image = $image;
$this->_file = $file;
$this->_filesystem = $fileSystem;

}

public function execute(){

$fileName = 'IMG_'.$this->image->currentUser()->getId();
$mediaRootDir = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('images/'.$this->image->currentUser()->getId().'/');
if ($this->_file->isExists($mediaRootDir.$fileName)) {
$this->_file->deleteFile($mediaRootDir.$fileName);
}
$this->_redirect('customer/account/');
}
}

  1. In Index -> Index.php , paste the following code

namespace <vendor>\<module>\Controller\Index;

use Magento\Framework\App\Filesystem\DirectoryList;


class Index extends \Magento\Framework\App\Action\Action
{
protected $_filesystem;
protected $image;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Filesystem $fileSystem,
\<vendor>\<module>\Block\Imageprofile $image
) {
parent::__construct($context);
$this->_filesystem = $fileSystem;
$this->image = $image;
}
public function execute()
{
$result = array();
if ($_FILES['profile_image']['name']) {
try {
// init uploader model.
$uploader = $this->_objectManager->create(
'Magento\MediaStorage\Model\File\Uploader',
['fileId' => 'profile_image']
);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png']);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
// get media directory
$mediaDirectory = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA);
// save the image to media directory
$result = $uploader->save($mediaDirectory->getAbsolutePath('images/'.$this->image->currentUser()->getId().'/'),'IMG_'.$this->image->currentUser()->getId());
} catch (Exception $e) {
\Zend_Debug::dump($e->getMessage());
}
}
$this->_redirect('customer/account/');
//echo "Hello";
}
}


  1. Finally create a folder named ‘Block’ and create a file ‘Imageprofile.php’ in it. Paste the following code in it.

namespace <vendor>\<module>\Block;

use Magento\Framework\App\Filesystem\DirectoryList;

class Imageprofile extends \Magento\Framework\View\Element\Template
{
protected $customerSession;
protected $_file;

public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\Filesystem\Driver\File $file,
array $data = []
)
{
parent::__construct($context,$data);
$this->customerSession = $customerSession;
$this->_file = $file;
}
public function currentUser()
{
return $this->customerSession->getCustomer();//->getId();
}

public function getMediaUrl()
{
$mediaUrl = $this->_storeManager
->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
return $mediaUrl;
}

public function checkExist()
{
$filename = 'IMG_'.$this->currentUser()->getId();
$filepath = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath('images/'.$this->currentUser()->getId().'/');
if ($this->_file->isExists($filepath.$filename)) {
return 1;
}else{
return 0;
}
//return $filepath.$filename;
}

}

Thursday 10 October 2019

Creating symlink using command line

ln -s <Full path of source folder> <Full path of destination folder>

For example: symlink for var folder under cnsv folder

ln -s /var/www/html/var /var/www/html/cnsv

Wednesday 25 September 2019

How to open aws server in Linux local system by ppk or pem file

1. Requirement : .ppk or .pem key file
2. If you have .ppk file. It is required to change it to .pem file as it is the key format supported by Linux.
You need putty tools for generating .pem file from .ppk.
Install putty tools : sudo apt-get install putty-tools
Go to the directory of the .ppk file and run the following command : puttygen [filename].ppk -O private-openssh -o [filename].pem
3. Now you have the .pem file. It is needed to be added to the linux known hosts.
Run the following command : ssh-add [filename].pem
4. Now connect to AWS using linux in built 'Connect to Server' -> Type(SSH). You don't need to add password. 

Tuesday 27 August 2019

how to remove estimate shipping and tax in magento 2

checkout_cart_index.xml
<referenceBlock name="checkout.cart.shipping">
<arguments>
<argument name="jsLayout" xsi:type="array">
<item name="components" xsi:type="array">
<item name="block-summary" xsi:type="array">

<!-- My custom part: -->
<item name="config" xsi:type="array">
<item name="componentDisabled" xsi:type="boolean">true</item>
</item>

</item>
</item>
</argument>
</arguments>
</referenceBlock>



===================================
cart/shipping.phtml

<div class="title" data-role="title">
    <strong id="block-shipping-heading" role="heading" aria-level="2">
        <?php / @escapeNotVerified / echo $block->getQuote()->isVirtual() ? _('Estimate Tax') : _('Estimate Shipping and Tax') ?>
    </strong>
</div>

Friday 23 August 2019

How to upgrade magento 2.X to 2.X?

Step 1: Access Your Server via SSH

You need to connect your server via SSH.

Step 2: Navigate to the Magento 2 Root Directory

Once your SSH connection is up, you will need to move to your target application folder. In that application folder, you will find the public_html folder which is the root directory of Magento 2.

Step 3: Upgrade Commands

composer require magento/product-community-edition 2.1.9 --no-update

composer update
rm -rf var/di var/generation
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento indexer:reindex

Tuesday 30 July 2019

How to make auto select first child product of configurable product in magento2?


Override this file to your theme:
vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js

your theme file location will be:
app/design/frontend/[vendor]/[theme]/Magento_ConfigurableProduct/web/js/configurable.js

_fillSelect: function (element) {
    var attributeId = element.id.replace(/[a-z]*/, ''),
        options = this._getAttributeOptions(attributeId),
        prevConfig,
        index = 1,
        allowedProducts,
        i,
        j;

    this._clearSelect(element);
    element.options[0] = new Option('', '');
    element.options[0].innerHTML = this.options.spConfig.chooseText;
    prevConfig = false;

    if (element.prevSetting) {
        prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
    }

    if (options) {
        for (i = 0; i < options.length; i++) {
            allowedProducts = [];
            if (prevConfig) {
                for (j = 0; j < options[i].products.length; j++) {
                    // prevConfig.config can be undefined
                    if (prevConfig.config &&
                        prevConfig.config.allowedProducts &&
                        prevConfig.config.allowedProducts.indexOf(options[i].products[j]) > -1) {
                        allowedProducts.push(options[i].products[j]);
                    }
                }
            } else {
                allowedProducts = options[i].products.slice(0);
            }

            if (allowedProducts.length > 0) {
                options[i].allowedProducts = allowedProducts;
                element.options[index] = new Option(this._getOptionLabel(options[i]), options[i].id);
                if (typeof options[i].price !== 'undefined') {
                    element.options[index].setAttribute('price', options[i].prices);
                }

                element.options[index].config = options[i];




                index++;
            }
            // Code added to select option
            if (i == 0) {
                this.options.values[attributeId] = options[i].id;
            } 
        }
        //Code added to check if configurations are set in url and resets them if needed
        if (window.location.href.indexOf('#') !== -1) {this._parseQueryParams(window.location.href.substr(window.location.href.indexOf('#') + 1));}
    }

},

===================================================================
For Swatch: Override the below file to your theme

/module-swatches/view/frontend/web/js/SwatchRenderer.js

_RenderControls: function () {
    var $widget = this,
        container = this.element,
        classes = this.options.classes,
        chooseText = this.options.jsonConfig.chooseText,
        selectedArray = []; // Variable declation for autoselect element array

    $widget.optionsMap = {};

    $.each(this.options.jsonConfig.attributes, function () {
        var item = this,
            controlLabelId = 'option-label-' + item.code + '-' + item.id,
            options = $widget._RenderSwatchOptions(item, controlLabelId),
            select = $widget._RenderSwatchSelect(item, chooseText),
            input = $widget._RenderFormInput(item),
            listLabel = '',
            label = '';

        // Show only swatch controls
        if ($widget.options.onlySwatches && !$widget.options.jsonSwatchConfig.hasOwnProperty(item.id)) {
            return;
        }

        if ($widget.options.enableControlLabel) {
            label +=
                '<span id="' + controlLabelId + '" class="' + classes.attributeLabelClass + '">' +
                    item.label +
                '</span>' +
                '<span class="' + classes.attributeSelectedOptionLabelClass + '"></span>';
        }

        if ($widget.inProductList) {
            $widget.productForm.append(input);
            input = '';
            listLabel = 'aria-label="' + item.label + '"';
        } else {
            listLabel = 'aria-labelledby="' + controlLabelId + '"';
        }

        // Create new control
        container.append(
            '<div class="' + classes.attributeClass + ' ' + item.code + '" ' +
                 'attribute-code="' + item.code + '" ' +
                 'attribute-id="' + item.id + '">' +
                label +
                '<div aria-activedescendant="" ' +
                     'tabindex="0" ' +
                     'aria-invalid="false" ' +
                     'aria-required="true" ' +
                     'role="listbox" ' + listLabel +
                     'class="' + classes.attributeOptionsWrapper + ' clearfix">' +
                    options + select +
                '</div>' + input +
            '</div>'
        );

        $widget.optionsMap[item.id] = {};

        // Aggregate options array to hash (key => value)
        $.each(item.options, function () {
            if (this.products.length > 0) {
                $widget.optionsMap[item.id][this.id] = {
                    price: parseInt(
                        $widget.options.jsonConfig.optionPrices[this.products[0]].finalPrice.amount,
                        10
                    ),
                    products: this.products
                };
            }
        });
        //Create array for Autoselect swatch
        selectedArray.push($widget.element.find('[attribute-id=' + item.id + '] .swatch-option')[0]);
    });


    // Connect Tooltip
    container
        .find('[option-type="1"], [option-type="2"], [option-type="0"], [option-type="3"]')
        .SwatchRendererTooltip();

    // Hide all elements below more button
    $('.' + classes.moreButton).nextAll().hide();

    // Handle events like click or change
    $widget._EventListener();

    // Rewind options
    $widget._Rewind(container);

    //Emulate click on all swatches from Request
    $widget._EmulateSelected($.parseQuery());
    $widget._EmulateSelected($widget._getSelectedAttributes());

    //Trigger click for Autoselect first option swatch
    $.each(selectedArray, function () {
        if(this != undefined) this.click();
    });

},


Friday 26 July 2019

How to create a new administrator account through SSH in Magento 2

php bin/magento admin:user:create --admin-user='ayurvuser' --admin-password='admin#123' --admin-email='admin@ytd.com' --admin-firstname='Test' --admin-lastname='Tester'

Monday 15 July 2019

Magento 2 folder/file permissions command line

You should set as bellow recommended.

cd <your Magento install dir>

find . -type f -exec chmod 644 {} \;                        // 644 permission for files

find . -type d -exec chmod 755 {} \;                        // 755 permission for directory

find ./var -type d -exec chmod 777 {} \;                // 777 permission for var folder   

find ./pub/media -type d -exec chmod 777 {} \;

find ./pub/static -type d -exec chmod 777 {} \;

chmod 777 ./app/etc

chmod 644 ./app/etc/*.xml

chown -R :<web server group> .

Wednesday 10 July 2019

How to get USPS Shipping API (Shipping price) with PHP

<?php
function USPSParcelRate($weight,$dest_zip,$origin_zip ,$pack_size="REGULAR",$userName,$servicecode) {
// =============== DON'T CHANGE BELOW THIS LINE API CALL===============
$url = "http://Production.ShippingAPIs.com/ShippingAPI.dll";
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// parameters to post
curl_setopt($ch, CURLOPT_POST, 1);
$data = "API=RateV4&XML=<RateV4Request USERID=\"$userName\"><Package ID=\"1ST\"><Service>ALL</Service><ZipOrigination>$orig_zip</ZipOrigination><ZipDestination>$dest_zip</ZipDestination><Pounds>$weight</Pounds><Ounces>0</Ounces><Container/><Size>$pack_size</Size><Machinable>FALSE</Machinable></Package>
</RateV4Request>";
// send the POST values to USPS
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result=curl_exec ($ch);
$data = strstr($result, '<?');
// echo '<!-- '. $data. ' -->'; // Uncomment to show XML in comments
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (array_key_exists('attributes',$xml_elem)) {
list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
} else {
$level[$xml_elem['level']] = $xml_elem['tag'];
}
}
if ($xml_elem['type'] == 'complete') {
$start_level = 1;
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
eval($php_stmt);
}
}
curl_close($ch);
// echo '<pre>'; print_r($params); echo'</pre>'; // Uncomment to see the full array
return $params['RATEV3RESPONSE']['1ST'][$servicecode]['RATE'];
}

$res = USPSParcelRate($weight,$dest_zip,$origin_zip ,"REGULAR",$userName,$servicecode);

echo "Price ".$res;
?>

Monday 8 July 2019

how to password protected in htaccess url in pacific country ?

.htaccess

File content:

AuthType Basic
AuthName "Restricted access"
AuthUserFile /home2/b4x4u4fu/public_html/.htpasswd
require valid-user
Order allow,deny
Allow from all
deny from 1.6.0.0/1

command line run : htpasswd -c .htpasswd [username]

how to password protected in php url in pacific country ?

/* ------------------------------ */

function ip_visitor_country()
{

    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];
    $country  = "Unknown";

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://www.geoplugin.net/json.gp?ip=".$ip);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $ip_data_in = curl_exec($ch); // string
    curl_close($ch);

    $ip_data = json_decode($ip_data_in,true);
    $ip_data = str_replace('&quot;', '"', $ip_data); // for PHP 5.2 see stackoverflow.com/questions/3110487/

    if($ip_data && $ip_data['geoplugin_countryName'] != null) {
        $country = $ip_data['geoplugin_countryName'];
    }

    return $country;
}

$ip =trim(ip_visitor_country());

if($ip=='India'){

    function CheckAccess()

{

  $result = (isset($_SERVER['PHP_AUTH_USER']) &&

            $_SERVER['PHP_AUTH_USER'] == 'admin' &&

            $_SERVER['PHP_AUTH_PW'] == 'admin@123');

  if (!$result)

  {

   header('WWW-Authenticate: Basic realm=“Test restricted area”');

   header('HTTP/1.0 401 Unauthorized');

   return false;

  }

  else

   return true;

}


if (!CheckAccess())

{

  //show the access denied message and exit script

  echo 'Access denied!';

  exit;

}

}

//exit;
/* ------------------------------------- */

Wednesday 19 June 2019

How to Set up an SSH Server on a Home Computer

Step 1: sudo apt-get upgrade

Step 2: sudo apt-get install openssh-client

Step 3:  sudo apt-get install openssh-server


ssh targetusername@xxx.xxx.xx.xxx (target IP address for example 192.168.0.10)

Monday 27 May 2019

Magento 2.X - Display Recently Viewed Products block on Product Detail page

catalog_product_view.xml
===================================
<referenceContainer name="content">
       
          <block class="Magento\Reports\Block\Product\Widget\Viewed" after="-" name="recently_viewed" cacheable="false" template="Magento_Reports::widget/viewed/content/viewed_grid.phtml">
            <action method="setPageSize">
              <argument name="page_size" xsi:type="number">5</argument>
            </action>
          </block>
         
        </referenceContainer>

How to Add Custom Field to Customer Address in magento 1.9

<?php
$installer = new Mage_Customer_Model_Entity_Setup('core_setup');

$installer->startSetup();

$installer->addAttribute('customer_address', 'flatnumber', array(
    'type' => 'varchar',
    'input' => 'text',
    'label' => 'Door / Flat Number',
    'global' => 1,
    'visible' => 1,
    'required' => 0,
    'user_defined' => 1,
    'visible_on_front' => 1
));
Mage::getSingleton('eav/config')
    ->getAttribute('customer_address', 'flatnumber')
    ->setData('used_in_forms', array('customer_register_address','customer_address_edit','adminhtml_customer_address'))
    ->save();
$installer->endSetup();

 ?>

Monday 20 May 2019

How to send forgot password link programmatically in magento 1.9

How to send forgot password link programmatically in magento 1.9

<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app('default');
$yourCustomerEmail="bliss.jaimin@gmail.com";
$customer = Mage::getModel('customer/customer')
    ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
    ->loadByEmail($yourCustomerEmail);
if ($customer->getId()) {
    try {
        $newResetPasswordLinkToken =  Mage::helper('customer')->generateResetPasswordLinkToken();
        $customer->changeResetPasswordLinkToken($newResetPasswordLinkToken);
        $customer->sendPasswordResetConfirmationEmail();
    } catch (Exception $exception) {
        Mage::log($exception);
    }
}

Monday 25 March 2019

Programmatically assign customer to a quote in magento

$customer = Mage::getModel('customer/customer')->load($userId);

$quote = Mage::getModel('sales/quote')->load($quoteId);
$quote->setCustomer($customer);
$quote->save();

How to copy one quote (only cart items) to other quote (only items ) in magento

$quoteA = Mage::getModel('sales/quote')->load($quoteId);
$quoteB = Mage::getModel('sales/quote')->load($userQuoteId);
$quoteB->merge($quoteA);
$quoteA->delete();
$quoteA->collectTotals()->save();
$quoteB->collectTotals()->save();

Monday 18 March 2019

How do I add to wishlist programatically in magento 1.9?

$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customerId, true);
$product = Mage::getModel('catalog/product')->load($productId);

$buyRequest = new Varien_Object(array()); // any possible options that are configurable and you want to save with the product

$result = $wishlist->addNewItem($product, $buyRequest);
$wishlist->save();

Tuesday 5 March 2019

How to get (cart) items programatically shows duplicate SKUs for both the configurable and simple product in magento


As you have using getAllItems() then on for loop you need to check is it has parent item $item->getParentItemId().

foreach ($cart->getAllItems() as $item) {
    / * add this */
    if ($item->getParentItemId()) {
        continue;
    }
........
}

Saturday 2 March 2019

Check the customer password field Magento 1.9

    $email='test@gmail.com';
    $customer =Mage::getModel('customer/customer')
    ->setWebsiteId(Mage::app()->getStore()
    ->getWebsiteId())
    ->loadByEmail($email);
    $hash= $customer->getPasswordHash();

    Mage::helper('core')->validateHash($currentpassword, $hash);

Thursday 14 February 2019

Get product from save event observer - Magento 2

Get product from save event observer - Magento 2

If you want to $productobj after saving product from backend then you can easily use catalog_product_save_after event.
I am assuming that you already know how to create a module in M2.
Put this events.xml in below path
app\code\YOUR_NAMESPACE\YOURMODULE\etc\adminhtml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_save_after">
        <observer name="test_name" instance="YOUR_NAMESPACE\YOUR_MODULENAME\Observer\Productsaveafter" />
    </event>
</config>

And put your Productsaveafter.php in below path
app\code\YOUR_NAMESPACE\YOURMODULE\Observer\


<?php

namespace YOURNAMESPACE\YOURMODULENAME\Observer;

use Magento\Framework\Event\ObserverInterface;

class Productsaveafter implements ObserverInterface
{   
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $_product = $observer->getProduct();  // you will get product object
        $_sku=$_product->getSku(); // for sku

    }  
}

Tuesday 12 February 2019

How to search for product by name or sku with PageSize and CurPage programatically magento 1.9?

How to search for product by name or sku with PageSize and CurPage programatically magento 1.9?
$products = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter(
                        array(
                            array('attribute' => 'sku', 'like' => '%'.$search.'%'),
                            array('attribute' => 'name', 'like' => '%'.$search.'%')
                        )
                    )
                    ->setPageSize(10)->setCurPage(1)->load();

Tuesday 15 January 2019

How to get instagram feed in custom page in magento

<?php
$fields = array(
'client_id' => "bdb4fd62e6e24f938fb7d124acf80187",
'client_secret' => "1cca64ded0e046118b311fdc001bb52c",
'grant_type' => "authorization_code",
'redirect_uri' => "http://wgi-mobile-dev-949798541.ap-south-1.elb.amazonaws.com/insta.php",
//'code' => $_GET['code'],
);
//1484074220.1677ed0.af32987ae8984bb59d9803afabc83e65
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.instagram.com/v1/users/self/media/recent/?access_token=1484074220.1677ed0.af32987ae8984bb59d9803afabc83e65');
curl_setopt($ch, CURLOPT_POST, false);
//curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$posts = curl_exec($ch);
curl_close($ch);
$posts = json_decode($posts);

if ($posts) {
foreach ($posts->data as $dat) {
echo '<img src="' . $dat->images->standard_resolution->url . '" style="width:250px;height:200px;">';
}
}
?>

instagram access token generator :- https://instagram.pixelunion.net/