In magento 2 customer login programatically using email and password?
2 Answers
Try this
<?php
...
private $customer;
private $customerSession;
public function __construct(
...
\Magento\Customer\Model\Customer $customer,
\Magento\Customer\Model\Session $customerSession
) {
$this->customer = $customer;
$this->customerSession = $customerSession;
...
}
...
$customerEmail = "[email protected]"; // add customer email address
$websiteId = "1"; // add your website id
$customer = $this->customer;
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($customerEmail);
$this->customerSession->setCustomerAsLoggedIn($customer);
echo "customer is logged in";
protected $customer;
protected $customerSession;
public function __construct(...
\Magento\Customer\Model\Customer $customer,
\Magento\Customer\Model\Session $customerSession) {
...
$this->customer = $customer;
$this->customerSession = $customerSession;
...
}
...
$customer = $this->customer->loadByEmail("[email protected]");
$this->customerSession->setCustomerAsLoggedIn($customer);
if($this->customerSession->isLoggedIn()) {
echo "Customer Logged in";
}else{
echo "customer is not Logged in";
}