cancel
Showing results for 
Search instead for 
Did you mean: 

get Magento 2.1 customer session data outside of Magento

SOLVED

get Magento 2.1 customer session data outside of Magento

I have a Magento 2.1 based website and I want to run a query after a customer clicks a button in there customer dashboard that would run an external php file. My issue is I can not figure out in Magento 2.1 how to get magento and the customers session data into the external php file?

Here is the code I am trying to use

 

require('app/bootstrap.php');
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
/** @var \Magento\Framework\App\Http $app */
//$app = $bootstrap->createApplication('DemoApplication');
//$bootstrap->run($app);

//mysql connection
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();


$customerSession = $om->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
    $thecustomeridis = $customerSession->getCustomer()->getId(); 
    //echo   $customerSession->getCustomer()->getName()."<br/>";  // get  Full Name
    //echo   $customerSession->getCustomer()->getEmail()."<br/>"; // get Email Name
    $origional_groupid = $customerSession->getCustomer()->getGroupId();  // get Customer Group Id

    //lets run sql to update the customer to be a vip 
    $sql = "UPDATE customer_entity SET group_id = 3 WHERE entity_id = $thecustomeridis AND store_id= 1 AND website_id = 1";
   $result = $connection->fetchAll($sql); 
  }  
1 REPLY

Re: get Magento 2.1 customer session data outside of Magento

Hi Jayreis, sorry but this is the wrong way to go about this solution as it goes against Magento best practices. You should instead be creating a real Magento extension. This will probably need to create a new controller that your button can link to. This controller will then handle communication with the relevant customer models to update their VIP status.  It's unwise to use direct database queries, and is a security risk to pass session data straight into the SQL query as well. 

 

Check out this introduction to building a Magento 2 extension: http://inchoo.net/magento-2/how-to-create-a-basic-module-in-magento-2/

----
If you've found one of my answers useful, please give "Kudos" or "Accept as Solution" as appropriate. Thanks!