PHP

How to send push notification to I-Phone and Android

Please check below code which will help you to send push notifications


include('pushnotification.php');

$msg = array( 'mtitle' =>'Push notification title', 'mdesc' => 'Push notification desc', );

// For Android

$regId = 'adadadadA8686865665656565dddsxsx;

// For iOS

$deviceToken = 'FFFFFFFFFFSDSDDSD';

// For Android

PushNotifications::android($msg, $token);

// For iOS

PushNotifications::iOS($msg, $token);

Include a class file name as pushnotification.php


class PushNotifications {
// (Android)API access key from Google API's Console.
private static $API_ACCESS_KEY = 'sdsdsdsdsdsdd-gfgerrccscs';
// (iOS) Private key's passphrase.
private static $passphrase = 'dsefsdd';
public function __construct() {
    exit('Init function is not allowed');
}

// Sends Push notification for Android users
public function android($data, $reg_id) {
    $url = 'https://android.googleapis.com/gcm/send';
    $message = array(
    'title' => $data['mtitle'],
    'message' => $data['mdesc'],
    'subtitle' => '',
    'tickerText' => '',
    'msgcnt' => 1,
    'vibrate' => 1
    );

    $headers = array(
    'Authorization: key=' .self::$API_ACCESS_KEY,
    'Content-Type: application/json'
    );

    $fields = array(
    'registration_ids' => array($reg_id),
    'data' => $message,
    );

    return $this->useCurl($url, $headers, json_encode($fields));
}

public function iOS($data, $devicetoken) {
    $deviceToken = $devicetoken;
    $ctx = stream_context_create();
    // ck.pem is your certificate file
    stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
    stream_context_set_option($ctx, 'ssl', 'passphrase', self::$passphrase);

    // Open a connection to the APNS server
    $fp = stream_socket_client(
    'ssl://gateway.sandbox.push.apple.com:2195', $err,
    $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

    if (!$fp)
        exit("Failed to connect: $err $errstr" . PHP_EOL);

    // Create the payload body
    $body['aps'] = array(
    'alert' => array(
    'title' => $data['mtitle'],
    'body' => $data['mdesc'],
    ),
    'sound' => 'default'
    );

    // Encode the payload as JSON
    $payload = json_encode($body);

    // Build the binary notification
    $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

    // Send it to the server
    $result = fwrite($fp, $msg, strlen($msg));

    // Close the connection to the server
    fclose($fp);

    if (!$result)
        return 'Message not delivered' . PHP_EOL;
    else
        return 'Message successfully delivered' . PHP_EOL;

}

// Curl
private function useCurl(&$model, $url, $headers, $fields = null) {
    // Open connection
    $ch = curl_init();
    if ($url) {
        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        if ($fields) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        }

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);

        return $result;
    }
}
 
}

 

Magento

How to make all store images the base, small and thumbnail images in Magento 2

If you want to set Base , Small and Thumbnail image for all the added products please follow below steps

1- Open ‘eav_attribute’ table from phpmyadmin and get attribute value for IMAGE, SMALL_IMAGE and THUMBNAIL attribute ids are 87, 88, 89.

Magento eav_attribute table

2- Run Below query in phpmyadmin

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 mgv.entity_id = ev.entity_id
AND ev.attribute_id IN (74, 75, 76)
AND mgv.position = 1;

Magento

How to update password from Database for Magento

Update Password from admin panel by running following query 

UPDATE admin_user SET password = md5(‘YOUR_NEW_SELECTED_PASSWORD’), is_active = 1 WHERE username = ‘admin’;

YOUR_NEW_SELECTED_PASSWORD will be your new password

Username will be the name of user for which you want to change Password

Magento

You did not sign in correctly or your account is temporarily disabled for Magento

Many time you face such a issue that you cannot log in to the admin panel. Or some other user face such issues when try to login.

Please follow following steps to solve this issue

1-  Run Command:- php bin/magento admin:user:unlock admin 

2- Truncate the admin_user_session table so all session data gets removed

3- In the mage_admin_user table reset failures_num to 0

4- In the mage_admin_user table reset first_failure to NULL for the user

5- Reset Password from DB or from Forgot Password Section of website front end / admin panel

6- Update Password from admin panel by running following query 

UPDATE admin_user SET password = md5(‘YOUR_NEW_SELECTED_PASSWORD’), is_active = 1 WHERE username = ‘admin’;

YOUR_NEW_SELECTED_PASSWORD will be your new password

Username will be the name of user for which you want to change Password

Magento

How to Load Order by ID in Magento 2

$orderId = 1;

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$order = $objectManager->create('Magento\Sales\Model\Order')->load($<em>orderId</em>); 

$totall = $order->getGrandTotal();

$shippingAddress = $order->getShippingAddress();

$shippingAddress->getTelephone(); 

$shippingAddress->getPostcode(); 

$items = $order->getAllItems();

foreach($items as $i) { 

 $objectManager->create('Magento\Catalog\Model\Product') ->load($i->getProductId())->getSku();  

 echo "product sku:".$_product."<br/>";

}
Magento

How to load Product by Sku or ID in Magento 2

Load Catalog Product by SKU or ID

                $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        

 

                $appState = $objectManager->get(‘\Magento\Framework\App\State’);

                $appState->setAreaCode(‘frontend’);

 

                $productRepository = $objectManager->get(‘\Magento\Catalog\Model\ProductRepository’);

 

                $id = 1; // YOUR PRODUCT ID;

                $sku = ’24-MB01′; // YOUR PRODUCT SKU

 

                // get product by product id

                $product = $productRepository->getById($id);

 

                // get product by product sku

                $product = $productRepository->get($sku);

Magento

What are the changes in THEME folder structure in Magento 2?

  • In Terms of theme, there are 2 main changes in Mage 2.
    1. Removal of skin folder from root.
    2. Introduction of a new directory ‘view’ in the module folder structure which actually completes the MVC structure in more structured way.
  • we don’t have to create a directory inside skin directory like we did in Magento 1.x,. Instead, we can place all the module specify JS, CSS, Images inside the web directory in each module folder.
  • Themes are grouped by ‘vendor’ which we known as ‘package’ in magento 1.x. Theme structure in Magento 2 is like ‘app/design/frontend/vendor_name/theme_name’1
Magento

What are the basic extend and implement classes for Magento2?

  • Model: extends \Magento\Framework\Model\AbstractModel
  • ResourceModel: extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
  • Collection: extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
  • Block : extends \Magento\Framework\View\Element\AbstractBlock
  • Helper : extends \Magento\Framework\App\Helper\AbstractHelper
  • InstallData: implements InstallDataInterface
  • InstallSchema: implements InstallSchemaInterface
  • UpgradeData: implements UpgradeDataInterface
  • UpgradeSchema: implements UpgradeSchemaInterface
Magento

What is Full page Caching in Magento 2?

  • Full page caching is now a part of both Community and Enterprise editions of Magento. This means that Magento will cache category and product pages, as well as CMS pages.
  • The cached version of all pages are located in /var/page_cache folder and are automatically updated when a product is added, edited or other changes are applied.
Magento

What Changes are Made in the Folder Structure

Changes in folder structure:

  • Media folder, errors folder, get.php, cron.php and index.php files are all moved to a pub folder.
  • Skin and js folders are also moved to a pub/static folder. This makes it easier to manage static content with CDN.
  • The database connection string is now defined in app/etc/env.php instead of the local.xml where it was previously located.
  • Theme folder organization is also different now. All themes are grouped by vendor now and path naming convention is app/design/frontend/vendorName/themeName.
  • Changes to modules have been made in a similar fashion. Paths to modules now contain both vendors’ name (namespace) and module name.