Magento
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 – <=
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 – <=
PHP CMS Frameworks
December 29, 2013
Read more →
Drupal
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.
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.
PHP CMS Frameworks
December 25, 2013
Read more →
Magento
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.
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.
PHP CMS Frameworks
December 22, 2013
Read more →
Magento
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
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
PHP CMS Frameworks
December 18, 2013
Read more →
Joomla
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.
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.
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.
- Click on the "Manually add tables" button.
- Add the table's name using as prefix #__yourcomponent_ like: #__yourcomponent_mytable
- Mark the checkbox to create the list view in administrator. Use the plural of the name to displays a label, like: My Tables
- Check the checkbox to add the form view in administrator. Place the label name for this one.
- Check the checkbox to enable the Frontend view.
- Check the checkbox to enable the ACL Control.
- 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.
- Click on the "Add field" button.
- Field name - unique name; use lowercase without spaces.
- Fieldtype - like text, textarea, checkbox, radio buttons, etc.
- Optional fields.
- Check the checkbox to enable the form view and assign a custom name.
- Check the checkbox to enable a list view.
- 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.
PHP CMS Frameworks
December 15, 2013
Read more →
CakePHP
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 "beforeFilter" method, 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() && $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() && $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.
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 "beforeFilter" method, 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() && $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() && $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.
PHP CMS Frameworks
December 11, 2013
Read more →
CodeIgniter
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"
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"
PHP CMS Frameworks
December 08, 2013
Read more →
Wordpress
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
- wp-config.php
- wp-contents folder
- .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.
PHP CMS Frameworks
December 04, 2013
Read more →
Wordpress
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!
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!
PHP CMS Frameworks
December 01, 2013
Read more →
CodeIgniter
Steps to implement Memcache in Codeigniter
In this article, we are going to discuss about How to implement memcache in CodeIgniter (CI). Memcache is used to increase the performance of the websute (ie, speed-up the website) by using the memory space of our used domains and store the database query results in that cache and minimise the application-database interaction.
Step 1:
Before we implement Memcache in CodeIgniter (CI), we need to check whether the memcache is enabled in our web server or not. If it is not enabled, then enable it by uncomment the 'extension=php_memcache.dll' in php.ini file in the server. (Just remove the ";" symbol infront of the line).
Step 2:
Download the Memcache executable file to install the Memcache in the webserver. To download the Memacache executable file, Click on the below link
Download link - http://code.jellycan.com/files/memcached-1.2.6-win32-bin.zip
Step 3:
Once downloaed, Unzip the downloaded file, you will get a memcached executable file. Store that in a web server to install.
Step 4:
Then open the command prompt and run this command
c:/xampp/htdocs/memcached.exe -d install
then run the below command
'c:/xampp/htdocs/memcached.exe -d start'
Step 5:
Download the cache driver from the below URL
http://d45jz936mo8n8.cloudfront.net/wp-content/uploads/2010/01/Cache.php_1.zip
Once downloaded, Unzip and place the cache.php in system/libraries/cache folder.
Step 6:
Create an empty folder named "cache" on the location system folder.
Step 7:
Load the Cache driver in controller CodeIgniter (CI) application
$this->load->driver('cache');
Add the following lines of code where needed to cache the query result.
$cache = $this->cache->get('cache_data');
if($cache)
{
$data = $this->cache->get('cache_data');
}
else
{
$data = $this->sample_model->get_data();
$this->cache->save('cache_data', $data, NULL, 3600);
}
While accessing the webpage, it will execute query on the database for the first time, then the result will be stored in cache upto the refreshing time given in the save() function above.
So until the time exceeds, whenever the user refreshes the page, the application will not interact with the database. instead it will retrieve from cache and display.
This caching is applicable only for the select queries and the static updates.
Step 1:
Before we implement Memcache in CodeIgniter (CI), we need to check whether the memcache is enabled in our web server or not. If it is not enabled, then enable it by uncomment the 'extension=php_memcache.dll' in php.ini file in the server. (Just remove the ";" symbol infront of the line).
Step 2:
Download the Memcache executable file to install the Memcache in the webserver. To download the Memacache executable file, Click on the below link
Download link - http://code.jellycan.com/files/memcached-1.2.6-win32-bin.zip
Step 3:
Once downloaed, Unzip the downloaded file, you will get a memcached executable file. Store that in a web server to install.
Step 4:
Then open the command prompt and run this command
c:/xampp/htdocs/memcached.exe -d install
then run the below command
'c:/xampp/htdocs/memcached.exe -d start'
Step 5:
Download the cache driver from the below URL
http://d45jz936mo8n8.cloudfront.net/wp-content/uploads/2010/01/Cache.php_1.zip
Once downloaded, Unzip and place the cache.php in system/libraries/cache folder.
Step 6:
Create an empty folder named "cache" on the location system folder.
Step 7:
Load the Cache driver in controller CodeIgniter (CI) application
$this->load->driver('cache');
Add the following lines of code where needed to cache the query result.
$cache = $this->cache->get('cache_data');
if($cache)
{
$data = $this->cache->get('cache_data');
}
else
{
$data = $this->sample_model->get_data();
$this->cache->save('cache_data', $data, NULL, 3600);
}
While accessing the webpage, it will execute query on the database for the first time, then the result will be stored in cache upto the refreshing time given in the save() function above.
So until the time exceeds, whenever the user refreshes the page, the application will not interact with the database. instead it will retrieve from cache and display.
This caching is applicable only for the select queries and the static updates.
PHP CMS Frameworks
November 27, 2013
Read more →
CodeIgniter
Execute Cron Job in CodeIgniter using PHP Curl
In this article we are going to discuss about, How to execute Cron Job in CodeIgniter (CI) using PHP. Codeigniter (CI) runs based on the front controller pattern where all the requests are routed using the index.php file. So we need to go through the routing procedures to execute any code on CodeIgniter (CI) application. Basically if we need to run cron job, we need to create the code files and placed it in the server and call the files in the cron job using path to files.
But in CodeIgniter (CI) applications, it is not much easy to call the cron job files and use CodeIgniter models inside this scripts. You need to load all the required models and files manually. We cannot achieve this using normal php script calling procedure.
Curl:
PHP Curl extension is used to transfer data from server to another server using various methods. In this example we need to execute a remote url using normal http method in curl.
Steps to install Curl in Windows:
You have to allow the curl extension by removing ';' in the php.ini file and restart apache server.
Steps to install Curl in Fedora:
Type the following command in the terminal using the super user.
yum install php-curl
Steps to install Curl in Ubuntu:
Type the following command in the terminal using the super user.
apt-get install php-curl
Setting the Cronjob using Curl
You can set up the cronjob to call the CodeIgniter (CI) url using the following line of code.
/usr/bin/curl http://www.example.com/controller/cron_function
Open the crontab using the terminal and enter the above line of code and restart the cron. Use the path to the curl file according to your installed location. Call the cron function of your site remotely using http.
But in CodeIgniter (CI) applications, it is not much easy to call the cron job files and use CodeIgniter models inside this scripts. You need to load all the required models and files manually. We cannot achieve this using normal php script calling procedure.
Curl:
PHP Curl extension is used to transfer data from server to another server using various methods. In this example we need to execute a remote url using normal http method in curl.
Steps to install Curl in Windows:
You have to allow the curl extension by removing ';' in the php.ini file and restart apache server.
Steps to install Curl in Fedora:
Type the following command in the terminal using the super user.
yum install php-curl
Steps to install Curl in Ubuntu:
Type the following command in the terminal using the super user.
apt-get install php-curl
Setting the Cronjob using Curl
You can set up the cronjob to call the CodeIgniter (CI) url using the following line of code.
/usr/bin/curl http://www.example.com/controller/cron_function
Open the crontab using the terminal and enter the above line of code and restart the cron. Use the path to the curl file according to your installed location. Call the cron function of your site remotely using http.
PHP CMS Frameworks
November 24, 2013
Read more →
Magento
Magento - Create an external Database Connection
Normally we are all experienced with connecting the database with Magento. But in this article, we are going to discuss about How to create an external database connection in Magento. Hopefully, by presenting this code here, I can save you from the pain I endured :)
Creating a database Connection
To create a new connection, create a custom module and add the following codes to your config.xml. The code below is needed to get the external database connection working.
<?xml version="1.0"?>
<config>
<modules>
<PHPCmsframework_Externaldb>
<version>0.1.0</version>
</PHPCmsframework_Externaldb>
</modules>
<global>
<resources>
<externaldb_write>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_write>
<externaldb_read>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_read>
<externaldb_setup>
<connection>
<use>core_setup</use>
</connection>
</externaldb_setup>
<externaldb_database>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[db_username]]></username>
<password><![CDATA[db_password]]></password>
<dbname><![CDATA[db_name]]></dbname>
<model>mysql4</model>
<type>pdo_mysql</type>
<active>1</active>
</connection>
</externaldb_database>
</resources>
</global>
</config>
Clear the cache after creating your new module and from now on, each time you load Magento, a second database connection will be created.
Accessing an external Database
When I initially checked out how to create an external database connection, I was using Zend_Db to retrieve all of my information. You can use the following to test your database connection is working:
<?php
$resource = Mage::getSingleton('core/resource');
$conn = $resource->getConnection('externaldb_read');
$results = $conn->query('SELECT * FROM tblName');
print_r($results);
The above code is working fine, however kind of takes the point away from having this connection available in Magento.
Accessing an External Database Using Models
Using models to access the database keeps our code style uniform throughout Magento. Also, it means we can integrate any other CMS or database driven application without learning it's coding practices. To achieve this, simply add models to your custom module like you would for any other module.
I will attempt to demonstrate how to set up the models and config.xml files now.
Creating The Model Class Files
Create the following files:
code/local/PHPCmsframework/Externaldb/Model/Book.php
<?php
class PHPCmsframework_Externaldb_Model_Book extends Mage_Core_Model_Abstract
{
public function _construct()
{
$this->_init('externaldb/book');
}
}
code/local/PHPCmsframework/Externaldb/Model/Mysql4/Book.php
<?php
class PHPCmsframework_Externaldb_Model_Mysql4_Book extends Mage_Core_Model_Mysql4_Abstract
{
public function _construct()
{
$this->_init('externaldb/book', 'book_id'); // book_id refers to the primary key of the book table
}
}
code/local/PHPCmsframework/Externaldb/Model/Mysql4/Book/Collection.php
<?php
class PHPCmsframework_Externaldb_Model_Mysql4_Book_Collection extends Mage_Core_Model_Mysq4_Collection_Abstract
{
public function _construct()
{
$this->_init('externaldb/book');
}
}
That's the minimum needed for your models to be able to access an external database!
Adding the Models to The Config
To inform Magento about our models, we need to register them in config.xml. Below is an updated version of config.xml with the models for Book registered.
<?xml version="1.0"?>
<config>
<modules>
<PHPCmsframework_Externaldb>
<version>0.1.0</version>
</PHPCmsframework_Externaldb>
</modules>
<global>
<models>
<externaldb>
<class>PHPCmsframework_Externaldb_Model</class>
<resourceModel>externaldb_mysql4</resourceModel>
</externaldb>
<externaldb_mysql4>
<class>PHPCmsframework_Externaldb_Model_Mysql4</class>
<entities>
<book>
<table>library_book</table>
</book>
</entities>
</externaldb_mysql4>
</models>
<resources>
<externaldb_write>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_write>
<externaldb_read>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_read>
<externaldb_setup>
<connection>
<use>core_setup</use>
</connection>
</externaldb_setup>
<externaldb_database>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[db_username]]></username>
<password><![CDATA[db_password]]></password>
<dbname><![CDATA[db_name]]></dbname>
<model>mysql4</model>
<type>pdo_mysql</type>
<active>1</active>
</connection>
</externaldb_database>
</resources>
</global>
</config>
That's it, the models should now be registered in Magento!
Testing The Models
Testing them is easy enough, just treat them like normal Magento models.
<?php
// Load the book with a primary key value of 4
$_book = Mage::getModel('externaldb/book')->load(4);
// This would print out the value in the field isbn in the external database
echo $_book->getIsbn();
//You can even update records!
$_book->setName('1984');
$_book->setAuthor('George Orwell');
try {
$_book->save();
} catch (Exception $e) {
exit($e->getMessage());
}
This is one of my favaourite article. So I probably haven't written this up as well as I could have, however, I think that using a second database in Magento can be extremely useful.
Creating a database Connection
To create a new connection, create a custom module and add the following codes to your config.xml. The code below is needed to get the external database connection working.
<?xml version="1.0"?>
<config>
<modules>
<PHPCmsframework_Externaldb>
<version>0.1.0</version>
</PHPCmsframework_Externaldb>
</modules>
<global>
<resources>
<externaldb_write>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_write>
<externaldb_read>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_read>
<externaldb_setup>
<connection>
<use>core_setup</use>
</connection>
</externaldb_setup>
<externaldb_database>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[db_username]]></username>
<password><![CDATA[db_password]]></password>
<dbname><![CDATA[db_name]]></dbname>
<model>mysql4</model>
<type>pdo_mysql</type>
<active>1</active>
</connection>
</externaldb_database>
</resources>
</global>
</config>
Clear the cache after creating your new module and from now on, each time you load Magento, a second database connection will be created.
Accessing an external Database
When I initially checked out how to create an external database connection, I was using Zend_Db to retrieve all of my information. You can use the following to test your database connection is working:
<?php
$resource = Mage::getSingleton('core/resource');
$conn = $resource->getConnection('externaldb_read');
$results = $conn->query('SELECT * FROM tblName');
print_r($results);
The above code is working fine, however kind of takes the point away from having this connection available in Magento.
Accessing an External Database Using Models
Using models to access the database keeps our code style uniform throughout Magento. Also, it means we can integrate any other CMS or database driven application without learning it's coding practices. To achieve this, simply add models to your custom module like you would for any other module.
I will attempt to demonstrate how to set up the models and config.xml files now.
Creating The Model Class Files
Create the following files:
code/local/PHPCmsframework/Externaldb/Model/Book.php
<?php
class PHPCmsframework_Externaldb_Model_Book extends Mage_Core_Model_Abstract
{
public function _construct()
{
$this->_init('externaldb/book');
}
}
code/local/PHPCmsframework/Externaldb/Model/Mysql4/Book.php
<?php
class PHPCmsframework_Externaldb_Model_Mysql4_Book extends Mage_Core_Model_Mysql4_Abstract
{
public function _construct()
{
$this->_init('externaldb/book', 'book_id'); // book_id refers to the primary key of the book table
}
}
code/local/PHPCmsframework/Externaldb/Model/Mysql4/Book/Collection.php
<?php
class PHPCmsframework_Externaldb_Model_Mysql4_Book_Collection extends Mage_Core_Model_Mysq4_Collection_Abstract
{
public function _construct()
{
$this->_init('externaldb/book');
}
}
That's the minimum needed for your models to be able to access an external database!
Adding the Models to The Config
To inform Magento about our models, we need to register them in config.xml. Below is an updated version of config.xml with the models for Book registered.
<?xml version="1.0"?>
<config>
<modules>
<PHPCmsframework_Externaldb>
<version>0.1.0</version>
</PHPCmsframework_Externaldb>
</modules>
<global>
<models>
<externaldb>
<class>PHPCmsframework_Externaldb_Model</class>
<resourceModel>externaldb_mysql4</resourceModel>
</externaldb>
<externaldb_mysql4>
<class>PHPCmsframework_Externaldb_Model_Mysql4</class>
<entities>
<book>
<table>library_book</table>
</book>
</entities>
</externaldb_mysql4>
</models>
<resources>
<externaldb_write>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_write>
<externaldb_read>
<connection>
<use>externaldb_database</use>
</connection>
</externaldb_read>
<externaldb_setup>
<connection>
<use>core_setup</use>
</connection>
</externaldb_setup>
<externaldb_database>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[db_username]]></username>
<password><![CDATA[db_password]]></password>
<dbname><![CDATA[db_name]]></dbname>
<model>mysql4</model>
<type>pdo_mysql</type>
<active>1</active>
</connection>
</externaldb_database>
</resources>
</global>
</config>
That's it, the models should now be registered in Magento!
Testing The Models
Testing them is easy enough, just treat them like normal Magento models.
<?php
// Load the book with a primary key value of 4
$_book = Mage::getModel('externaldb/book')->load(4);
// This would print out the value in the field isbn in the external database
echo $_book->getIsbn();
//You can even update records!
$_book->setName('1984');
$_book->setAuthor('George Orwell');
try {
$_book->save();
} catch (Exception $e) {
exit($e->getMessage());
}
This is one of my favaourite article. So I probably haven't written this up as well as I could have, however, I think that using a second database in Magento can be extremely useful.
PHP CMS Frameworks
November 20, 2013
Read more →
Magento
Magento - Load a Category OR Product by an attribute
In this article, we are going to discuss about How to load a categort or a product by an attribute. Most of the developers are often searching for how to load a product by a particular attribute. This article is quite easy to achieve this in Magento and can be done using Magento collections.
Load a Product By SKU
In magento, we have lot of pre defined product attributes. SKU is a static attribute. This means that instead of being stored in one of the products EAV tables, it is stored in the main product entity table (catalog_product_entity). This makes loading a product based on it's SKU much easier and efficient.
<?php
$sku = 'my-product-sku';
$product = Mage::getModel('catalog/product')->load($sku, 'sku');
if ($product->getId()) {
echo $product->getName();
}
else {
echo 'Product not found with SKU of ' . $sku;
}
The above code is used to makes the use of load method, which is available for all EAV entities in Magento. By default this method takes two parameters:
Load a Product By SKU
In magento, we have lot of pre defined product attributes. SKU is a static attribute. This means that instead of being stored in one of the products EAV tables, it is stored in the main product entity table (catalog_product_entity). This makes loading a product based on it's SKU much easier and efficient.
<?php
$sku = 'my-product-sku';
$product = Mage::getModel('catalog/product')->load($sku, 'sku');
if ($product->getId()) {
echo $product->getName();
}
else {
echo 'Product not found with SKU of ' . $sku;
}
The above code is used to makes the use of load method, which is available for all EAV entities in Magento. By default this method takes two parameters:
- A value that is used to match the product and the field that the values is checked against.
- If the second parameter is empty, Magento will use the primary key, which is usually the model ID. By passing a static attribute (SKU is the only useful static attribute for this context), it is possible to load a product model on a different value.
Load a product by an Attribute
The most of product attributes that you work with in Magento will not be static attributes and their values will be separated across several different tables. oading a product by a value that's stored like this is less efficient as several Magento tables will need to be joined to locate the product you are looking for. This doesn't mean that you shouldn't do it, it's just always good to be aware of such performance factors.
<?php
// Instantiate a product collection object
$products = Mage::getResourceModel('catalog/product_collection');
// Select which fields to load into the product
// * will load all fields but it is possible to pass an array of
// select fields to load
$products->addAttributeToSelect('*');
// Ensure the product is visible
$products->addAttributeToFilter('visibility', array('neq' => 1));
// Ensure the product is enabled
$products->addAttributeToFilter('status', 1);
// Add Name filter
$products->addAttributeToFilter('name', 'My Product Name');
// Limit the collection to 1 result
$products->setCurPage(1)->setPageSize(1);
// Load the collection
$products->load();
if ($products->getFirstItem()) {
$product = $products->getFirstItem();
echo $product->getName();
}
else {
echo 'No product exists with the name ' . $name;
}
The above code is a lot longer than the code we used to load by SKU, but hopefully you can see the power and flexibility of the Magento collection code. Line #17 is where the filter is added to filter by name, but the rest of the code is required to ensure that the product returned is a valid product.
If you are wondering what the SQL query the above generates, add the following line anywhere before line #23.
<?php
// Print out the SQL query generated by the collection object so far
echo $products->getSelect() . '<br/><br/>';
Load a Category by an Attribute
Load a category by an attribute is almost exactly the same. The reason for this is that both products and categories use Magento's EAV database structure and both extend from the same base classes, which provide the core collection functionality (as do the majority of Magento model's).
<?php
// Instantiate a category collection object
$categories = Mage::getResourceModel('catalog/categories_collection');
// Select which fields to load into the category
// * will load all fields but it is possible to pass an array of
// select fields to load
$categories->addAttributeToSelect('*');
// Ensure the category is active
$categories->addAttributeToFilter('is_active', 1);
// Add Name filter
$categories->addAttributeToFilter('name', 'My Category Name');
// Limit the collection to 1 result
$categories->setCurPage(1)->setPageSize(1);
// Load the collection
$categories->load();
if ($categories->getFirstItem()) {
$category = $categories->getFirstItem();
echo $category->getName();
}
else {
echo 'No category exists with the name ' . $name;
}
The main difference when working with categories is the resource model name (line #3) and the filter for the `is_active` attribute.
Hopefully you can see how flexible and powerful the Magento collection system is. I recommend that you print out the SQL query command for your collections so you can understand what Magento is doing in the background. Although Magento protects you from really needing to know this information, understanding it will make you a better developer and if you're like me, you'll find it interesting to disect the SQL!
PHP CMS Frameworks
November 10, 2013
Read more →
CakePHP
CakePHP - Save page output as HTML
In this article, we are going to discuss about How to Save page output as HTML with cakePHP. As of now, I am working on a project that requres store the dynamically created output HTML files on a CDN (Content Delivery Network). I need to dynamically create a HTML page with database data and then store that HTML file on a CDN (Amazon S3) which cannot parse PHP.
I was looking for a way to output a view, and save it as an HTML file which could then be uploaded via the S3 API. In the CakePHP API, we see the Controller render method returns the output of the View model's render method which returns a string of the HTML output to be loaded in the browser. But we don't want to call the Controller's render method as that will send the user's browser to that page. Instead we want to use the View's render method so we get the string value that can be saved into an HTML file.
Assume we have a publish controller method which is called when the user wants to publish the HTML file. We also have a private method to generate the HTML and save it as a file in the local filesystem.
<?php
class VideosController extends AppController {
protected function publish( $id ){
$html_file = $this->generate( (int)$id );
//do whatever needs to be done with the HTML file
//for example, this is where I upload the file to S3
}
private function generate( $id ){
//set whatever data is required to build the page;
//be sure this is done before instantiating the View class so all
//set variables are passed when you pass this controller object in the constructor
$video = $this->Video->read( null, $id );
$this->set('video', $video);
//instantiate a new View class from the controller
$view = new View($this);
//call the View object's render method which will return the HTML.
//Note, I'm setting the layout to HTML and telling the view to render the html.ctp file in /app/views/videos/ directory
$viewdata = $view->render(null,'html','html');
//set the file name to save the View's output
$path = WWW_ROOT . 'files/html/' . $id . '.html';
$file = new File($path, true);
//write the content to the file
$file->write( $viewdata );
//return the path
return $path;
}
}
Let me know if you run into any problems. But so far, seems to be working well.
PHP CMS Frameworks
October 28, 2013
Read more →
CakePHP
Setting Error page layout based on Auth status with CakePHP
In this tutorial, we are going to discuss about How to setting the separate layout for the error pages based on the Auth Status with CakePHP. By default, CakePHP error pages load within the default layout. This is enough for most of the applications. But in some applications we need a separate layout for logged in users. So here I'm going to explain about how to set the separate layout for the error pages based on the Auth status with CakePHP.
For example, the navigation changes when a user logged in. Basically including the proper elements based in the user's login status. But for the some projects, the entire layout needs to be changed based on the user status. Therefore I needed to find a way to be sure the proper layout was loaded when 404 errors appeared.
To achieve this, we need to create an app_error.php file in our /app directory. Our AppError class should extend the ErrorHandler class. Now extend the error404 method. You'll have a reference to the controller via $this->controller so that you can access the Auth component. So just see if we have a valid logged in user, and if not, set the layout to 'guest', or whatever your layout happens to be named.
Be sure to call the parent method, passing in the $params variable to be sure the error is handled properly by the ErrorHandler's error404 method.
<?php
class AppError extends ErrorHandler {
function error404($params) {
if( !$this->controller->Auth->User() ){
$this->controller->layout = "guest";
}
parent::error404($params);
}
}
For example, the navigation changes when a user logged in. Basically including the proper elements based in the user's login status. But for the some projects, the entire layout needs to be changed based on the user status. Therefore I needed to find a way to be sure the proper layout was loaded when 404 errors appeared.
To achieve this, we need to create an app_error.php file in our /app directory. Our AppError class should extend the ErrorHandler class. Now extend the error404 method. You'll have a reference to the controller via $this->controller so that you can access the Auth component. So just see if we have a valid logged in user, and if not, set the layout to 'guest', or whatever your layout happens to be named.
Be sure to call the parent method, passing in the $params variable to be sure the error is handled properly by the ErrorHandler's error404 method.
<?php
class AppError extends ErrorHandler {
function error404($params) {
if( !$this->controller->Auth->User() ){
$this->controller->layout = "guest";
}
parent::error404($params);
}
}
PHP CMS Frameworks
October 21, 2013
Read more →
CakePHP
Pagination Caching in CakePHP - Step by step tutorial
In this article, we are going to discuss about How to achieve pagination cachin in CakePHP. Pagination is nothing but, it is a mechanism which provides users with additional navigation options for browsing through single parts of the given article. Parts of the article are usually referred to by numbers, hints, arrows as well as "previous" and "next"-buttons. In this, we are going to discuss about How to achieve this in CakePHP.
In most cases pagination is better than traditional "previous – next" navigation as it offers visitors a more quick and convenient navigation through the site. It's not a must, but a useful nice-to-have-feature.
If we have large number of datas it will producing unneccessary high load on the database. To reduce the load in database, we can use "Caching". Unlike normal returned data from the database paginated data can not be cached as easily, as the paginate method needs to be called to generate the pagination numbers etc. So we need to do a custom pagination query with cache built in.
To implement pagination caching in CakePHP, add the below code in your app_model.php file.
function paginate ($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array())
{
$args = func_get_args();
$uniqueCacheId = '';
foreach ($args as $arg) {
$uniqueCacheId .= serialize($arg);
}
if (!empty($extra['contain'])) {
$contain = $extra['contain'];
}
$uniqueCacheId = md5($uniqueCacheId);
$pagination = Cache::read('pagination-'.$this->alias.'-'.$uniqueCacheId, 'paginate_cache');
if (empty($pagination)) {
$pagination = $this->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive', 'group', 'contain'));
Cache::write('pagination-'.$this->alias.'-'.$uniqueCacheId, $pagination, 'paginate_cache');
}
return $pagination;
}
function paginateCount ($conditions = null, $recursive = 0, $extra = array()) {
$args = func_get_args();
$uniqueCacheId = '';
foreach ($args as $arg) {
$uniqueCacheId .= serialize($arg);
}
$uniqueCacheId = md5($uniqueCacheId);
if (!empty($extra['contain'])) {
$contain = $extra['contain'];
}
$paginationcount = Cache::read('paginationcount-'.$this->alias.'-'.$uniqueCacheId, 'paginate_cache');
if (empty($paginationcount)) {
$paginationcount = $this->find('count', compact('conditions', 'contain', 'recursive'));
Cache::write('paginationcount-'.$this->alias.'-'.$uniqueCacheId, $paginationcount, 'paginate_cache');
}
return $paginationcount;
}
This will then take over from any paginate calls and generate a cached version of the dataset for the paginated items and the pagination controls, unique to each page and query set.
You need to specify the caching rule in core.php, something like:
Cache::config('paginate_cache', array(
'engine' => 'File',
'path' => CACHE .'sql'. DS,
'serialize' => true,
'duration' => '+1 hour',
));
In most cases pagination is better than traditional "previous – next" navigation as it offers visitors a more quick and convenient navigation through the site. It's not a must, but a useful nice-to-have-feature.
If we have large number of datas it will producing unneccessary high load on the database. To reduce the load in database, we can use "Caching". Unlike normal returned data from the database paginated data can not be cached as easily, as the paginate method needs to be called to generate the pagination numbers etc. So we need to do a custom pagination query with cache built in.
To implement pagination caching in CakePHP, add the below code in your app_model.php file.
function paginate ($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array())
{
$args = func_get_args();
$uniqueCacheId = '';
foreach ($args as $arg) {
$uniqueCacheId .= serialize($arg);
}
if (!empty($extra['contain'])) {
$contain = $extra['contain'];
}
$uniqueCacheId = md5($uniqueCacheId);
$pagination = Cache::read('pagination-'.$this->alias.'-'.$uniqueCacheId, 'paginate_cache');
if (empty($pagination)) {
$pagination = $this->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive', 'group', 'contain'));
Cache::write('pagination-'.$this->alias.'-'.$uniqueCacheId, $pagination, 'paginate_cache');
}
return $pagination;
}
function paginateCount ($conditions = null, $recursive = 0, $extra = array()) {
$args = func_get_args();
$uniqueCacheId = '';
foreach ($args as $arg) {
$uniqueCacheId .= serialize($arg);
}
$uniqueCacheId = md5($uniqueCacheId);
if (!empty($extra['contain'])) {
$contain = $extra['contain'];
}
$paginationcount = Cache::read('paginationcount-'.$this->alias.'-'.$uniqueCacheId, 'paginate_cache');
if (empty($paginationcount)) {
$paginationcount = $this->find('count', compact('conditions', 'contain', 'recursive'));
Cache::write('paginationcount-'.$this->alias.'-'.$uniqueCacheId, $paginationcount, 'paginate_cache');
}
return $paginationcount;
}
This will then take over from any paginate calls and generate a cached version of the dataset for the paginated items and the pagination controls, unique to each page and query set.
You need to specify the caching rule in core.php, something like:
Cache::config('paginate_cache', array(
'engine' => 'File',
'path' => CACHE .'sql'. DS,
'serialize' => true,
'duration' => '+1 hour',
));
PHP CMS Frameworks
October 13, 2013
Read more →
CakePHP
Steps to Install CakePHP on Shared Hosting
In this article, we are going to discuss about How to install CakePHP on Shared Hosting. I have installed cakaPHP on my hosted web but I Couldn't get it to work quite right. After a few hours playing around with cakePHP, finally I got the correct installation.
My hosting service allows me to publish multiple websites/domains on the one account. They have FTP access to upload the websites and each website/domain appears as a separate directory off the root directory.
/
/site1.com
site1_files.htm
/site2.com
site2_files.htm
/site3.com
site3_files.htm
My original installation was to simply unzip the CakePHP files to my new site. The result was something like:
/
/site1.com
site1_files.htm
/site2.com
site2_files.htm
/site3.com
site3_files.htm
/site4.com
/cake
/config
/console
/libs
/tests
basics.php
bootstrap.php
dispatcher.php
/app
/config
/controllers
/models
/tests
/tmp
/vendors
/webroot
/css
/files
/img
/js
.htaccess
index.php
.htaccess
index.php
.htaccess
index.php
I have not listed all files and directories here. My webhost doesn't allow the DocumentRoot to be changed in the .htaccess file nor via the CPanel. I moved the 'app', 'cake' and 'vendors' directories and contents into the root directory. I deleted the .htaccess and index.php files from the site4.com directory (i.e the first level).
I moved the contents of the 'webroot' directory into the site4.com directory and then deleted the empty webroot directory. I also changed the name of my 'app' directory to 'site4app', this allows me to run multiple cake apps from the one server, one cake app for each domain.
This is the resulting structure:
/
/cake
/config
/console
/libs
/tests
basics.php
bootstrap.php
dispatcher.php
/site4app
/config
/controllers
/models
/tests
/tmp
/vendors
.htaccess
index.php
/site1.com
site1_files.htm
/site2.com
site2_files.htm
/site3.com
site3_files.htm
/site4.com
/css
/files
/img
/js
.htaccess
index.php
/vendors
/css
/js
I then had to edit the index.php file in the site4.com directory (the old app/webroot directory) to point to the 'cake' and 'app' (now called site4app) directories. The CPanel of my account listed the actual directory of my site4.com domain as /hsphere/local/home/my_account_name/site4.com. Therefore I had to change;
ROOT to look at /hsphere/local/home/my_account_name
APP_DIR to look at /hsphere/local/home/my_account_name/site4app
CAKE_CORE_INCLUDE_PATH to look at /hsphere/local/home/my_account_name/cake
ROOT = /hsphere/local/home/my_account_name, APP_DIR = site4app, and
CAKE_CORE_INCLUDE_PATH = /hsphere/local/home/my_account_name.
The web document root has already been set in the CPanel settings from my web host as /hsphere/local/home/my_account_name/site4.com and therefore doesn't need to be set anywhere in cakephp.
The section below is what the relevant section in my index.php file looks like.
/**
* The full path to the directory which holds "app", WITHOUT a trailing DS.
*
*/
if (!defined('ROOT')) {
define('ROOT', DS.'hsphere'.DS.'local'.DS.'home'.DS.'my_account_name');
}
/**
* The actual directory name for the "app".
*
*/
if (!defined('APP_DIR')) {
define('APP_DIR', 'site4app');
}
/**
* The absolute path to the "cake" directory, WITHOUT a trailing DS.
*
*/
if (!defined('CAKE_CORE_INCLUDE_PATH')) {
define('CAKE_CORE_INCLUDE_PATH', DS.'hsphere'.DS.'local'.DS.'home'.DS.'my_account_name');
}
/**
I used the standarf .htaccess file in the site4.com directory (the old webroot) so it would load the correct page when someone went to www.site4.com. Anyway, mine looks like this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?url=$1 [QSA,L]
</IfModule>
I went to www.site4.com and it was all working. Nice! There was only one problem, I was getting the session ID appended to the URL. The advice of setting the "php_flag session.trans_id off" only caused a web server error.
To fix the problem I changed a setting in the core.php file in the site4app/config (old app/config) directory. Change the session.save value from 'php' to 'cake'. It's about line 104 in my file.
Configure::write('Session.save', 'cake');
Now when I loaded the page at www.site4.com it displayed some errors. This turned out to be due to a missing directory. I went to site4app/tmp (old app/tmp) directory and created a directory called 'sessions'. Loaded the page again. Now No errors.
I hope this method also works for you. Good luck. Have a great day.
My hosting service allows me to publish multiple websites/domains on the one account. They have FTP access to upload the websites and each website/domain appears as a separate directory off the root directory.
/
/site1.com
site1_files.htm
/site2.com
site2_files.htm
/site3.com
site3_files.htm
My original installation was to simply unzip the CakePHP files to my new site. The result was something like:
/
/site1.com
site1_files.htm
/site2.com
site2_files.htm
/site3.com
site3_files.htm
/site4.com
/cake
/config
/console
/libs
/tests
basics.php
bootstrap.php
dispatcher.php
/app
/config
/controllers
/models
/tests
/tmp
/vendors
/webroot
/css
/files
/img
/js
.htaccess
index.php
.htaccess
index.php
.htaccess
index.php
I have not listed all files and directories here. My webhost doesn't allow the DocumentRoot to be changed in the .htaccess file nor via the CPanel. I moved the 'app', 'cake' and 'vendors' directories and contents into the root directory. I deleted the .htaccess and index.php files from the site4.com directory (i.e the first level).
I moved the contents of the 'webroot' directory into the site4.com directory and then deleted the empty webroot directory. I also changed the name of my 'app' directory to 'site4app', this allows me to run multiple cake apps from the one server, one cake app for each domain.
This is the resulting structure:
/
/cake
/config
/console
/libs
/tests
basics.php
bootstrap.php
dispatcher.php
/site4app
/config
/controllers
/models
/tests
/tmp
/vendors
.htaccess
index.php
/site1.com
site1_files.htm
/site2.com
site2_files.htm
/site3.com
site3_files.htm
/site4.com
/css
/files
/img
/js
.htaccess
index.php
/vendors
/css
/js
I then had to edit the index.php file in the site4.com directory (the old app/webroot directory) to point to the 'cake' and 'app' (now called site4app) directories. The CPanel of my account listed the actual directory of my site4.com domain as /hsphere/local/home/my_account_name/site4.com. Therefore I had to change;
ROOT to look at /hsphere/local/home/my_account_name
APP_DIR to look at /hsphere/local/home/my_account_name/site4app
CAKE_CORE_INCLUDE_PATH to look at /hsphere/local/home/my_account_name/cake
ROOT = /hsphere/local/home/my_account_name, APP_DIR = site4app, and
CAKE_CORE_INCLUDE_PATH = /hsphere/local/home/my_account_name.
The web document root has already been set in the CPanel settings from my web host as /hsphere/local/home/my_account_name/site4.com and therefore doesn't need to be set anywhere in cakephp.
The section below is what the relevant section in my index.php file looks like.
/**
* The full path to the directory which holds "app", WITHOUT a trailing DS.
*
*/
if (!defined('ROOT')) {
define('ROOT', DS.'hsphere'.DS.'local'.DS.'home'.DS.'my_account_name');
}
/**
* The actual directory name for the "app".
*
*/
if (!defined('APP_DIR')) {
define('APP_DIR', 'site4app');
}
/**
* The absolute path to the "cake" directory, WITHOUT a trailing DS.
*
*/
if (!defined('CAKE_CORE_INCLUDE_PATH')) {
define('CAKE_CORE_INCLUDE_PATH', DS.'hsphere'.DS.'local'.DS.'home'.DS.'my_account_name');
}
/**
I used the standarf .htaccess file in the site4.com directory (the old webroot) so it would load the correct page when someone went to www.site4.com. Anyway, mine looks like this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?url=$1 [QSA,L]
</IfModule>
I went to www.site4.com and it was all working. Nice! There was only one problem, I was getting the session ID appended to the URL. The advice of setting the "php_flag session.trans_id off" only caused a web server error.
To fix the problem I changed a setting in the core.php file in the site4app/config (old app/config) directory. Change the session.save value from 'php' to 'cake'. It's about line 104 in my file.
Configure::write('Session.save', 'cake');
Now when I loaded the page at www.site4.com it displayed some errors. This turned out to be due to a missing directory. I went to site4app/tmp (old app/tmp) directory and created a directory called 'sessions'. Loaded the page again. Now No errors.
I hope this method also works for you. Good luck. Have a great day.
PHP CMS Frameworks
October 07, 2013
Read more →
No more posts to load.
About this blog
PHPCMSFramework.com
Tutorials for WordPress, Laravel, Drupal, Joomla, Symfony & more — including AI-powered PHP guides. Publishing since 2012.
Trending posts
- Building a RAG System in Laravel from Scratch
- Steps to create a Contact Form in Symfony With SwiftMailer
- Build an AI Code Review Bot with Laravel — Real-World Use Case
- Build a WhatsApp AI Assistant Using Laravel, Twilio and OpenAI
- CIBB - Basic Forum With Codeigniter and Twitter Bootstrap
- Drupal 7 - Create your custom Hello World module
- Laravel and Prism PHP: The Modern Way to Work with AI Models
- Create Front End Component in Joomla - Step by step procedure
- A step by step procedure to develop wordpress plugin
- Symfony Framework - Introduction
Blog Archive
-
▼
2013
(25)
-
▼
December
(9)
- Fetch products with specific attribute value in Ma...
- Steps to solve Magic Quotes Error in Drupal 8 Inst...
- Steps to override/rewrite model class in Magento
- Steps to install Magento on server using SSH
- Steps to create Joomla Components with Component C...
- Integrating Facebook Connect with CakePHP Auth Com...
- Steps to remove index.php from Codeigniter URL
- Tips to secure your wordpress site using .htaccess
- Steps to change the Default Admin Username in Word...
-
▼
December
(9)