Fetch products with specific attribute value in Magento

In Magento, we have a lot of product attributes. It is difficult to fetch the products with a specific attribute. In this article, we are going to discuss about How to fetch the products with specific attribute value in Magento. To fetch the products, we need to instantiate the Product collection.

Use the below code to instantiate the product collection.

$collection = Mage::getModel('catalog/product')->getCollection();

Magento products are EAV style model. So we need to add additional attributes that you want to return. Use the below codes.

$collection = Mage::getModel('catalog/product')->getCollection();
//fetch name and size into data
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('size');

We can select the attributes as like the below code.

$collection->addAttributeToSelect('*')

There are multiple syntax for setting filters on collections:

//filter for products whose orig_price is greater than (gt) 100
$collection->addFieldToFilter(array(
        array('attribute'=>'price','gt'=>'100'),
));     

//AND filter for products whose orig_price is greater than (lt) 130
$collection->addFieldToFilter(array(
        array('attribute'=>'price','lt'=>'130'),
));

//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
array('attribute'=>'name','eq'=>'Widget A'),
array('attribute'=>'name','eq'=>'Widget B'),
));

foreach ($collection as $product)
{
        //var_dump($product);
        var_dump($product->getData());
}

Below are the list of some most used short conditionals:

eq – equal
neq – not equal
like – %like%
nlike – not %like%
in – in(array…)
nin – not in(array…)
notnull
null
moreq – >=
gt – >
lt – <
gteq – >=
lteq – <=

Steps to solve Magic Quotes Error in Drupal 8 Installation

When we install Drupal 8 we get a Magic Quotes error. In this article, we are going to discuss about, How to solve the Magic quotes error in Drupal 8 installation. Drupal 8 does not support PHP 5.2. It supports only PHP 5.3. Because support for PHP 5.2 ended in September 2011. Most of the hosting companies still not updated their PHP version. Still they are using PHP 5.2. So when we trying to install Drupal 8 in those hosting environment, we will produces the below error message.

PHP's 'magic_quotes_gpc' and 'magic_quotes_runtime' setting are not supported and must be disabled.

Here are the steps to solve the Magic Quotes error.

Step 1 : Create php.ini file

Create a php.ini file in the root folder of your drupal 8 and add the below codes in the php.ini file.

magic_quotes_gpc = Off
extension=pdo.so
extension=pdo_mysql.so

It will not required you to ask your hosting company to change the php.ini. you can create your own php.ini and use it for your website.

Step 2 : Edit the .htaccess file

After creating the php.ini file, open the .htaccess file and add the below codes to use your own php.ini file.

<IfModule mod_suphp.c>
suPHP_ConfigPath /home/username/public_html/Drupal8folder
<Files php.ini>
order allow,deny
deny from all
</Files>
</IfModule>

Step 3 : Recheck

Now try to install Drupal 8. It will not produces any magic_quotes error. 

Steps to override/rewrite model class in Magento

In this article, we are going to discuss about How to override/rewrite the model class in Magento. In most of the cases we need to extend the Magento core functionality. For that we have to copy the core model class file to the local directory from core. Then, we can override/rewrite the core model class.

Here we are going to discuss about How to override the sales order model (Mage_Sales_Model_Order class).

Step 1 : Create a config.xml file for the new module

Create a new config.xml file in "/app/code/local/MyCompany/NewModule/etc/" folder and add the below codes in the config.xml file.

<global>
    <models>
        <sales>
            <rewrite>
                <order>MyCompany_NewModule_Model_Order</order>
            </rewrite>
        </sales>
    </models>
</global>

By using the above code, we have overloaded the Mage_Sales_Model_Order class with the MyCompany_NewModule_Model_Order class.

Step 2 : Create the new module

After creating a config.xml file, we need to create a new extended order class "order.php" file in "/app/code/local/MyCompany/NewModule/Model/" folder and add the below code in the order.php file.

<?php
class MyCompany_NewModule_Model_Order extends Mage_Sales_Model_Order
{
    public function newFunctions()
    {
                 //new functions/methods content
    }

    public function existingFunctions()
    {
                 //new functions/methods content with the extended functionalities
    }
}

We have created a new model class which extends the core model class. That means the new class will have all the properties and functions the core class has. All the functions we put in our new class will be used instead of the core classes functions, and we can also add completely new functions to it.

Step 3 : create the new modules initialization xml

Create a "MyCompany_NewModule.xml" file in the folder "/app/etc/" and add the below code in the file.

<?xml version="1.0"?>
<config>
  <modules>
    <MyCompany_NewModule>
      <active>true</active>
      <codePool>local</codePool>
    </MyCompany_NewModule>
  </modules>
</config>

By placing the above file in that directory, Magento will know that it has to look for a "config.xml" in "/app/code/local/MyCompany/NewModule/etc" and load our module.

That's all. Try it yourself.

Steps to install Magento on server using SSH

In this article, I am going to explain the step by step procedure to install Magento on server using SSH (Secure SHell). By using SSH, we can able to install Magento on server in few minutes. Before installing Magento, we need to check whether the hosting server is compatible with magento.

Step 1 :

To check the hosting server compatibility, read the Magento Requirements page carefully, and make sure your server meets those. To test the server, download the magento-check file from the Magento website and run the "magento-check.php" file on the server by navigating like "magento/magento-check.php".

Click Here to download the magento-check file. (http://www.magentocommerce.com/_media/magento-check.zip)

Step 2 :

Login to your hosting environmant usign SSH with your valid SSH username and password.

Step 3 :

Run the below commands in SSH command line.

wget http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gzs
tar -zxvf magento-1.8.1.0.tar.gz
mv magento/* magento/.htaccess .
chmod -R o+w media
./pear mage-setup .
./pear install magento-core/Mage_All_Latest-stable
touch var/.htaccess | mkdir app/etc
chmod o+w var var/.htaccess app/etc
rm -rf downloader/pearlib/cache/* downloader/pearlib/download/*
rm -rf magento/ magento-1.8.1.0.tar.gz

Step 4 :

If you run into an error like:

exec: 94: php not found error 

trying to run

sudo ./pear mage-setup 

then the php client is not installed properly. To solve this install it using this:

sudo apt-get install php5-cli

Step 5:

Run the Web-Based Installer to Finish the Installation. Your Magento site is up and running. You may also install custom extensions using ssh protocol like this:

./pear install EXTENSION_KEY

Steps to create Joomla Components with Component Creator

In this article, we are going to discuss about How to create Joomla components using Component creator. we can create our own Joomla component from the website (http://www.component-creator.com). It is absolutely free. From this website, developers have created more than 10,000 components for Joomla. In this article, we going to discuss about step by step procedure to create Joomla component using Component creator website.

Step 1:

To create an own joomla component in component creator website, we need to create a new user account. (It's free). Click on the below link and create an account.

http://www.component-creator.com

Step 2:

After creating an account, login in to the website and click on the button "Add Component".

Step 3 :

Enter the following details to create a new Joomla component.

Name - Name of your component. Use the prefix (com_) - Be sure you use a unique when you create several components.
Display Name - This one will be displayed in your menu under "Components" section.
Target Joomla version - Select the joomla version. It supports Joomla 2.5 and Joomla 3.x.x

Also you can select the language, Copyright information, license information, Author Details.

After entering all the above details click on the "Save Component" button.

Now you will get a success message like "Component saved successfully. How about adding a table".

Step 4: Add tables

Adding a database table to your newly created component is the way that you will get a back-end and front-end interface for managing content.

To add table to your component follow the below steps.

  1. Click on the "Manually add tables" button.
  2. Add the table's name using as prefix #__yourcomponent_ like: #__yourcomponent_mytable
  3. Mark the checkbox to create the list view in administrator. Use the plural of the name to displays a label, like: My Tables
  4. Check the checkbox to add the form view in administrator. Place the label name for this one.
  5. Check the checkbox to enable the Frontend view.
  6. Check the checkbox to enable the ACL Control.
  7. After entering all the above details click on the "Create table" button. 

Now you will get a success message like "Your table was added successfully".

Step 5: Add fields to your table

You may need to add custom fields to manage and display custom content.

  1. Click on the "Add field" button.
  2. Field name - unique name; use lowercase without spaces.
  3. Fieldtype - like text, textarea, checkbox, radio buttons, etc.
  4. Optional fields.
  5. Check the checkbox to enable the form view and assign a custom name.
  6. Check the checkbox to enable a list view.
  7. After entering all the above details click on the "Add field" button.

Step 6 : Build the component

Now, you have a custom component with a single table. Now its time to generate the installer zip package.

Click on the "Build" button on the right or in the list of your components.

You'll get a message saying the the extension was created. The next extension file will have a name like this: com_yourcomponent-1.0.0.zip.

Integrating Facebook Connect with CakePHP Auth Component

In this article, we are going to discuss about How to intergate the Facebook connect with Cakephp Auth component. By connecting Facebook connect with cakephp Auth component, we can allow both normal user account users and Facebook connect generated users can access the application. we can achieve by dynamically set the Auth->fields.

Follow the below steps to integrate the Facebook connect with the cakephp Auth component.

Step 1 :

Delete the Facebook client libraries from "app/vendors/facebook" folder. In your "app_controller", import the classes, and set the below properties.

<?php
App::import('Vendor', 'facebook/facebook');
class AppController extends Controller {
    var $components = array('Auth');
    var $uses = array('User');
    var $facebook;
    var $__fbApiKey = 'your_key';
    var $__fbSecret = 'your_secret';
}

Step 2 : 

To instantiate a Facebook Object, overwrite the inherited "__construct" method like below.

function __construct() {
    parent::__construct();
        
    // Prevent the 'Undefined index: facebook_config' notice from being thrown.
    $GLOBALS['facebook_config']['debug'] = NULL;
        
    // Create a Facebook client API object.
    $this->facebook = new Facebook($this->__fbApiKey, $this->__fbSecret);

  }

Step 3 :


In our "beforeFiltermethod, we define the default Auth properties, call a private __checkFBStatus method, and pass any user data to the view:

function beforeFilter() {
    // Authentication settings
    $this->Auth->fields = array('username' => 'email', 'password' => 'password');
    $this->Auth->logoutRedirect = '/';

    //check to see if user is signed in with facebook
    $this->__checkFBStatus();

    //send all user info to the view
    $this->set('user', $this->Auth->user());
}

Step 4 :


Define the "private method __checkFBStatus" that's called in our "beforeFilter" method. Before that, we need check to make sure "$this->Auth->User" isn't already set by a normal user account, and we check to see if there's a logged in Facebook user. The logged in facebook user is available after we use the JavaScript API to log facebook users into the site.

private function __checkFBStatus(){
        //check to see if a user is not logged in, but a facebook user_id is set
        if(!$this->Auth->User() &amp;&amp; $this->facebook->get_loggedin_user()):

Step 5 :

Check if the user is already logged in and also check already has an entry in our User table.

//see if this facebook id is in the User database; if not, create the user using their fbid hashed as their password
$user_record =
    $this->User->find('first', array(
        'conditions' => array('fbid' => $this->facebook->get_loggedin_user()),
        'fields' => array('User.fbid', 'User.fbpassword', 'User.password'),
        'contain' => array()
    ));

Step 6:

If no record was found, we create a new record for this user. We are setting 3 variables, fbid, fbpassword, and password. The fbpassword field will hold a randomly generated 20 character string un-hashed so that we can access the value of the field directly from the database. We retrieve this value based on the fbid field, hash it, and that's our password as the Auth Component expects:

//create new user
if(empty($user_record)):
    $user_record['fbid'] = $this->facebook->get_loggedin_user();
    $user_record['fbpassword'] = $this->__randomString();
    $user_record['password'] = $this->Auth->password($user_record['fbpassword']);
    
    $this->User->create();
    $this->User->save($user_record);
endif;

Step 7:

We need to then update our Auth Component's fields property to use fbid as the username.

//change the Auth fields
    $this->Auth->fields = array('username' => 'fbid', 'password' => 'password');

    //log in the user with facebook credentials
    $this->Auth->login($user_record);
    
endif;
}

Step 8:

Here's the complete app_controller.php:

<?php
App::import('Vendor', 'facebook/facebook');

class AppController extends Controller {
    var $components = array('Auth');
    var $uses = array('User');
  var $facebook;
  var $__fbApiKey = 'your_key';
  var $__fbSecret = 'your_secret';
    
  function __construct() {
    parent::__construct();
        
    // Prevent the 'Undefined index: facebook_config' notice from being thrown.
    $GLOBALS['facebook_config']['debug'] = NULL;
        
    // Create a Facebook client API object.
    $this->facebook = new Facebook($this->__fbApiKey, $this->__fbSecret);
  }

    function beforeFilter() {
    // Authentication settings
    $this->Auth->fields = array('username' => 'email', 'password' => 'password');
    $this->Auth->logoutRedirect = '/';

        //check to see if user is signed in with facebook
        $this->__checkFBStatus();

        //send all user info to the view
        $this->set('user', $this->Auth->user());
  }

    private function __checkFBStatus(){
        //check to see if a user is not logged in, but a facebook user_id is set
        if(!$this->Auth->User() &amp;&amp; $this->facebook->get_loggedin_user()):

            //see if this facebook id is in the User database; if not, create the user using their fbid hashed as their password
            $user_record =
                $this->User->find('first', array(
                    'conditions' => array('fbid' => $this->facebook->get_loggedin_user()),
                    'fields' => array('User.fbid', 'User.fbpassword', 'User.password'),
                    'contain' => array()
                ));

            //create new user
            if(empty($user_record)):
                $user_record['fbid'] = $this->facebook->get_loggedin_user();
                $user_record['fbpassword'] = $this->__randomString();
                $user_record['password'] = $this->Auth->password($user_record['fbpassword']);
                
                $this->User->create();
                $this->User->save($user_record);
            endif;

            //change the Auth fields
            $this->Auth->fields = array('username' => 'fbid', 'password' => 'password');

            //log in the user with facebook credentials
            $this->Auth->login($user_record);
            
        endif;
    }

    private function __randomString($minlength = 20, $maxlength = 20, $useupper = true, $usespecial = false, $usenumbers = true){
        $charset = "abcdefghijklmnopqrstuvwxyz";
        if ($useupper) $charset .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        if ($usenumbers) $charset .= "0123456789";
        if ($usespecial) $charset .= "~@#$%^*()_+-={}|][";
        if ($minlength > $maxlength) $length = mt_rand ($maxlength, $minlength);
        else $length = mt_rand ($minlength, $maxlength);
        $key = '';
        for ($i=0; $i<$length; $i++){
            $key .= $charset[(mt_rand(0,(strlen($charset)-1)))];
        }
        return $key;
    }

}
?>

Step 9 :

Next we need to make a few changes to our default.ctp layout; first add the facebook namespace.

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">

Step 10:

Add these 2 javascript snippets.

<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"></script>
<script type="text/javascript">FB.init("your_api_key","/xd_receiver.htm");</script>

Step 11:

Last step, place your login and logout buttons in your default view. Few things to point out here; onlogin="window.location.reload();" will cause the page to reload after a successful Facebook Connect login. This is how we are able to access $this->facebook->get_loggedin_user() in our app_controller to force the manual Auth login. If the user is a facebook user (determined with $user['User']['fbid'] > 0), add an onclick event that calls the FB.Connect.logout() function with a redirect URL as the parameter. This will log the User out of the Auth Component after it logs the user out of Facebook.

<?php
if(!empty($user)):
if($user['User']['fbid'] > 0):
echo $html->link('logout', '#', array('onclick' => 'FB.Connect.logout(function() { document.location = \'http://your_server/users/logout/\'; }); return false;'));
else:
echo $html->link('logout', array('controller' => 'users', 'action' => 'logout'));
endif;
else:
echo '<fb:login-button onlogin="window.location.reload();"></fb:login-button>';
endif;

?>

One last thing to consider, for security reasons… In your login method, be sure only users with fbid = 0 can login via the normal auth fields (username / password). Just an extra precaution considering you have an unhashed password in your database for those facebook users.

Steps to remove index.php from Codeigniter URL

In this article, we are going to discuss about How to enable SEF url in CodeIgniter (CI). We can get the SEF url by removing the index.php from the URL. If you are using Codeigniter you are noticed that by default index.php will be included with your URL. In this article I am going to explain about How to remove the index.php from the CodeIgniter (CI) site URL.

By removing the index.php from the URL we can get the site URL like below

http://domain.com/about

To acheive this, follow the below steps.

Step 1 :

Open the folder "system/application/config" and open the file "config.php". find and replace the below code in config.php file.

find the below code

$config['index_page'] = "index.php" 

replace with the below code

$config['index_page'] = ""


Step 2 :

Create ".htaccess" file in the root of CodeIgniter (CI) directory. Then the below codes in the ".htaccess" file.

RewriteEngine on
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

In some case the default setting for uri_protocol does not work properly. To solve this problem just open the file "system/application/config/config.php", then find and replace the below code

find the below code

$config['uri_protocol'] = "AUTO" 

replace with the below code

$config['uri_protocol'] = "REQUEST_URI" 

Tips to secure your wordpress site using .htaccess

In this article, I am going to provide some tips to secure your Wordpress website using .htaccess. Wordpress is a popular CMS among everyone. Because Wordpress is easy to use and install. It is very easy to learn. When you installing the wordpress, you have to make sure that how safe is your install.

In this post, I am going to share few security tips to your wordpress cms/blog using .htaccess file. Below are the 3 important files/folders to be considered while thinking about security
  1. wp-config.php
  2. wp-contents folder
  3. .htaccess file

Tip 1 : Protect your wp-config.php


wp-config.php is the main configuration file which resides in your root directory that stores information about your site as well as database details, this file in particular we would not want to fall into the wrong hands.

In your .htaccess add the following to prevent any access to the wp-config.php file:

<Files wp-config.php>
order allow,deny
deny from all
</Files>

Tip 2 : No directory browsing

As WordPress is now so popular many people know the structure of a WordPress install and know where to look to discover what plug-ins you may use or any other files that might give away too much information about your site, one way to combat this is to prevent directory browsing

Options All -Indexes

Tip 3 : Prevent Access To wp-content

The wp-content folder contains images, themes and plug-ins and it's a very important folder within your WordPress install, so it makes sense to prevent outsiders accessing it.

This requires it's very own .htaccess file which must be added to the wp-content folder, it allows users to see images, CSS etc … but protects the important PHP files:

Order deny,allow
Deny from all
<Files ~ ".(xml|css|jpe?g|png|gif|js)$">
Allow from all
</Files>

Tip 4 : Protect .htaccess

This below code actually stops anyone viewing any file on your site that begins with "hta", this will protect it and make it safer.

<Files ~ "^.*.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>

Please don't forget to share and subscribe to latest updates of the blog.

Thanks. Have a great day.

Steps to change the Default Admin Username in WordPress

Most of the Wordpress users struggling to change the default Wordpress Administrator username (Admin) with the new username. In this article, we are going to discuss about how to change the default Wordpress administrator username without entering into the website. Here I am going to explain about, How to change the admin username in the database. On every Wordpress installation will create an account with the default administrator username (Admin). Being able to change this default username, will give your WordPress admin panel additional security.

Step to change default username into your new name:

UPDATE wp_users SET user_login = 'YourNewUsername' WHERE user_login = 'Admin';

Please don't forget to share and subscribe to latest updates of the blog.

Thanks. Have a great day!