How to access Magento from CodeIgniter? - codeigniter

I have a default CodeIgniter 2.1 install with Magento 10.4.4 installed in a subdir called store.
The following code works when run from web root (with .htaccess disabled). It will give the firstname, lastname of the logged in Magento user.
<?php
$site_root = '/var/www/mysite/www/httpdocs';
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
$name='frontend';
$options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options);
Mage::getSingleton("core/session", array("name" => $name));
$websiteId = Mage::app()->getWebsite()->getId();
echo "websiteid: $websiteId<br>";
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
echo 'customerwebsiteId: ' . $customer->website_id . '<br>';
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if($session->isLoggedIn()){
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}else{
$magento_message .= 'Guest!';
}
echo $magento_message;
?>
But, if I run this in a CodeIgniter model, then isLoggedIn returns false.
Here is the CodeIgniter page:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test_mage extends CI_Controller {
function __construct()
{
parent::__construct();
}
public function index()
{
$site_root = '/var/www/mysite/www/httpdocs';
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
$name='frontend';
$options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options);
Mage::getSingleton("core/session", array("name" => $name));
$websiteId = Mage::app()->getWebsite()->getId();
echo "websiteid: $websiteId<br>";
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
echo 'customerwebsiteId: ' . $customer->website_id . '<br>';
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if($session->isLoggedIn()){
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}else{
$magento_message .= 'Guest!';
}
echo $magento_message;
}
}
CodeIgniter is doing something that I have not been able to track yet. The websiteId is returned correctly, but isLoggedIn returns false.
Anyone have any ideas? THANKS!!

I use both but ive never tried to mash them like that. I foresee quite a few problems.
How are you patching into magento?
You might need two db connections running :
$db['magento']
$db['default'] // codeigniter default
Sessions could become a real problem here also aswell as config data.
Consider sticking with magento for now, then maybe patch into your blog/website via a RESTFul service.

Both code examples above work fine. The problem I had was calling session_start() near the top of the CodeIgniter index.php file. Once that was removed, it all started working.
For posterity, here is a Magento 10 Library for CodeIgniter 2.1:
application/libraries/magento.php
<?php if ( ! defined('BASEPATH')) exit("No direct script access allowed");
Class Magento {
function __construct($params)
{
global $site_root;
$name = $params['name'];
// Include Magento application
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
// Uncomment next line if you have moved app/etc
// $options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options=null);
return Mage::getSingleton("core/session", array("name" => $name));
}
}
// end of magento.php
Usage example app/model/test_mage.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test_mage extends CI_Controller {
function __construct()
{
parent::__construct();
$params = array('name' => 'frontend'); // frontend or adminhtml
$this->load->library('magento', $params);
}
public function index()
{
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if ($session->isLoggedIn())
{
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}
else
$magento_message .= 'Guest!';
echo $magento_message . '<br>';
}
}
// end of test_mage.php

Related

Clear cache on CodeIgniter using wildcard

CodeIgniter documentation specified only two-ways to delete cache. They are:
$this->cache->delete('cache_item_id')
- for deleting individual cache thru ID
$this->cache->clean()
- for deleting ALL cache
My website have static and dynamic content and I would like to delete all the cache on the latter only.
I'm looking for something like ->delete("latest*") that will delete "latest-video", "latest-video-funny", "latest-video-music", "latest-article", etc.
I think I've got it working, calling $this->cache->cache_info(); will fetch a multidimensional array of all saved cache. The array keys inside the fetch array are the cache_item_id so I can just do the following.
$wildcard = 'latest';
$all_cache = $this->cache->cache_info();
foreach ($all_cache as $cache_id => $cache) :
if (strpos($cache_id, $wildcard) !== false) :
$this->cache->delete($cache_id);
endif;
endforeach;
There is a helper that does this, you can find it here.
how is cache created
$path = $CI->config->item('cache_path');
$cache_path = ($path == '') ? APPPATH.'cache/' : $path;
.
.
.
$uri = $CI->config->item('base_url').
$CI->config->item('index_page').
$CI->uri->uri_string();
$cache_path .= md5($uri);
helper itself
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('delete_cache'))
{
function delete_cache($uri_string)
{
$CI =& get_instance();
$path = $CI->config->item('cache_path');
$cache_path = ($path == '') ? APPPATH.'cache/' : $path;
$uri = $CI->config->item('base_url').
$CI->config->item('index_page').
$uri_string;
$cache_path .= md5($uri);
if (file_exists($cache_path))
{
return unlink($cache_path);
}
else
{
return TRUE;
}
}
}
all credits go to Steven Benner, his blog.
usage:
delete_cache('/blog/comments/123');

Magento customer login from outside magento

I am trying to login as a customer.
I am requesting the Following code (AJAX) and this outside magento store.
<?php
require_once "../app/Mage.php";
umask(0);
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));
$user = $_POST['user'];
$password = $_POST['password'];
$session = Mage::getSingleton('customer/session');
$flag = 0;
$resultArr = array();
function customerLogin($user,$password){
try{
$session = Mage::getSingleton('customer/session');
$result = $session->login($user,$password);
$customer = $session->getCustomer();
$session->setCustomerAsLoggedIn($customer);
$resultArr['flag'] = 1;
$resultArr['msg'] ='Logged in as '.$customer->getName();
$jsonReturn = json_encode($resultArr);
return $jsonReturn;
}catch(Exception $e){
$resultArr['flag'] = 0;
$resultArr['msg'] = $e->getMessage();
$jsonReturn = json_encode($resultArr);
return $jsonReturn;
}
}
echo customerLogin($user,$password);
?>
I found the above code is Creating the session files at var/session directory successfully but unable to write customer entry in log_customer DB table . Anybody know whats the problem here.
Thanks :)
UPDATED
Okie the following updated code(customerLogin.php) is working under a condition
<?php
function customerLogin($user,$password){
require_once "./app/Mage.php";
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));
$user = $_POST['user'];
$password = $_POST['password'];
$flag = 0;
$resultArr = array();
$session = Mage::getSingleton('customer/session');
try{
$result = $session->login($user,$password);
//$customer = $session->getCustomer();
$session->setCustomerAsLoggedIn($session->getCustomer());
$resultArr['flag'] = 1;
$resultArr['msg'] ='Logged in as '.$session->getCustomer()->getName();
$cusArr = array(
'isLoggedIn' => true,
'name' => $session->getCustomer()->getName(),
'id' => $session->getId(),
'email' =>$session->getCustomer()->getEmail(),
);
$resultArr['customerData'] = $cusArr;
$jsonReturn = json_encode($resultArr);
return $jsonReturn;
}catch(Exception $e){
$resultArr['flag'] = 0;
$resultArr['msg'] = $e->getMessage();
$jsonReturn = json_encode($resultArr);
return $jsonReturn;
}
}
echo customerLogin($user,$password);
?>
if i follow the directory structure like:
|-- app
|-- **customerLogin.php**
|-- downloader
|-- install.php
|-- js
|-- lib
|-- media
|-- var
But its not working if I place code one directory level down like :
|-- app
|-- **customerLogin**
`--**customerLogin.php**
|-- downloader
|-- install.php
|-- js
|-- lib
|-- media
|-- var
Anybody knows whats the problem.
I am wondering why magento is unable to write session entry in log_customer table when i place my code one level down.
Get your customer id then use the below code.
Mage::getSingleton('customer/session')->loginById($customerId);
try this code to login from outside of magento, create demo.php file in magento root and put following code.
include('app/Mage.php');
Mage::app();
if($_POST && $_POST["email"] && $_POST["password"])
{
$email=$_POST["email"];
$password=$_POST["password"];
$session = Mage::getSingleton('customer/session');
try {
$log = $session->login($email, $password);
$session->setCustomerAsLoggedIn($session->getCustomer());
$customer_id=$session->getCustomerId();
$send_data["success"]=true;
$send_data["message"]="Login Success";
$send_data["customer_id"]=$customer_id;
}
catch (Exception $ex) {
$send_data["success"]=false;
$send_data["message"]=$ex->getMessage();
}
}
else
{
$send_data["success"]=false;
$send_data["message"]="Enter both Email and Password";
}
echo json_encode($send_data);
store id and website id here set custom
you will change accordance to u
<?php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
require_once "app/Mage.php";
umask(0);
Mage::app();
$firstname = "krishana";
$lastname = "singh";
$email = "krish.bhati#gmail.com";
$password = "12345678";
// Website and Store details
$websiteId = Mage::app()->getWebsite()->getId('1');
$store = Mage::app()->getStore('31');
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
$mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
$mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';
$app = Mage::app ( $mageRunCode, $mageRunType );
Mage::app('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));
$session = Mage::getSingleton('customer/session');
$session->start();
$customer->loadByEmail($email);
$customer_id= $customer->getId();
if($customer_id){
Mage::getSingleton('customer/session')->loginById($customer_id);
Mage_Core_Model_Session_Abstract_Varien::start();
try{
$session->login($email, $password);
}
catch(Exception $e) {}
$session->setCustomerAsLoggedIn($session->getCustomer());
echo $session->isLoggedIn() ? $session->getCustomer()->getName().' is online!' : 'not logged in';
}
?>
Easily open your account & forgot password for your Magento without loading any pages through GSD Ajax login. Below URL is very useful.
http://www.magentocommerce.com/magento-connect/easy-ajax-login-by-smartshore.html
use below code in magento controller it will work inside controller because custom PHP file can not generate magento visitor log
public function customerLoginSession($customer_id){
/** #var $session Mage_Customer_Model_Session */
$session = Mage::getSingleton( 'customer/session' );
Mage::app()->getStore()->setWebsiteId(1);
try
{
//$session->login( $user, $pass);
$session->loginById($customer_id);
$customer = $session->getCustomer();
$session->setCustomerAsLoggedIn($customer);
$res = json_encode(array('status' => 'valid', 'userData' => $customer->getId()));
}
catch( Exception $e )
{
$res = json_encode(array('status' => 'invalid', 'userData' => $e->getMessage()));
}
return $res;
}

Session expiring for twitter oAuth

I am using Abraham Williams' oAuth library to update a status. The application does not have a UI (other than the prompt from Twitter for credentials. Instead, the user enters a URL in the browser.
When the URL is called, I get an error: "Could not post Tweet. Error: Reason: 1".
I inserted some test code, and it seems as if the session is getting lost in between transitions: $_SESSION['tweetmsg'] is set on initial call in index.php, but then when the switch to connect.php happens, it seems as if the session is lost. Any ideas?
Following is the source code:
index.php
<?php
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
session_start();
if (empty($_SESSION['access_token'])) {
$_SESSION['tweetmsg'] = create_tweet_text();
print "<script>self.location='./connect.php');</script>";
}
$connection = new TwitterOAuth(
CONSUMER_KEY,
CONSUMER_SECRET,
$_SESSION['access_token']['oauth_token'],
$_SESSION['access_token']['oauth_token_secret']
);
if (!isset($_SESSION['tweetmsg'])) {
exit('No tweet value in session or from form');
}
$tweetmsg = $_SESSION['tweetmsg'];
$result = $connection->post('statuses/update', array('status' => $tweetmsg));
unset($_SESSION['tweetmsg']);
if (200 === $connection->http_code) {
echo 'Tweet Posted: '.$tweetmsg;
}
else {
echo 'Could not post Tweet. Error: '.$httpCode.' Reason: '.
session_destroy();
}
function create_tweet_text () {
return 'this is a test';
}
connect.php
?php
session_start();
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken(OAUTH_CALLBACK.'callback.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
$url = $connection->getAuthorizeURL($request_token);
print "<script>self.location='$url';</script>";
callback.php
<?php
session_start();
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
if (
isset($_REQUEST['oauth_token'])
&& $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']
) {
echo 'Session expired';
}
else {
$connection = new TwitterOAuth(
CONSUMER_KEY,
CONSUMER_SECRET,
$_SESSION['oauth_token'],
$_SESSION['oauth_token_secret']
);
$_SESSION['access_token'] = $connection->getAccessToken($_REQUEST['oauth_verifier']);
print "<script>self.location='index.php';</script>";
}
Recently Twitter deactivated a number of http urls for oAuth and replaced them with https equivalents. If you can see the URL string http://twitter.com/oauth/request_token in the includes then it means you need to follow https://dev.twitter.com/discussions/10803 and change all the calls to https...

Can't use session variable in routes.php file in codeigniter?

I am use following code to retrieve the session variable in routes.php
if($this->db_session->userdata('request_url')!="")
{
$route['user/(:any)'] = "search_user_name/redirect_url/".$_SESSION['request_url'];
$this->db_session->unset_userdata('request_url');
}
else {
$route['user/(:any)'] = "search_user_name/index/$1";
}
the session variable would be set into template/header.php
$this->db_session->set_userdata('request_url', $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
You can not use db_session in routes.php because routes.php is parsed before db_session is loaded.
Maybe you should create a base controller and redirect from the constructor of the base controller.
Correct me if iam wrong.
You can use hooks.
Codeigniter user guide hooks
You can use database in routes and put your routes url in database.
Here is an example:
require_once( BASEPATH .'database/DB'. EXT );
$db =& DB();
$table2 = $db->dbprefix.'lang';
$query2 = $db->get( $table2 );
$result2 = $query2->result();
foreach( $result2 as $row )
{
$fields = $db->list_fields($table2);
$findme = 'code';
foreach($fields as $field):
$pos = strpos($field, $findme);
if($pos !== false and $row->$field != ''):
$route[''.$row->$field.''] = 'main/setlang/$1';
endif;
endforeach;
}

$db undefined when using model from helper in codeigniter

I want to have a simple helper which records one hit in my database. I have created a $CI instance and attempt to access the model like this...
$CI->load->model('stats_model');
$CI->stats_model->set_hit();
But i get an error in the model..
Severity: Notice
Message: Undefined property: Stats_model::$db
Filename: models/stats_model.php
Line Number: 16
Line 16 is a simple...
$this->db->select('*');
I got the idea to do this from this link http://blog.avinash.com.np/2010/07/01/talk-to-the-database-from-a-helper-codeigniter/
I have tried $CI->db... instead of $this->db in the model but still no luck, any ideas?
HELPER
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
function check_hit() {
//stuff that uses CI
$CI = & get_instance();
$CI->load->library('user_agent');
if ($CI->agent->is_robot()) {
return FALSE;
} else {
//check for a 12 hour cookie
$check = $CI->input->cookie('stat');
if ($check == false) {
//insert a database entry
$CI->load->model('Stats_model');
$CI->Stats_model->set_hit();
//set a cookie
$cookie = array(
'name' => 'stat',
'value' => '1',
'expire' => '43200'
);
// $CI->input->set_cookie($cookie);
}
}
}
check_hit();
?>
MODEL
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Stats_model extends Model {
function Stats_model() {
// Call the Model constructor
parent::Model();
}
function set_hit() {
$date = date('Y-m-d');
$this->db->select('unique_visitors');
$this->db->from('daily_stats');
$this->db->where('date', $date);
$query = $this->db->get();
$date_rows = $query->num_rows();
$result = $query->row();
$visits = $result->unique_visitors;
$visits++;
$data = array(
'unique_visitors' => $visits,
'date' => $date
);
if ($date_rows == 1) {
$this->db->where('date', $date);
$this->db->update('daily_stats', $data);
} else {
$this->db->insert('daily_stats', $data);
}
}
}
?>
This part was a little confusing for me a while back. This seemed to work.
//load the CI instance
$this->ci =& get_instance();
//run a db get
$this->ci->db->get('mytable');

Resources