Magento retrieve customer ID - php

I've tried various methods to get the customerID but an empty value is stored in the variable. Please advise :)
Below remnants of things I've tried. The file is located in the root.
require_once '/home/ab71714/public_html/app/Mage.php';
//Mage::app("default");
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
/* if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getSingleton('customer/session')->getCustomer();
echo $customerData->getId();
} */
if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerId = Mage::getModel('customer/session')->getCustomer()->getId();
} else {
echo 'Not logged In';
}

require "/home/ab71714/public_html/app/Mage.php";
umask(0);
Mage::app();
$session = Mage::getSingleton('customer/session');
if($session->isLoggedIn()) {
print_r($session);
$customerId = $session->getCustomer()->getId();
} else {
echo 'Not logged In';
}
For more information:
http://ka.lpe.sh/2011/06/19/magento-get-customer-details-customer-id-name-email/

if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getSingleton('customer/session')->getCustomer();
echo $customerData->getId();
}

Related

Problems returning to the index using steamapi login

So i am currently studying PHP and Java and i encountered an error while working on my code. I am working on a login button where the user is able to connect to my page using the SteamAPI login.
I am testing 2 codes to make this work. The first code is the following:
<?php
require('openid.php');
$db = mysqli_connect("localhost", "root", "(my pw of the database)", "(name of my database)");
$_STEAMAPI = "(My steam api key)";
try {
$openid = new LightOpenID("http://mypage.com?id=1");
if(!$openid->mode) {
if(isset($_GET['login'])) {
$openid->identity = 'http://steamcommunity.com/openid/?l=english';
header("Location: " . $openid->authUrl());
} else {
echo "<h2>Connect to Steam</h2>";
echo "<form action='?login' method='post'>";
echo "<input type='image' src='http://steamcommunity-a.akamaihd.net/public/images/signinthroughsteam/sits_large_border.png'>";
echo "</form>";
}
} elseif($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
if($openid->validate()) {
$id = $openid->identity;
$ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
preg_match($ptn, $id, $matches);
$url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=$_STEAMAPI&steamids=$matches[1]";
$json_object= file_get_contents($url);
$json_decoded = json_decode($json_object);
foreach ($json_decoded->response->players as $player)
{
$sql_fetch_id = "SELECT * FROM users_steam WHERE steamid = $player->steamid";
$query_id = mysqli_query($db, $sql_fetch_id);
$_SESSION['name'] = $player->personaname;
$_SESSION['steamid'] = $player->steamid;
$_SESSION['avatar'] = $player->avatar;
if (mysqli_num_rows($query_id) == 0) {
$sql_steam = "INSERT INTO users_steam (name, steamid, avatar) VALUES ('$player->personaname', '$player->steamid', '$player->avatar')";
mysqli_query($db, $sql_steam);
}
}
} else {
echo "User is not logged in.\n";
}
}
} catch(ErrorException $e) {
echo $e->getMessage();
}
?>
`
The other code i am working with is:
<?php
require 'openid.php';
$_STEAMAPI = "(My steam api key)";
try
{
$openid = new LightOpenID('http://mypage.com/');
if(!$openid->mode)
{
if(isset($_GET['login']))
{
$openid->identity = 'http://steamcommunity.com/openid/?l=english'; // This is forcing english because it has a weird habit of selecting a random language otherwise
header('Location: ' . $openid->authUrl());
}
?>
<form action="?login" method="post">
<input type="image" src="http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_small.png">
</form>
<?php
}
elseif($openid->mode == 'cancel')
{
echo 'User has canceled authentication!';
}
else
{
if($openid->validate())
{
$id = $openid->identity;
// identity is something like: http://steamcommunity.com/openid/id/76561197960435530
// we only care about the unique account ID at the end of the URL.
$ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
preg_match($ptn, $id, $matches);
echo "User is logged in (steamID: $matches[1])\n";
$url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=$_STEAMAPI&steamids=$matches[1]";
$json_object= file_get_contents($url);
$json_decoded = json_decode($json_object);
foreach ($json_decoded->response->players as $player)
{
echo "
<br/>Player ID: $player->steamid
<br/>Player Name: $player->personaname
<br/>Profile URL: $player->profileurl
<br/>SmallAvatar: <img src='$player->avatar'/>
<br/>MediumAvatar: <img src='$player->avatarmedium'/>
<br/>LargeAvatar: <img src='$player->avatarfull'/>
";
}
}
else
{
echo "User is not logged in.\n";
}
}
}
catch(ErrorException $e)
{
echo $e->getMessage();
}
?>
So my problem is that i am trying to redirect to my index.html but it doesn't work. On the first code i get redirected to my index.html because i added a ?id=1 after the URL of my website. If i remove that it will leave me on a blank page. So, it does the work when adding the ?id=1, but it sends me to my website offline. In other words, it send me to my index.html but the login button is still there, showing as if i didn't log in at all (offline index).
On the second code (i haven't used it a lot), it will redirect me to a website showing the information i asked for (id steam, steam name, etc.). It gives me the information i asked for, but it doesn't redirect me to the index.html.
I searched all over the internet and i couldn't find an answer. If someone can help me and tell me where i should change the code so as to get redirected to the index.html and connected i would appreciate it a lot.
Thanks in advanced and sorry for my english, Davor.

Can't create SESSION

<?php
ob_start();
session_start();
require ('openid.php');
function logout() {
echo '<form action="logout.php" method="post"><button class="btn btn-danger" type="submit"><i class="fa fa-power-off"></i> Log Out</button></form>'; //logout button
}
function steamlogin() {
try {
require("settings.php");
$openid = new LightOpenID($domain);
if(!$openid->mode) {
if(isset($_GET['login'])) {
$openid->identity = 'http://steamcommunity.com/openid';
header('Location: ' . $openid->authUrl());
}
return "<form action=\"?login\" method=\"post\"> <input type=\"image\" src=\"http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_large_noborder.png\"></form>";
}
elseif($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
if($openid->validate()) {
$id = $openid->identity;
$ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
preg_match($ptn, $id, $matches);
$steamid = $matches[1];
$link = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=".$key."&steamids=".$steamid."");
$decode = json_decode($link);
$newlink = $decode->response->players->profileurl;
$xml = simplexml_load_file($newlink."?xml=1");
#$custom = $xml->customURL;
if(strlen($custom) <= 4){
$user = $xml->steamID64;
} else {
$user = $custom;
}
$_SESSION['steamid'] = $user;
//Determine the return to page. We substract "login&"" to remove the login var from the URL.
//"file.php?login&foo=bar" would become "file.php?foo=bar"
$returnTo = str_replace('login&', '', $_GET['openid_return_to']);
//If it didn't change anything, it means that there's no additionals vars, so remove the login var so that we don't get redirected to Steam over and over.
if($returnTo === $_GET['openid_return_to']) $returnTo = str_replace('?login', '', $_GET['openid_return_to']);
header('Location: '.$returnTo);
} else {
echo "User is not logged in.\n";
}
}
} catch(ErrorException $e) {
echo $e->getMessage();
}
}
I checked this code 10 times (atleast) , but i don't understand why it doesn't create $_SESSION['steamid'] . Can you help me ?
I edited first post !
First off, you should try setting dummy data to test if your session is working at all. Right after your session_start() put a line like
$_SESSION['test'] = 'test';
var_dump($_SESSION);
If the key does not persist throughout requests then it means there is a problem with your session handler (possibly lacking write permission).
If your session is working then you start going down the tree of logic, check the expressions in each if statement to see what the execution path is, you do not provide any current output so I cannot tell right away.
This is not a definitive answer but I'm sure if you follow my advice you'll get to the root of the problem.

Magento login a customer programmatically

I am trying to login a customer programmatically in magento.
I have followed this tutorial.
So I created a file named test.php in the root of my magento app.
<?php
require_once 'app/Mage.php';
function loginById($customerId)
{
Mage::app(); // to make sure that Mage::getModel() works
$customer = Mage::getModel('customer/customer')->load($customerId);
if ($customer->getWebsiteId()) {
Mage::init($customer->getWebsiteId(), 'website');
$session = Mage::getSingleton('customer/session');
$session->loginById($customerId);
return $session;
}
throw new Exception('Login failed');
}
try {
$session = loginById(1);
//echo Mage_Customer_Model_Session::isLoggedIn();exit;
// var_dump($session);exit;
// function login() from above
$session->setAfterAuthUrl(
'http://192.168.1.61/magento/index.php/customer/account');
//echo $session->getAfterAuthUrl();exit;
header('Location: ' . $session->getAfterAuthUrl());
} catch (Mage_Core_Exception $e) {
echo "error";
}
But when I access this file, it redirect me to login form.
Try this one
<?php
function loginUser( $email, $password )
require_once ("app/Mage.php");
umask(0);
ob_start();
session_start();
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
try {
$customer->loadByEmail($email);
$session = Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
$session->login($email, $password);
}catch(Exception $e){
}
}
?>

Magento API : How to load customer session by ID

I'm working on magento module to log in customer with API.
I can log in customer and get frontend sessionId,
but when I want to load session with this sessionId to check if the customer is already logged in I can't.
Here the API function I used:
public function login($email,$password,$storecode){
$result = array();
$result['code'] = '';
$result['messages'] = '';
try{
$session = Mage::getSingleton('customers/session');
$storemodel = Mage::getModel('core/store')->load($storecode);
$store_id = $storemodel->getId();
$websiteId = $storemodel->getWebsiteId();
if($session->loginByApi($email, $password,$websiteId)){
$result['code'] = 'SUCCESS';
$result['sessionId'] = $session->getSessionId();
$customer = $session->getCustomer();
$result['customer']= array(
'customerid' => $customer->getId(),
'firstname' => $customer->getFirstname(),
'lastname' => $customer->getLastname(),
);
}
} catch (Mage_Core_Exception $e) {
$result['code'] = 'ERRORS';
$result['messages'] = $e->getMessage();
}
return $result;
}
public function isloggedin($customerId,$customersessionId ,$storecode){
if(!isset($storecode)){
$storecode = 'default';
}
Mage::app($storecode, 'store');
$core_session = Mage::getSingleton('core/session', array('name'=>'frontend'));
if($customersessionId != null){
$core_session->setSessionId($customersessionId);
$core_session->start('frontend');
}
$session = Mage::getSingleton('customer/session', array('name'=>'frontend'));
$customer = Mage::getModel('customer/customer')->load($customerId);
$session->setCustomer($customer);
if($session->isLoggedIn()){
$session->setCustomerAsLoggedIn($customer);
$result['sessionId'] = $session->getSessionId();
}else{
$result['logged'] = false;
}
return $result;
}
Anyone have an idea?
Not sure if this helps too much, but this code:
Mage::app('2', 'store');
$s = Mage::getSingleton('customer/session', array('name'=>'frontend'));
$c = Mage::getModel('customer/customer')->load(1);
$s->setCustomer($c);
if($s->isLoggedIn()){
echo $c->getName()." is logged in, session: ".$s->getSessionId().PHP_EOL;
} else {
echo "not logged in".PHP_EOL;
}
Did seem to work for me:
John Smith is logged in, session: d3rcgvd56md4u3cfctcvnt2ou6
If you have the Session ID, you can get at the data with the following call to the core session singleton:
$sessId = 'sn1q4ndvr1kieumsmplhd39n83';
$sess = Mage::getSingleton('core/session', array( 'value' => $sessId ));
That will retrieve the session for any user, logged-in or not. From there you can determine whether the session belongs to a customer with a check for the customer object:
$sessionCustomerId = $sess->getCustomer()->getId();
if ( $sessionCustomerId ) {
// yay, they are a customer!
echo $sessionCustomerId;
}
Hope that helps.
Edit:
You can get the session id from the core session (in a chicken-and-egg style) using Mage::getSingleton('core/session')->getEncryptedSessionId()

Underfind index in session

I try to load a session as I want with me into my handler. But the line 8 says that "during the find index" what is the error in my controller? It is a user name that I want to use a database to retrieve the id of the person.
Controller:
<?php
require_once ("View/PersonInfoView.php");
require_once ("Handler/UserHandler.php");
class PersonInfoController{
public function DoPersonInfo(){
$Personinfoview = new PersonInfoView();
$UserHandler = new UserHandler();
$PK = $UserHandler->GetUserID($_SESSION['Person']);
$Person_array = $UserHandler->ListPerson($PK);
$Personinfoview->Personbox($Person_array);
}
}
I set Session :
<?php
require_once ("Handler/Userhandler.php");
require_once ("Controller/LoginController.php");
class DologinHandler{
public function Login(){
if(isset($_REQUEST['is_ajax']))
{
$LoginController = new LoginController();
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$_SESSION['Person'] = $username;
$UserHandler = new UserHandler();
$sign = $UserHandler -> controllDB($username,$password);
if($sign == true)
{
echo 'success';
return true;
}
else
{
echo 'error';
return false;
}
}
}
}
$loginclass = new DologinHandler();
$loginclass->Login();
I'm guessing your $_REQUEST doesn't contain the key Person. Try doing a var_dump() on $_REQUEST to see what it contains.
Other than that, I suggest you implement some kind of error handeling when calling $UserHandler->GetUserID()
For instance.
try {
$PK = $UserHandler->GetUserID($_SESSION['Person']);
} catch(Exception $e) {
echo($e->getMessage());
}
Read about exceptions.

Categories