Friday 30 March 2012

Browser Detection Code

You can detect your browser using below code


<?php
function getBrowser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";


    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }
   
    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }
   
    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }
   
    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];
        }
        else {
            $version= $matches['version'][1];
        }
    }
    else {
        $version= $matches['version'][0];
    }
   
    // check if we have a number
    if ($version==null || $version=="") {$version="?";}
   
    return array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
}


// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>

may this code help you to find out detail about your browser

Magento – How to Reset the Admin Password


Use any password for admin username and after that you can change your password:

Only need FTP Access:



Use any password for admin username:

Only need FTP Access :


To login into magento admin, using only ftp access is a little tricky. Through FTP open the class Mage_Admin_Model_User located at app\code\core\Mage\Admin\Model\User.php
Next find the authenticate() function around line no: 225. Inside the authenticate function, this code is written

$this->loadByUsername($username);

You need to add the line return true; after this i.e

$this->loadByUsername($username);
return true;

And that’s it..
now find username using below script :


<?php
require_once 'app/Mage.php';
umask(0);
Mage::app('');
$tprefix = (string) Mage::getConfig()->getTablePrefix();
echo "<br/>".$tprefix;
        $connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$b=$connection->query("select * from ".$tprefix."admin_user ");
$t=0;
while($roes2=$b->fetch(PDO::FETCH_ASSOC)) 
{
$adminemail=$roes2['email'];
$adminuser=$roes2['username'];
echo $adminemail.'=>'.$adminuser.'<br/>';
}
?>
make one php file and past above code in it,after that put that php file in root and run it ex. if php file name is findadnim.php than run http://yourdomainname.com/findadmin.php
so you get all usernames of admin select any of them , now you login in admin using any password for. Since, we have skipped the code for password checking, login using any password and then change the password in admin from System -> Permission -> Users.

Programmatically Add Product In Cart in Magento

Adding a Product to the Cart via Querystring


For Simple Product :

$this->getUrl('checkout/cart').'add?product='.$pro_id.'&qty='.$qty.';
where : $pro_id= 'Product id' ; $qty = 'Product Quentity'

For Simple Product with Custome Option:

$this->getUrl('checkout/cart').'add?product = '.$pro_id.'&qty = '.$qty.'&options['.$pro_value.'] = '.$pro_opt_val.'
where : $pro_value= 'Product option_id';$pro_opt_val= 'Product option_type_id';

For Bundle Product :

$this->getUrl('checkout/cart').'add/product/['.$pro_id.']/?bundle_option[['.option_id.']][]=['.selection_id.']

like if bundle product's id is 2790 than :
      $_product = Mage::getModel('catalog/product')->load(2790);
      if ($_product->getTypeId() == 'bundle') 
     {
        $w = Mage::getSingleton('core/resource')->getConnection('core_write');
        $result = $w->query("select `option_id`, `selection_id` from `catalog_product_bundle_selection` where        `parent_product_id`=$id");
        $route = "checkout/cart/add";
        $params = array('product' => $id);
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $params['bundle_option['. $row[option_id] .']'][] = $row['selection_id'];
       };
        header("Location: ". Mage::getUrl($route, $params));
   }

For Adding a Configurable Product to the Cart via Querystring:

http://www.your_domain.com/checkout/cart/add?product = 68&qty = 1&super_attribute[528] = 55& super_attribute[525] = 56


Here  68  is the product entity id displayed in magento admin panel.  528 and 525  is the attribute associated with this product and  55 and 56  is the selected value of that attribute. 

Another way to add product in cart :

For Simple Product :

$params = array(
    'product' => 23,
    'qty' => 2,
);
$cart = Mage::getSingleton('checkout/cart'); 
$product = new Mage_Catalog_Model_Product();
$product->load(23); 
$cart->addProduct($product, $params);
$cart->save(); 
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);



For  Configurable  Product  :



$params = array(
    'product' => 23,
    'super_attribute' => array(
         528 =>55,
    ),
    'qty' => 2,
);

$cart = Mage::getSingleton('checkout/cart'); 
$product = new Mage_Catalog_Model_Product();
$product->load(23); 
$cart->addProduct($product, $params);
$cart->save(); 
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

Programmatically Create New Magento Admin User


<?php
/*
 * Create New Admin User
 */


//define USERNAME, EMAIL and PASSWORD below whta ever you want and uncomment this 3 lines (remove # sign)


#define('USERNAME','admin');
#define('EMAIL','xyz@xyz.com');
#define('PASSWORD','admin123');




if(!defined('USERNAME') || !defined('EMAIL') || !defined('PASSWORD')){
echo 'Edit this file and define USERNAME, EMAIL and PASSWORD.';
exit;
}


//load Magento
$mageFilename = 'app/Mage.php';
if (!file_exists($mageFilename)) {
echo $mageFilename." was not found";
exit;
}
require_once $mageFilename;
Mage::app();


try {
//create new user write you firstname,lastname
$user = Mage::getModel('admin/user')
->setData(array(
'username'  => USERNAME,
'firstname' => 'Gz',
'lastname' => 'Chauhan',
'email'     => EMAIL,
'password'  => PASSWORD,
'is_active' => 1
))->save();


} catch (Exception $e) {
echo $e->getMessage();
exit;
}


try {
//create new role
$role = Mage::getModel("admin/roles")
->setName('Inchoo')
->setRoleType('G')
->save();

//give "all" privileges to role
Mage::getModel("admin/rules")
->setRoleId($role->getId())
->setResources(array("all"))
->saveRel();


} catch (Mage_Core_Exception $e) {
echo $e->getMessage();
exit;
} catch (Exception $e) {
echo 'Error while saving role.';
exit;
}


try {
//assign user to role
$user->setRoleIds(array($role->getId()))
->setRoleUserId($user->getUserId())
->saveRelations();


} catch (Exception $e) {
echo $e->getMessage();
exit;
}


echo 'Admin User sucessfully created!<br /><br /><b>THIS FILE WILL NOW TRY TO DELETE ITSELF, BUT PLEASE CHECK TO BE SURE!</b>';
@unlink(__FILE__);


?>

create php file like newuser.php and past above code in that file, put newuser.php file in magento root and run script like http://yourdomain.com/newuser.php thats it, now you can login in magento admin using username and password that you enter above code

Wednesday 17 August 2011

How to disable / remove Secret Key from Admin URL in Magento?


A new secret key is created every time you login to Magento Admin. So, there will be a unique key (32 chars long) for each session of your Magento admin login. This key is appended to the admin URL as http://your-admin-url/key/743c37b1…adf6588/


This is basically added for security reason. In their release note, Magento say that they added secret key to URL for CSRF (Cross-site request forgery) Attack Prevention.


Sometime you may want to access admin URL without the secret key. For this, you can disable the secret key from admin URL.

Here is how you do it:-

- Login to admin
- Go to System -> Configuration -> ADVANCED -> Admin -> Security -> Add Secret Key to URLs
- Select No
- Save Config

You are done. You will not see the secret key in admin URL nowonwards.

Hope this helps.

Magento: How to change Admin URL Path?

Here is a quick guide on how to change admin url path in Magento. This need to be done for security reason to be safe from hacking/cracking issue. Basically, this is done not to let any general user to access the admin page.

Generally, we do have ‘admin‘ as the administrator path for Magento. So, the admin URL will be http://www.example.com/admin/

This article will show you, how you can change the admin url. Let’s say from ‘admin‘ to ‘backend‘. So, the new admin URL will be http://www.example.com/backend/
Here is how we do it:-

- Open app/etc/local.xml
- Find the following:-

<admin>
 <routers>
  <adminhtml>
   <args>
     <frontName><![CDATA[admin]]></frontName>
   </args>
  </adminhtml>
 </routers>
</admin>

- Change

<frontName><![CDATA[admin]]></frontName>
to your desired name. Like below:-
<frontName><![CDATA[backend]]></frontName>

- Save the file
- Refresh the Cache from Magento Admin (System -> Cache Management)

Now, you should be able to access admin panel from http://www.example.com/backend/ instead of http://www.example.com/admin/

Magento: Disable Admin Notification Popup

Every time you login to Magento Admin panel, by default you will always encounter a notification popup message. If you not want to Pop-up when Login in Admin than simply do
 - Login to admin panel
- Go to System –> Configuration –> Advanced
- Disable Mage_AdminNotification module.
You are done :)