Joomla
AllVideos - Joomla Video and Multimedia Extension free download
AllVideos (by JoomlaWorks) is truely THE all-in-one media management solution for Joomla!. You can use the plugin to easily embed videos hosted on popular services like YouTube, Metacafe, Vimeo (and many more) inside your Joomla! articles (content items).
Additionally, it allows you to playback almost any video/audio filetype directly from your server or a remote server, giving you the competitive edge when it comes to rich media content.
Extension Name: AllVideos
Extension Provider: JoomlaWorks
Price: Free
More info and reviews: AllVideos on JED
To download this extension Click Here
Additionally, it allows you to playback almost any video/audio filetype directly from your server or a remote server, giving you the competitive edge when it comes to rich media content.
Extension Name: AllVideos
Extension Provider: JoomlaWorks
Price: Free
More info and reviews: AllVideos on JED
To download this extension Click Here
PHP CMS Frameworks
December 28, 2014
Read more →
CodeIgniter
Codeigniter - Run Multiple Sites from single install
In this article, we are going to discuss about How to run multiple websites from a single CodeIgniter (CI) install. CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. If you're a developer who lives in the real world of shared hosting accounts and clients with deadlines, and if you're tired of ponderously large and thoroughly undocumented frameworks
Each CodeIgniter website have a different "application" folder. But all are using the same "System" folder.
Take the application folder out from the system folder and make an additional copies based on the number of sites your need to create. For example, if you want to create 3 sites then, create the application folder names like "application_site1, application_site2, application_site3".
Now copy the index.php file to the root of each website folder, and edit it as follows:
At line 26, put the full path to the system folder:
$system_folder = dirname(__FILE__) . '../codeigniter/system';
At line 43, put the full path to the application folder:
$application_folder = dirname(__FILE__) . '../application_site1';
Now you can have independent websites using separate application folders, but sharing the same system folder.
There is a similar implementation in the CodeIgniter User Guide you can read also.
Each CodeIgniter website have a different "application" folder. But all are using the same "System" folder.
Take the application folder out from the system folder and make an additional copies based on the number of sites your need to create. For example, if you want to create 3 sites then, create the application folder names like "application_site1, application_site2, application_site3".
Now copy the index.php file to the root of each website folder, and edit it as follows:
At line 26, put the full path to the system folder:
$system_folder = dirname(__FILE__) . '../codeigniter/system';
At line 43, put the full path to the application folder:
$application_folder = dirname(__FILE__) . '../application_site1';
Now you can have independent websites using separate application folders, but sharing the same system folder.
There is a similar implementation in the CodeIgniter User Guide you can read also.
PHP CMS Frameworks
December 24, 2014
Read more →
Magento
Steps to Add Icon for New Products in Magento
In this article, we are going to discuss about How to add Icon for new products in Magento. As your inventory rises it's always very necessary to make your products stand out using an unique icon. Visitors to your website will be able to notice which products are newly arrived as the icon will show up in wherever you set it to in your theme.
Step 1: Manage attributes
Go to Catalogue -> Attributes -> Manage Attributes. Set up a new attribute at this page and call it 'Boolean'. Set its ID as new_product. Under your advanced options, you will have the option to select it as a front end product. Do this. Now you simply have to add the new attribute to your custom attribute if you are using one. If not, set it to default. Save the new product.
You will now have a new product in your catalogue which has a Boolean flag set to yes. The next stage involves taking this new product icon and putting it in your front end.
Step 2: Make it show
Now that you have a product icon with a Boolean flag, it's time to make this show on your front end. This is achieved by accessing template files: templates/catalog/product/list.phtml and templates/catalog/product/view/media.phtml.
<div class="product-image">
<?php if($_product->getNewProduct()) { ?>
<div class="new-product"></div>
<?php } ?>
<?php
$_img = '<img id="image" src="'.$this->helper('catalog/image')
->init($_product, 'image').'"
alt="'.$this->htmlEscape($this->getImageLabel()).'"
title="'.$this->htmlEscape($this->getImageLabel()).'" />';
echo $_helper->productAttribute($_product, $_img, 'image');
?>
</div>
As you can see, above, your new product is shows in '$_product->getNewProduct'. The next step is to ensure that your CSS is set up to show your product with Boolean flag. You need to make the product_class relative to the position of the icon. So:
.products-grid .product-image { position: relative; display:block; width:244px; height:156px; margin:0 0 10px; }
.new-product {position: absolute;right: 0;top: 0;width: 65px;height: 66px;display: block;z-index: 2;background: url(../images/new-product.png) no-repeat;}
Step 3: Save
Save your changes and ensure that your code is correct before doing so. Now, every time you add a new product and it goes on sale through your front end, it'll have an icon and Boolean flag.
Step 1: Manage attributes
Go to Catalogue -> Attributes -> Manage Attributes. Set up a new attribute at this page and call it 'Boolean'. Set its ID as new_product. Under your advanced options, you will have the option to select it as a front end product. Do this. Now you simply have to add the new attribute to your custom attribute if you are using one. If not, set it to default. Save the new product.
You will now have a new product in your catalogue which has a Boolean flag set to yes. The next stage involves taking this new product icon and putting it in your front end.
Step 2: Make it show
Now that you have a product icon with a Boolean flag, it's time to make this show on your front end. This is achieved by accessing template files: templates/catalog/product/list.phtml and templates/catalog/product/view/media.phtml.
<div class="product-image">
<?php if($_product->getNewProduct()) { ?>
<div class="new-product"></div>
<?php } ?>
<?php
$_img = '<img id="image" src="'.$this->helper('catalog/image')
->init($_product, 'image').'"
alt="'.$this->htmlEscape($this->getImageLabel()).'"
title="'.$this->htmlEscape($this->getImageLabel()).'" />';
echo $_helper->productAttribute($_product, $_img, 'image');
?>
</div>
As you can see, above, your new product is shows in '$_product->getNewProduct'. The next step is to ensure that your CSS is set up to show your product with Boolean flag. You need to make the product_class relative to the position of the icon. So:
.products-grid .product-image { position: relative; display:block; width:244px; height:156px; margin:0 0 10px; }
.new-product {position: absolute;right: 0;top: 0;width: 65px;height: 66px;display: block;z-index: 2;background: url(../images/new-product.png) no-repeat;}
Step 3: Save
Save your changes and ensure that your code is correct before doing so. Now, every time you add a new product and it goes on sale through your front end, it'll have an icon and Boolean flag.
PHP CMS Frameworks
December 22, 2014
Read more →
CakePHP
Steps to install DebugKit in CakePHP on Ubuntu 14.04
In this article, we are going to discuss about How to install DebugKit in CakePHP on ubuntu 14.04. CakePHP is an open source web application framework. It follows the Model-View-Controller (MVC) approach and is written in PHP, modeled after the concepts of Ruby on Rails, and distributed under the MIT License.
CakePHP uses well-known software engineering concepts and software design patterns, as Convention over configuration, Model-View-Controller, Active Record, Association Data Mapping, and Front Controller.
Requirements to install DebugKit:
Follow the below steps to install DebugKit in CakePHP on Ubuntu.
Step 1:
Open terminal and first of all install git if not installed already.
$ sudo apt-get install git
Step 2:
Go to app/Plugin folder where DebugKit will be installed.
$ cd /var/www/html/cake/app/Plugin
Now initialize git repository here so that we can clone the DebugKit through GitHub using git.
$ sudo git init
Step 3:
To clone DebugKit type this command:
$ sudo git submodule add https://github.com/cakephp/debug_kit.git
or use this command:
$ sudo git clone https://github.com/cakephp/debug_kit.git
When this process is done then a folder will be created named as debug_kit in Plugin folder. Rename this folder as DebugKit. Type following command to do this:
$ sudo mv debug_kit/ DebugKit
[Note: Make sure you are in the Plugin folder.]
Step 4:
Go to app/Config folder
$ cd /var/www/html/cake/app/Config
$ sudo nano bootstrap.php
Add this line in the file CakePlugin::load('DebugKit'); if not already present.
Press ctrl+x, press y and enter to save file. Refresh localhost/cake page. Now DebugKit is detected.
Step 5:
After this check whether this line is present in core.php file or not Configure::write('debug',2); If it's not present then add this line and save file. Core.php file is present in app/Config. To edit this file type this:
$ sudo nano core.php
Step 6:
Now add DebugKit toolbar. Go to app/Controller folder.
$ cd app/Controller
$ sudo nano AppController.php
Add the red text color line in the empty class AppController which is present at the end of the file.
class AppController extends Controller {
public $components = array('DebugKit.Toolbar');
}
Press ctrl+x, press y and enter to save file. Refresh localhost/cake page. DebugKit toolbar is added at the top right end of the page.
Step 7:
After this go to app/View/Layouts folder to remove sql_dump.
$ cd app/View/Layouts
$ sudo nano default.ctp
Comment the following line present at the end of file embedded in php tags i.e. in between these tags <?php ?>
<?php //echo $this->element('sql_dump'); ?>
Press ctrl+x, press y and enter to save file. Refresh localhost/cake page.
Installation is DONE!!! Hope you get the points and this post is helpful for you. If you have any query then comment on the post. i'll get back to you as soon as possible. All The Best.
CakePHP uses well-known software engineering concepts and software design patterns, as Convention over configuration, Model-View-Controller, Active Record, Association Data Mapping, and Front Controller.
Requirements to install DebugKit:
- CakePHP 2.2.0 or greater.
- PHP 5.3.0 or greater.
Follow the below steps to install DebugKit in CakePHP on Ubuntu.
Step 1:
Open terminal and first of all install git if not installed already.
$ sudo apt-get install git
Step 2:
Go to app/Plugin folder where DebugKit will be installed.
$ cd /var/www/html/cake/app/Plugin
Now initialize git repository here so that we can clone the DebugKit through GitHub using git.
$ sudo git init
Step 3:
To clone DebugKit type this command:
$ sudo git submodule add https://github.com/cakephp/debug_kit.git
or use this command:
$ sudo git clone https://github.com/cakephp/debug_kit.git
When this process is done then a folder will be created named as debug_kit in Plugin folder. Rename this folder as DebugKit. Type following command to do this:
$ sudo mv debug_kit/ DebugKit
[Note: Make sure you are in the Plugin folder.]
Step 4:
Go to app/Config folder
$ cd /var/www/html/cake/app/Config
$ sudo nano bootstrap.php
Add this line in the file CakePlugin::load('DebugKit'); if not already present.
Press ctrl+x, press y and enter to save file. Refresh localhost/cake page. Now DebugKit is detected.
Step 5:
After this check whether this line is present in core.php file or not Configure::write('debug',2); If it's not present then add this line and save file. Core.php file is present in app/Config. To edit this file type this:
$ sudo nano core.php
Step 6:
Now add DebugKit toolbar. Go to app/Controller folder.
$ cd app/Controller
$ sudo nano AppController.php
Add the red text color line in the empty class AppController which is present at the end of the file.
class AppController extends Controller {
public $components = array('DebugKit.Toolbar');
}
Press ctrl+x, press y and enter to save file. Refresh localhost/cake page. DebugKit toolbar is added at the top right end of the page.
Step 7:
After this go to app/View/Layouts folder to remove sql_dump.
$ cd app/View/Layouts
$ sudo nano default.ctp
Comment the following line present at the end of file embedded in php tags i.e. in between these tags <?php ?>
<?php //echo $this->element('sql_dump'); ?>
Press ctrl+x, press y and enter to save file. Refresh localhost/cake page.
Installation is DONE!!! Hope you get the points and this post is helpful for you. If you have any query then comment on the post. i'll get back to you as soon as possible. All The Best.
PHP CMS Frameworks
December 17, 2014
Read more →
Drupal
Steps to Add HTTP authentication to your Drupal site
In this article, we are going o discuss about how to add HTTp authentication to the Drupal website. HTTP authentication is quite useful to be added on your live site when you need only the authenticated people to have the access.
Step 1 :
Create the file that will keep the information of the usernames / passwords for authentication. (You can create more than one accounts). You can create this file in the project root folder. Like, the location /var/www/drupal_site/. Use the following command.
htpasswd [ -c ] passwdfilename username
So, here you have given the username that would be authenticated for the site. You will be asked twice to enter password for this username.
For example, in the following command, my file's name is ".dummyhtpasswd" and the username of the account is "user1".
htpasswd –c /var/www/drupal_site/.dummyhtpasswd user1
Step 2:
You are done with creation of account details, now you need to edit your .htaccess file to add the code for http authentication there and also to add the path of this newly created file that contains the credentials' information so that this newly created file's presence and the credentials are verified at every http access. For that you have to reach out to your .htaccess file. In my case, I found it in my project folder at /var/www/drupal_site/ . You can also find it in the folder of your project.
Step 3:
Now, edit the .htaccess file. By using the below command.
vi .htaccess
Now to go to edit mode, press "i", that's for "insert". Take the cursor to the very bottom of the code and then add the following lines.
# /var/www/drupal_site/.dummyhtpasswd
# AUTHENTICATION
## BASIC PASSWORD AUTHENTICATION
AuthName "Prompt"
AuthUserFile /var/www/drupal_site/.dummyhtpasswd
AuthType basic
Require valid-user
That is it. Now we have to save it. Press "Esc" and then :w <enter>. This saves it.
For saving and exiting press "Esc" and then press :wq! <enter>.
Now we have added the path of the newly created file. Please see that line 1 and 5 of the code would have the path of "your" created file, in above code I have given the path of "my" created file for reference.
Step 4:
You have to reach out to the newly created file. (You created in Step 1). After that the following command can be used to add a user to the already existing file.
htpasswd /var/www/ drupal_site/.dummyhtpasswd newuser <enter>
Enter the password twice and you are done. The path in above command will be the path for that newly created password file (of Step 1).
Done!!
Step 1 :
Create the file that will keep the information of the usernames / passwords for authentication. (You can create more than one accounts). You can create this file in the project root folder. Like, the location /var/www/drupal_site/. Use the following command.
htpasswd [ -c ] passwdfilename username
So, here you have given the username that would be authenticated for the site. You will be asked twice to enter password for this username.
For example, in the following command, my file's name is ".dummyhtpasswd" and the username of the account is "user1".
htpasswd –c /var/www/drupal_site/.dummyhtpasswd user1
Step 2:
You are done with creation of account details, now you need to edit your .htaccess file to add the code for http authentication there and also to add the path of this newly created file that contains the credentials' information so that this newly created file's presence and the credentials are verified at every http access. For that you have to reach out to your .htaccess file. In my case, I found it in my project folder at /var/www/drupal_site/ . You can also find it in the folder of your project.
Step 3:
Now, edit the .htaccess file. By using the below command.
vi .htaccess
Now to go to edit mode, press "i", that's for "insert". Take the cursor to the very bottom of the code and then add the following lines.
# /var/www/drupal_site/.dummyhtpasswd
# AUTHENTICATION
## BASIC PASSWORD AUTHENTICATION
AuthName "Prompt"
AuthUserFile /var/www/drupal_site/.dummyhtpasswd
AuthType basic
Require valid-user
That is it. Now we have to save it. Press "Esc" and then :w <enter>. This saves it.
For saving and exiting press "Esc" and then press :wq! <enter>.
Now we have added the path of the newly created file. Please see that line 1 and 5 of the code would have the path of "your" created file, in above code I have given the path of "my" created file for reference.
Step 4:
You have to reach out to the newly created file. (You created in Step 1). After that the following command can be used to add a user to the already existing file.
htpasswd /var/www/ drupal_site/.dummyhtpasswd newuser <enter>
Enter the password twice and you are done. The path in above command will be the path for that newly created password file (of Step 1).
Done!!
PHP CMS Frameworks
December 14, 2014
Read more →
Wordpress
Restrict Access to WordPress files using htaccess
In this article we are going to discuss about How to restrict access to wordpress files using htaccess file. It will restrict a number of files on your website from being accessed from an external source.
Htacess to restrict access to a single WordPress file
In the .htaccess file example below, we are restricting access to the WordPress wp-config.php file.
<files wp-config.php>
order allow,deny
deny from all
</files>
The .htaccess file in the above example should be uploaded to the same directory where the file resides, in this case in the WordPress root directory. If you would like to restrict access to any other individual file on your website change the file name in the first line and upload the .htaccess file to the directory where the file resides. Keep in mind that if you already have an .htaccess file in that directory, simply add the above directives at the end of the .htaccess file.
Restrict file access to by file type with htaccess
To restrict access to a variety of files which share the same file extension, you can use the syntax of the .htaccess file below. Such .htaccess file should be uploaded to the root of your website to apply file restriction site wide. In the below example, we are restricting access to .htaccess files, .htpasswd files, log files and ini files.
<FilesMatch "\.(htaccess|htpasswd|log|ini)$">
Order Allow,Deny
Deny from all
</FilesMatch>
If you would like to restrict access to more file extensions than the ones specified above, add the extension to the first line between the brackets next to the ini extension.
Htacess to restrict access to a single WordPress file
In the .htaccess file example below, we are restricting access to the WordPress wp-config.php file.
<files wp-config.php>
order allow,deny
deny from all
</files>
The .htaccess file in the above example should be uploaded to the same directory where the file resides, in this case in the WordPress root directory. If you would like to restrict access to any other individual file on your website change the file name in the first line and upload the .htaccess file to the directory where the file resides. Keep in mind that if you already have an .htaccess file in that directory, simply add the above directives at the end of the .htaccess file.
Restrict file access to by file type with htaccess
To restrict access to a variety of files which share the same file extension, you can use the syntax of the .htaccess file below. Such .htaccess file should be uploaded to the root of your website to apply file restriction site wide. In the below example, we are restricting access to .htaccess files, .htpasswd files, log files and ini files.
<FilesMatch "\.(htaccess|htpasswd|log|ini)$">
Order Allow,Deny
Deny from all
</FilesMatch>
If you would like to restrict access to more file extensions than the ones specified above, add the extension to the first line between the brackets next to the ini extension.
PHP CMS Frameworks
December 10, 2014
Read more →
YII
YII Controller methods - render and renderPartial
In this article, we are going to discuss about the two controller methods in YII, render and renderPartial. Both the render and renderPartial methods are used to creating the controller's view content. Simply put this is the information the view will receive from the controller.
The difference between render and renderPartial is that the latter will not load the layout. This is useful in case you'd like to have a popup window or ajax functionality which shows short information.
Here is an example with a whole method:
public function actionView($slug) {
$model = $this->loadSlug($slug);
$category = $this->loadCategory($model->category);
$this->render('view', array( 'model' => $model, 'category' => $category->category ));
}
The first argument for render is view. This is the view file to which will be added .php. This should be the file protected/views/view_name/view.php.
The next interesting thing is the array which comes as second argument. This is how you set the properties or variables that will be sent to the view and will be available there. In our case we will have $model (array) and $category at our disposal in the view file.
Eventually you could create variables in the view and you don't have to necessarily pass them from the controller. However, this will not be in the spirit of MVC.
The difference between render and renderPartial is that the latter will not load the layout. This is useful in case you'd like to have a popup window or ajax functionality which shows short information.
Here is an example with a whole method:
public function actionView($slug) {
$model = $this->loadSlug($slug);
$category = $this->loadCategory($model->category);
$this->render('view', array( 'model' => $model, 'category' => $category->category ));
}
The first argument for render is view. This is the view file to which will be added .php. This should be the file protected/views/view_name/view.php.
The next interesting thing is the array which comes as second argument. This is how you set the properties or variables that will be sent to the view and will be available there. In our case we will have $model (array) and $category at our disposal in the view file.
Eventually you could create variables in the view and you don't have to necessarily pass them from the controller. However, this will not be in the spirit of MVC.
PHP CMS Frameworks
December 07, 2014
Read more →
Zend
Create Custom Toolbar for ZendDeveloperTools - Zend Framework 2

To make it easy to learn, let's apply it into new module, I created a new module for it named SanSessionToolbar like the following :
1. Start with the Collector :
namespace SanSessionToolbar\Collector;
use ZendDeveloperTools\Collector\CollectorInterface;
use Zend\Mvc\MvcEvent;
use Zend\Session\Container;
/**
* Session Data Collector.
*/
class SessionCollector implements CollectorInterface
{
/**
* @inheritdoc
*/
public function getName()
{
// this name must same with *collectors* name in the configuration
return 'session.toolbar';
}
/**
* {@inheritDoc}
*/
public function getPriority()
{
return 10;
}
/**
* @inheritdoc
*/
public function collect(MvcEvent $mvcEvent)
{
}
public function getSessionData()
{
$container = new Container;
$arraysession = $container->getManager()->getStorage()->toArray();
$data = array();
foreach($arraysession as $key => $row) {
if ($row instanceof \Zend\Stdlib\ArrayObject) {
$iterator = $row->getIterator();
while($iterator->valid()) {
$data[$iterator->key()] = $iterator->current() ;
$iterator->next();
}
}
}
return $data;
}
}
2. Now, create a view to var_dump the
SanSessionToolbar\Collector\SessionCollector::getSessionData().
<?php /* @var $collector \SanSessionToolbar\Collector\SessionCollector */ ?>
<div class="zdt-toolbar-entry">
<div class="zdt-toolbar-preview">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAATxJREFUeNpi/P//PwMhMJuRkRVItQNxKhBzAPFOIM5O/f//MbpaFgbiAMigYiS+LxCDXOKPrpCJSAP1sYiZY1NIrIGHsYhtw6aQWC8vA2IlIM4EYn6oYRXYFDISEylokQOKlG/ACPlLsguBBggAKRUglgbi70B8EWjQS3x6sLoQaFAikLIDYjcglkKSegHEGUBDN+IyEFekeAOxJRBfAeJPSOISQDwZaKEYSS5Ec20KiEITVgW68g65yeYHAwmAGAN90PgPgPgjWQZCw8oOTXgX0LuvyXWhBxBLIvFBaW8zJV52RePfA+LdZBkI9K44kHJAEz4G9O5Pcl3IA8QyaGJHKYllRixiylDXywCxFKkGvgPiG2hiJUCDQHn5PhBbkGQgMKxABsYC8UEg/grFH4D4BBDHA/EebPoAAgwA3RZUHjvT8+IAAAAASUVORK5CYII=" alt="SESSION Data">
<span class="zdt-toolbar-info">
SessionData
</span>
</div>
<div class="zdt-toolbar-detail">
<span class="zdt-toolbar-info zdt-toolbar-info-redundant">
<span class="zdt-detail-label">Session Data</span>
</span>
<span class="zdt-toolbar-info">
<span class="zdt-detail-pre">
<?php Zend\Debug\Debug::dump($collector->getSessionData()); ?>
</span>
</span>
</div>
</div>
3. Configure the module configuration ( config/module.config.php ), Remember, that the toolbar entries name must same with our SessionCollector::getName().
return array(
'service_manager' => array(
'invokables' => array(
'session.toolbar' =>
'SanSessionToolbar\Collector\SessionCollector',
),
),
'view_manager' => array(
'template_map' => array(
'zend-developer-tools/toolbar/session-data'
=> __DIR__ . '/../view/zend-developer-tools/toolbar/session-data.phtml',
),
),
'zenddevelopertools' => array(
'profiler' => array(
'collectors' => array(
'session.toolbar' => 'session.toolbar',
),
),
'toolbar' => array(
'entries' => array(
'session.toolbar' => 'zend-developer-tools/toolbar/session-data',
),
),
),
);
The 'session.toolbar' must be registered into ServiceManager with an instance of SanSessionToolbar\Collector\SessionCollector, and registered into 'zenddevelopertools' config profiler and toolbar.
4. The Module.php is a usual Module class.
5. Register your new module into config/application.config.php
6. Now, let's test it by creating session data in our controller :
public function indexAction()
{
$container = new \Zend\Session\Container;
$container->a = 'b';
$container->foo = 'bar';
return new ViewModel();
}
Source :
https://samsonasik.wordpress.com/2014/06/27/zend-framework-2-create-custom-toolbar-for-zenddevelopertools/
Reference :
- http://stackoverflow.com/questions/20325842/how-to-log-something-to-zend-developer-tools-toolbar
- Image session icon originally from : http://makemore.info.yorku.ca/files/2012/11/info.png, encoded with base64_encode.
PHP CMS Frameworks
December 03, 2014
Read more →
Magento
Steps to Install Magento On Ubuntu
In this article, we are going to discuss about How to install Magento on Ubuntu. Magento is a feature-rich, open-source, enterprise-class platform that offers merchants a high degree of flexibility and control over the user experience, catalog, content and functionality of their online store.
Here are the steps to install Magento on ubuntu with sample data.
Create a database :
Use the below command to create a database for magento on ubundu.
mysql -u root -p
mysqladmin -u root -p create magento_test;
mysqladmin -u root -p reload;
GRANT ALL ON magento_test.* TO magento_test@localhost IDENTIFIED BY 'magento_test_password'
Install Magento :
This is almost the same as above, except you don't need to know the directory name. You will only have to replace DBHOST, DBNAME, DBUSER, and DBPASS.
wget http://www.magentocommerce.com/downloads/assets/1.7.0.2/magento-1.7.0.2.tar.gz
tar -zxvf magento-1.7.0.2.tar.gz
wget http://www.magentocommerce.com/downloads/assets/1.6.1.0/magento-sample-data-1.6.1.0.tar.gz
tar -zxvf magento-sample-data-1.6.1.0.tar.gz
mv magento-sample-data-1.6.1.0/media/* magento/media/
mv magento-sample-data-1.6.1.0/magento_sample_data_for_1.6.1.0.sql magento/data.sql
cd magento
chmod -R o+w media var
mysql -h DBHOST -u DBUSER -pDBPASS DBNAME < data.sql
chmod o+w var var/.htaccess app/etc
cd ..
rm -rf magento-sample-data-1.6.1.0/ magento-1.7.0.2.tar.gz magento-sample-data-1.6.1.0.tar.gz magento/data.sql
Go to www.DOMAIN.NAME/magento/ and follow the online installation guide.
Errors may occur during fresh installation :
WARNING: your Magento folder does not have sufficient write information
following is 100% safe to run from the directory where Magento is installed:
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod o+w var var/.htaccess app/etc
chmod 550 mage
chmod -R o+w media
If that is not working, try setting all directories to 777 by doing this:
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 777 {} \;
chmod o+w var/.htaccess
chmod 550 mage
http://www.magentocommerce.com/wiki/groups/227/resetting_file_permissions
Here are the steps to install Magento on ubuntu with sample data.
Create a database :
Use the below command to create a database for magento on ubundu.
mysql -u root -p
mysqladmin -u root -p create magento_test;
mysqladmin -u root -p reload;
GRANT ALL ON magento_test.* TO magento_test@localhost IDENTIFIED BY 'magento_test_password'
Install Magento :
This is almost the same as above, except you don't need to know the directory name. You will only have to replace DBHOST, DBNAME, DBUSER, and DBPASS.
wget http://www.magentocommerce.com/downloads/assets/1.7.0.2/magento-1.7.0.2.tar.gz
tar -zxvf magento-1.7.0.2.tar.gz
wget http://www.magentocommerce.com/downloads/assets/1.6.1.0/magento-sample-data-1.6.1.0.tar.gz
tar -zxvf magento-sample-data-1.6.1.0.tar.gz
mv magento-sample-data-1.6.1.0/media/* magento/media/
mv magento-sample-data-1.6.1.0/magento_sample_data_for_1.6.1.0.sql magento/data.sql
cd magento
chmod -R o+w media var
mysql -h DBHOST -u DBUSER -pDBPASS DBNAME < data.sql
chmod o+w var var/.htaccess app/etc
cd ..
rm -rf magento-sample-data-1.6.1.0/ magento-1.7.0.2.tar.gz magento-sample-data-1.6.1.0.tar.gz magento/data.sql
Go to www.DOMAIN.NAME/magento/ and follow the online installation guide.
Errors may occur during fresh installation :
WARNING: your Magento folder does not have sufficient write information
following is 100% safe to run from the directory where Magento is installed:
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod o+w var var/.htaccess app/etc
chmod 550 mage
chmod -R o+w media
If that is not working, try setting all directories to 777 by doing this:
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 777 {} \;
chmod o+w var/.htaccess
chmod 550 mage
http://www.magentocommerce.com/wiki/groups/227/resetting_file_permissions
PHP CMS Frameworks
November 30, 2014
Read more →
CodeIgniter
Steps to Install CodeIgniter On LinuxMint and Ubuntu
In this article, we are going to discuss about How to install CodeIgniter (CI) on LinuxMint and Ubuntu. CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. If you're a developer who lives in the real world of shared hosting accounts and clients with deadlines, and if you're tired of ponderously large and thoroughly undocumented frameworks
Step 1:
Download the latest version of CodeIgniter (CI) by Clicking Here
Step 2:
Unzip the downloaded zip file by executing the below command
sudo unzip CodeIgniter_2.2.0.zip
Step 3:
Rename the unzipped folder by executing the below command.
mv CodeIgniter_2.2.0 codeigniter
Step 4:
Move the unzipped renamed folder the www directory.
sudo mv codeigniter /var/www
Step 5:
Run the below URL and check the site is working.
http://localhost/codeigniter
Step 1:
Download the latest version of CodeIgniter (CI) by Clicking Here
Step 2:
Unzip the downloaded zip file by executing the below command
sudo unzip CodeIgniter_2.2.0.zip
Step 3:
Rename the unzipped folder by executing the below command.
mv CodeIgniter_2.2.0 codeigniter
Step 4:
Move the unzipped renamed folder the www directory.
sudo mv codeigniter /var/www
Step 5:
Run the below URL and check the site is working.
http://localhost/codeigniter
PHP CMS Frameworks
November 23, 2014
Read more →
CakePHP
Steps to Install CakePHP on Ubuntu 14.04
In thia article, we are going to discuss about How to install CakePHP on Ubuntu 14.04. CakePHP uses well-known software engineering concepts and software design patterns, as Convention over configuration, Model-View-Controller, Active Record, Association Data Mapping, and Front Controller.
Steps are almost same but in Windows we did that using GUI or in Windows Explorer and in Ubuntu we'll do it through terminal or you can say using commands.
Step 1:
Open the command prompt (terminal) and type the following command
cd /var/www/html
Step 2:
Type the below command to download the cakephp.
$ sudo wget https://codeload.github.com/cakephp/cakephp/legacy.zip/2.5.2
where 2.5.2 is the latest stable version of CakePHP.
Step 3:
Use the following command to unzip the downloaded zip file.
$ sudo unzip 2.5.2
Step 4:
Rename extracted folder.
$ mv cakephp-cakephp-736e999/ cake
where cakephp-cakephp-736e999 is the name of extracted folder.
To run CakePHP on browser use this path localhost/cake.
Step 5:
Go to cake folder.
$ cd cake
And change permissions to app/tmp folder.
$ sudo chown -R root:www-data app/tmp
$ sudo chmod -R 775 app/tmp
Step 6:
To make script writable perform these steps:
$ apache2clt -M
If you see mod_rewrite in the list shown then script is writable. If not then to enable it type this command:
$ a2enmod rewrite
Step 7:
Type cd /etc/apache2
$ sudo nano apache2.conf
Set these lines in the file:
<Directory /var/www>
Option Indexes FollowSymlinks
AllowOverride All
Required all granted
</Directory>
Press ctrl+x, then press y and enter to save the file.
Restart apache:
$ sudo service apache2 restart
Step 8:
Now go to app/Config
$ cd /var/www/html/cake/app/Config
$ sudo mv database.php.default default.php
Refresh localhost/cake page. Now database file is detected but still we have to create a database as it will show could not connect to database.
Step 9:
Open localhost/phpmyadmin on browser. Login using your username and password and create a database named as cake. After this edit database.php file.
$ sudo nano database.php
Set host as localhost, username is your phpmyadmin username, password is your phpmyadmin password and database name.
Refresh localhost/cake page. Now database is detected.
Step 10:
To remove the salt and seed error shown on top of the localhost/cake page we have to edit core.php file.
$ sudo nano core.php
Find this section and replace both the strings with any random strings or you can use these strings also.
/* A random string used in security hashing methods. */
Configure::write('Security.salt', 'fvjhdj8fvn85grg73fbrvfn9fjFGfnhvt758nADG');
/* A random numeric string (digits only) used to encrypt/decrypt strings. */
Configure::write('Security.cipherSeed', '55857485748594575784348784787475');
Then press ctrl+x, press y and enter to save file.
Refresh localhost/cake page. And its done.
Steps are almost same but in Windows we did that using GUI or in Windows Explorer and in Ubuntu we'll do it through terminal or you can say using commands.
Step 1:
Open the command prompt (terminal) and type the following command
cd /var/www/html
Step 2:
Type the below command to download the cakephp.
$ sudo wget https://codeload.github.com/cakephp/cakephp/legacy.zip/2.5.2
where 2.5.2 is the latest stable version of CakePHP.
Step 3:
Use the following command to unzip the downloaded zip file.
$ sudo unzip 2.5.2
Step 4:
Rename extracted folder.
$ mv cakephp-cakephp-736e999/ cake
where cakephp-cakephp-736e999 is the name of extracted folder.
To run CakePHP on browser use this path localhost/cake.
Step 5:
Go to cake folder.
$ cd cake
And change permissions to app/tmp folder.
$ sudo chown -R root:www-data app/tmp
$ sudo chmod -R 775 app/tmp
Step 6:
To make script writable perform these steps:
$ apache2clt -M
If you see mod_rewrite in the list shown then script is writable. If not then to enable it type this command:
$ a2enmod rewrite
Step 7:
Type cd /etc/apache2
$ sudo nano apache2.conf
Set these lines in the file:
<Directory /var/www>
Option Indexes FollowSymlinks
AllowOverride All
Required all granted
</Directory>
Press ctrl+x, then press y and enter to save the file.
Restart apache:
$ sudo service apache2 restart
Step 8:
Now go to app/Config
$ cd /var/www/html/cake/app/Config
$ sudo mv database.php.default default.php
Refresh localhost/cake page. Now database file is detected but still we have to create a database as it will show could not connect to database.
Step 9:
Open localhost/phpmyadmin on browser. Login using your username and password and create a database named as cake. After this edit database.php file.
$ sudo nano database.php
Set host as localhost, username is your phpmyadmin username, password is your phpmyadmin password and database name.
Refresh localhost/cake page. Now database is detected.
Step 10:
To remove the salt and seed error shown on top of the localhost/cake page we have to edit core.php file.
$ sudo nano core.php
Find this section and replace both the strings with any random strings or you can use these strings also.
/* A random string used in security hashing methods. */
Configure::write('Security.salt', 'fvjhdj8fvn85grg73fbrvfn9fjFGfnhvt758nADG');
/* A random numeric string (digits only) used to encrypt/decrypt strings. */
Configure::write('Security.cipherSeed', '55857485748594575784348784787475');
Then press ctrl+x, press y and enter to save file.
Refresh localhost/cake page. And its done.
PHP CMS Frameworks
November 20, 2014
Read more →
Wordpress
Fix Too Many Redirects Loop Error in WordPress
In this article, we are going to discuss about How to fix the too many redirects loop error in WordPress. When you add additional http authentication to the WordPress admin dashboard or the wp-admin directory, there are chances that you get any of the following errorr when trying to access the WordPress wp-admin directory;
The page isn't redirecting properly, This web page has a redirect loop, Error 310 (net::ERR_TOO_MANY_REDIRECTS) or an HTTP 404 error.
This is not a WordPress problem or error, but is an issue related to the configuration of your web server or hosting provider. If you do encounter such error, you can solve the issue by adding 1 line to the WordPress root .htaccess file. Follow the below step by step procedure to solve such issue:
ErrorDocument 401 default
That does the trick. Now your WordPress administrator dashboard is protected with double authentication.
The page isn't redirecting properly, This web page has a redirect loop, Error 310 (net::ERR_TOO_MANY_REDIRECTS) or an HTTP 404 error.
This is not a WordPress problem or error, but is an issue related to the configuration of your web server or hosting provider. If you do encounter such error, you can solve the issue by adding 1 line to the WordPress root .htaccess file. Follow the below step by step procedure to solve such issue:
- Connect to your WordPress website using FTP.
- Download the .htaccess file from the root of your WordPress website.
- Add the below line before the WordPress rules (above the # BEGIN WordPress line)
ErrorDocument 401 default
That does the trick. Now your WordPress administrator dashboard is protected with double authentication.
PHP CMS Frameworks
November 16, 2014
Read more →
YII
Access Rules and Access Control in YII
In this article, we are going to discuss about How use Access Rules and Access Control in YII framework. Yii gives powerful options for limiting access per controller methods / actions. Imagine that in an example controller we have actions index, view, create, update, delete (typical CRUD).
Here is how our access rules should look provided our remote IP is 4.2.2.2 and we want only authorized user 'admin' to access the administrative actions:
public function accessRules() {
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions' => array('index', 'view'),
'users' => array('*'),
),
array('allow', // allow admin users the admin actions
'actions' => array('create', 'update', 'delete'),
'users' => array('admin'),
'ips'=>array('127.0.1.1','4.2.2.2'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
The above shows a good practice to limit the access by IP and not only to rely on authorization. This is very important for your website security.
Here is how our access rules should look provided our remote IP is 4.2.2.2 and we want only authorized user 'admin' to access the administrative actions:
public function accessRules() {
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions' => array('index', 'view'),
'users' => array('*'),
),
array('allow', // allow admin users the admin actions
'actions' => array('create', 'update', 'delete'),
'users' => array('admin'),
'ips'=>array('127.0.1.1','4.2.2.2'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
The above shows a good practice to limit the access by IP and not only to rely on authorization. This is very important for your website security.
PHP CMS Frameworks
November 13, 2014
Read more →
Drupal
Drupal 7 - Download Adaptive Theme free
Adaptivetheme is a powerful theme framework designed from the ground up to power modern, cross browser/cross device websites using responsive design techniques. Adaptivetheme allows you to set up specific layouts for different device groups - such as desktop, tablet and smartphone - all with zero coding. Its all easy point-and-click configuration.
If you are using Panels try the Browscap CTools module to control the visibility of panel panes in mobile devices or Browscap Block to do the same thing with normal blocks.
Panels, Display Suite and Gpanels are fully supported with many options for displaying panel type layouts in mobile.
Adaptivetheme is blindingly fast - it employs extensive use of drupal_static and other caching techniques to speed up page rendering and delivery. If you're not fast you're last, right?
Adaptivetheme is built around these basic concepts:
If you are using Panels try the Browscap CTools module to control the visibility of panel panes in mobile devices or Browscap Block to do the same thing with normal blocks.
Panels, Display Suite and Gpanels are fully supported with many options for displaying panel type layouts in mobile.
Adaptivetheme is blindingly fast - it employs extensive use of drupal_static and other caching techniques to speed up page rendering and delivery. If you're not fast you're last, right?
Adaptivetheme is built around these basic concepts:
- Responsive design
- Pluggable layout system
- HTML5
- WGAC 2.0 Accessibility
To download the theme Click Here
For Documentation Click Here
PHP CMS Frameworks
November 09, 2014
Read more →
Joomla
Create Secure Joomla Extensions
In this article, we are going to discuss about How to create secure extentions in Joomla. It's no secret that most compromised Joomla sites are exploited through third party extensions. While there are core Joomla exploits too they are much fewer than the endless risks imposed from third party extensions.
In order Joomla extensions to be secure the following important aspects have to be observed:
The first and foremost important statement in any Joomla extension php file is making sure that the file is not accessed directly:
defined('_JEXEC') or die( 'Restricted access' );
The next important statement is making sure the visitor has the necessary privileges to access it. This is especially important when the extension is in the administrator panel. The simplest way to check if the user is authorized to open a sensitive file is:
$user = & JFactory::getUser();
if (!$user->authorize( 'com_users', 'manage' )) {
$mainframe->redirect( 'index.php', JText::_('ALERTNOTAUTH') );
}
If the user is authorized to manage the users then he should be allowed to do anything.
The general rule is, to follow the best practices of Joomla native Model View Controller concept. This ensures that your code will be tidier, easier to maintain and secure.
The essential part in writing a secure Joomla extension is using native Joomla classes and avoiding using your own code for the basic operations such as executing MySQL queries, including files and others. That's why make sure to be acquainted with all the Joomla Framework classes
http://docs.joomla.org/Framework
When studying the native Joomla classes pay special attention to JFilterInput and JFilterOutput. Their methods should be used regularly for filtering user input and output to avoid anything from MySQL injections to XSS flaws.
Finally, always take into consideration that Joomla runs on different environments and what is secure on yours might not be on others. Ensure that RG_emulation, register_globals or even allow_url_include will not allow anyone to tamper with your variables. If you cannot ensure it at least make sure to warn users about potential problems.
The above short secure Joomla extensions guidilines should give you an idea on how to write more secure Joomla extensions.
In order Joomla extensions to be secure the following important aspects have to be observed:
The first and foremost important statement in any Joomla extension php file is making sure that the file is not accessed directly:
defined('_JEXEC') or die( 'Restricted access' );
The next important statement is making sure the visitor has the necessary privileges to access it. This is especially important when the extension is in the administrator panel. The simplest way to check if the user is authorized to open a sensitive file is:
$user = & JFactory::getUser();
if (!$user->authorize( 'com_users', 'manage' )) {
$mainframe->redirect( 'index.php', JText::_('ALERTNOTAUTH') );
}
If the user is authorized to manage the users then he should be allowed to do anything.
The general rule is, to follow the best practices of Joomla native Model View Controller concept. This ensures that your code will be tidier, easier to maintain and secure.
The essential part in writing a secure Joomla extension is using native Joomla classes and avoiding using your own code for the basic operations such as executing MySQL queries, including files and others. That's why make sure to be acquainted with all the Joomla Framework classes
http://docs.joomla.org/Framework
When studying the native Joomla classes pay special attention to JFilterInput and JFilterOutput. Their methods should be used regularly for filtering user input and output to avoid anything from MySQL injections to XSS flaws.
Finally, always take into consideration that Joomla runs on different environments and what is secure on yours might not be on others. Ensure that RG_emulation, register_globals or even allow_url_include will not allow anyone to tamper with your variables. If you cannot ensure it at least make sure to warn users about potential problems.
The above short secure Joomla extensions guidilines should give you an idea on how to write more secure Joomla extensions.
PHP CMS Frameworks
November 05, 2014
Read more →
Joomla
Joomla - Duplicate Meta Description in Google Webmaster Optimization
For most of us who have been using Joomla 1.5 till 2.5, we are still facing the same old school issues of duplicated meta descriptions and title tags as reported in our Google Webmaster tools. As we're already used to this tools, I believed most of us can't sit comfortably as the duplication rate increases with every new pages that we created.
In general and as default, almost all Joomla user especially from the beginner (I'm at this level =)) to intermediate knowledge will experienced this kind of issue. We thought that it was nothing to be alarmed off until you started to feel uneasy on the rising amount of duplicate meta and title in your Google Webmaster report. Not until I watched videos on Matt comments (watch the videos below) on how Google use our meta description and keywords that I start to prioritise the importance of eliminating or reducing the duplication rate.
In this article, we are not going to install anything, just a little hard works. This has been done on my website and the result is satisfactory as the number or duplicate meta reduced from 50 (urrgh,) to 10. Another advice worth mentioned here is that, sometimes the duplicate meta description is caused by 'old link's from your internal pages that still pointed to 'old url' or the duplicate links (I'll explained it in the next post).
Global Configuration
Meta description and keywords should be empty. Leave it blank as mentioned in Joomla documentation. If you haven't read the document, you should better read sometimes.
Hard works Parts
Now, everytime you create a new page, you will need to create a unique meta description and keywords related to each pages. Most user will ignore this part but try to make a good habit of practicing this method. The option to add specific meta description to every pages is located in your article manager at the right side.
Regardless the techniques on how to improve our page ranking, here's some video worth our attention on the topic of whether Google use our meta keywords in search ranking and emphasize the use of 'unique' description by Matt Cutts.
Regarding the use of meta description
Regarding the use of meta keywords
In general and as default, almost all Joomla user especially from the beginner (I'm at this level =)) to intermediate knowledge will experienced this kind of issue. We thought that it was nothing to be alarmed off until you started to feel uneasy on the rising amount of duplicate meta and title in your Google Webmaster report. Not until I watched videos on Matt comments (watch the videos below) on how Google use our meta description and keywords that I start to prioritise the importance of eliminating or reducing the duplication rate.
In this article, we are not going to install anything, just a little hard works. This has been done on my website and the result is satisfactory as the number or duplicate meta reduced from 50 (urrgh,) to 10. Another advice worth mentioned here is that, sometimes the duplicate meta description is caused by 'old link's from your internal pages that still pointed to 'old url' or the duplicate links (I'll explained it in the next post).
Global Configuration
Meta description and keywords should be empty. Leave it blank as mentioned in Joomla documentation. If you haven't read the document, you should better read sometimes.
Hard works Parts
Now, everytime you create a new page, you will need to create a unique meta description and keywords related to each pages. Most user will ignore this part but try to make a good habit of practicing this method. The option to add specific meta description to every pages is located in your article manager at the right side.
Regardless the techniques on how to improve our page ranking, here's some video worth our attention on the topic of whether Google use our meta keywords in search ranking and emphasize the use of 'unique' description by Matt Cutts.
Regarding the use of meta description
Regarding the use of meta keywords
PHP CMS Frameworks
November 02, 2014
Read more →
Symfony
Zend
Symfony 2 - Use Dependency Injection as a standalone component
In this article, we are going to discuss about How to use the Dependency Injection component as a standalone component without using the whole Symfony 2 framework. I will also use ClassLoader from Symfony and just for the sake of the demo I will integrate it with Zend Framework. The code requires PHP 5.3 (mostly for namespaces support).
Create a directory for your project. Inside create "lib" directory. Inside lib, create directory structure: Symfony/Component. Put ClassLoader code inside Component – the easiest thing to do is to clone if from Symfony github:
cd lib/Symfony/Component
git clone https://github.com/symfony/ClassLoader.git
The same goes for DependencyInjection component:
cd lib/Symfony/Component
git clone https://github.com/symfony/DependencyInjection.git
Finally download Zend Framework and put the contents of Zend directory into lib/Zend (so for instance Log.php file will be available in lib/Zend/Log.php).
The actual source code will go into "src" directory, which is a sibling directory of "lib".
Configuring the ClassLoader
DependencyInjection uses namespaces for managing classes, so it needs to be registered with registerNamespace method. Zend Framework follows PEAR naming convention for classes – registerPrefix will do the work for us. Finally, I will register our own code that will be stored in src directory. I will use namespaces as well. Create a new file (let's call it main.php) in the top-level directory:
require_once('lib/Symfony/Component/ClassLoader/UniversalClassLoader.php');
$loader = new Symfony\Component\ClassLoader\UniversalClassLoader();
$loader->registerNamespace('PHPCmsframework',__DIR__.'/src');
$loader->registerNamespace('Symfony',__DIR__.'/lib');
$loader->registerPrefix('Zend',__DIR__.'/lib');
$loader->register();
set_include_path(get_include_path().PATH_SEPARATOR.__DIR__.'/lib');
ClassLoader should now work just fine but we still need set_include_path so require functions inside Zend code will work correctly.
Dependency Injection container
Create a sample class that we'll use for testing. I will call it Test and put it into PHPCmsframework\Techblog, which means it should be located at src/PHPCmsframework/Techblog/Test.php:
namespace PHPCmsframework\Techblog;
class Test
{
private $logger;
public function __construct($logger) {
$this->logger = $logger;
}
public function run() {
$this->logger->info("Running...");
}
}
$logger should be injected using container – here is where we will use Zend_Log class. This one in turn requires a Writer, so we will create it as well. The rest of main.php will look like this:
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
$sc = new ContainerBuilder();
$sc->register('log.writer','Zend_Log_Writer_Stream')
->addArgument('php://output');
$sc->register('logger', 'Zend_Log')
->addArgument(new Reference('log.writer'));
$sc->register('test','PHPCmsframework\Techblog\Test')
->addArgument(new Reference('logger'));
$sc->get('test')->run();
Running the code should give an output like below:
% php main.php
2011-06-09T15:17:22+01:00 INFO (6): Running...
Create a directory for your project. Inside create "lib" directory. Inside lib, create directory structure: Symfony/Component. Put ClassLoader code inside Component – the easiest thing to do is to clone if from Symfony github:
cd lib/Symfony/Component
git clone https://github.com/symfony/ClassLoader.git
The same goes for DependencyInjection component:
cd lib/Symfony/Component
git clone https://github.com/symfony/DependencyInjection.git
Finally download Zend Framework and put the contents of Zend directory into lib/Zend (so for instance Log.php file will be available in lib/Zend/Log.php).
The actual source code will go into "src" directory, which is a sibling directory of "lib".
Configuring the ClassLoader
DependencyInjection uses namespaces for managing classes, so it needs to be registered with registerNamespace method. Zend Framework follows PEAR naming convention for classes – registerPrefix will do the work for us. Finally, I will register our own code that will be stored in src directory. I will use namespaces as well. Create a new file (let's call it main.php) in the top-level directory:
require_once('lib/Symfony/Component/ClassLoader/UniversalClassLoader.php');
$loader = new Symfony\Component\ClassLoader\UniversalClassLoader();
$loader->registerNamespace('PHPCmsframework',__DIR__.'/src');
$loader->registerNamespace('Symfony',__DIR__.'/lib');
$loader->registerPrefix('Zend',__DIR__.'/lib');
$loader->register();
set_include_path(get_include_path().PATH_SEPARATOR.__DIR__.'/lib');
ClassLoader should now work just fine but we still need set_include_path so require functions inside Zend code will work correctly.
Dependency Injection container
Create a sample class that we'll use for testing. I will call it Test and put it into PHPCmsframework\Techblog, which means it should be located at src/PHPCmsframework/Techblog/Test.php:
namespace PHPCmsframework\Techblog;
class Test
{
private $logger;
public function __construct($logger) {
$this->logger = $logger;
}
public function run() {
$this->logger->info("Running...");
}
}
$logger should be injected using container – here is where we will use Zend_Log class. This one in turn requires a Writer, so we will create it as well. The rest of main.php will look like this:
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
$sc = new ContainerBuilder();
$sc->register('log.writer','Zend_Log_Writer_Stream')
->addArgument('php://output');
$sc->register('logger', 'Zend_Log')
->addArgument(new Reference('log.writer'));
$sc->register('test','PHPCmsframework\Techblog\Test')
->addArgument(new Reference('logger'));
$sc->get('test')->run();
Running the code should give an output like below:
% php main.php
2011-06-09T15:17:22+01:00 INFO (6): Running...
PHP CMS Frameworks
October 29, 2014
Read more →
CodeIgniter
CodeIgniter – Add Captcha to your website
In this article, we are going to discuss about How to add captcha to your website in CodeIgniter (CI). In CodeIgniter (CI), we have an in-built helper to add captcha named "Captcha Helper". Using Captcha helper, we can easily integrate Captcha into our application. To use this helper we have to load it.
At first we have to create a table for Captcha in our database. It contains four fields.
id => INT, word => TEXT, ip => TEXT, time=>TEXT
Then use the following code.
$this->load->helper('url');
$this->load->helper('string');
$this->load->helper('captcha');
Then declare an array with the following values. This array contains the values needed to create Captcha.
$rand = random_string('numeric', 8);
$vals = array(
'word' => $rand,
'img_path' => './captcha/',
'img_url' => './captcha/',
'img_width' => '150',
'img_height' => 60,
'expiration' => 7200
);
$cap = create_captcha($vals); // Generates Capthca
I would like to explain the values mentioned in this array. First 'word' mentions the random value to be displayed. I generated a random number of length 8 and assigned it to the Captcha word. Next is 'img_path'. This decides the path to the file where generated Captcha image is to be stored. 'img_url' defines the path to be used when displaying the image. As name specifies 'img_width','img_height','expiration' denotes the image width, height and expiration time of Captcha.
Next we have to insert the generated Captcha value into table.
$this->load->model('common_model');
$this->common_model->insert_captcha($cap);
$data['cap'] = $cap;
$this->load->view('welcome_message',$data);
Add the following in your View file.
<p><h3>Enter the following Number</h3></p>
<form action="<?php echo base_url().'index.php/welcome/check' ?>" method="post">
<?php echo $cap['image']; ?><br>
<input type="text" name="captcha" placeholder="Type here.."/>
<br><br>
<input type="submit" value="submit">
</form>
Captcha values are inserted into the table and View is called.
Then on form submission, use the following code.
$expiration = time()-7200; // Two hour limit
$ip = $_SERVER['REMOTE_ADDR'];
$this->load->database();
$this->db->query("DELETE FROM captcha WHERE time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip = ? AND time > ?";
$binds = array($_POST['captcha'], $ip, $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
echo "You must submit the word that appears in the image";
}
else{
echo "Matches";
}
At first we have to create a table for Captcha in our database. It contains four fields.
id => INT, word => TEXT, ip => TEXT, time=>TEXT
Then use the following code.
$this->load->helper('url');
$this->load->helper('string');
$this->load->helper('captcha');
Then declare an array with the following values. This array contains the values needed to create Captcha.
$rand = random_string('numeric', 8);
$vals = array(
'word' => $rand,
'img_path' => './captcha/',
'img_url' => './captcha/',
'img_width' => '150',
'img_height' => 60,
'expiration' => 7200
);
$cap = create_captcha($vals); // Generates Capthca
I would like to explain the values mentioned in this array. First 'word' mentions the random value to be displayed. I generated a random number of length 8 and assigned it to the Captcha word. Next is 'img_path'. This decides the path to the file where generated Captcha image is to be stored. 'img_url' defines the path to be used when displaying the image. As name specifies 'img_width','img_height','expiration' denotes the image width, height and expiration time of Captcha.
Next we have to insert the generated Captcha value into table.
$this->load->model('common_model');
$this->common_model->insert_captcha($cap);
$data['cap'] = $cap;
$this->load->view('welcome_message',$data);
Add the following in your View file.
<p><h3>Enter the following Number</h3></p>
<form action="<?php echo base_url().'index.php/welcome/check' ?>" method="post">
<?php echo $cap['image']; ?><br>
<input type="text" name="captcha" placeholder="Type here.."/>
<br><br>
<input type="submit" value="submit">
</form>
Captcha values are inserted into the table and View is called.
Then on form submission, use the following code.
$expiration = time()-7200; // Two hour limit
$ip = $_SERVER['REMOTE_ADDR'];
$this->load->database();
$this->db->query("DELETE FROM captcha WHERE time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip = ? AND time > ?";
$binds = array($_POST['captcha'], $ip, $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
echo "You must submit the word that appears in the image";
}
else{
echo "Matches";
}
PHP CMS Frameworks
October 27, 2014
Read more →
YII
SEO and Clean URLs in YII Framework
In this article, we are going to discuss about How to create a SEO and Clean URLs in Yii PHP Framework. Yii is a modern and robust PHP framework aimed to secure and scalable programming. It is not hardern or more complex compared to the popular PHP frameworks such as CakePHP. It supports all major databases from MySQL to Sqlite. The best is that it is much faster and scalable compared to other frameworks. The latter is what made me reconsider using it over CakePHP.
By default Yii routes all URL requests transparently through the main index.php file and your URLs look like this:
http://example.org/?r=site/page&view=about
Our aim is to make it look:
http://example.org/site/page/view/about
For this purpose follow these steps:
Open your site root protected/config/main.php and uncomment the part about the urlManager so that it looks like this:
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName'=> false,
'rules'=>array(
'/'=>'/view',
),
),
Add the following lines to your .htaccess (provided you are using Apache or compatible web server):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
Last you may wish to drop controller / action from the URL. This can be also done by a custom rule in the urlManager array in protected/config/main.php:
'about'=>'site/page/view/about',
This will ensure that by just going to http://example.org/about you will be routed to http://example.org/site/page/view/about.
By default Yii routes all URL requests transparently through the main index.php file and your URLs look like this:
http://example.org/?r=site/page&view=about
Our aim is to make it look:
http://example.org/site/page/view/about
For this purpose follow these steps:
Open your site root protected/config/main.php and uncomment the part about the urlManager so that it looks like this:
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName'=> false,
'rules'=>array(
'/'=>'/view',
),
),
Add the following lines to your .htaccess (provided you are using Apache or compatible web server):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
Last you may wish to drop controller / action from the URL. This can be also done by a custom rule in the urlManager array in protected/config/main.php:
'about'=>'site/page/view/about',
This will ensure that by just going to http://example.org/about you will be routed to http://example.org/site/page/view/about.
PHP CMS Frameworks
October 15, 2014
Read more →
Magento
Steps to add WYSIWYG editor to Magento backend
In thia article, we are going to discuss about steps to add WYSIWYG editor in Magento admin backend. WYSIWYG editor is a tool that helps easily format or edit text or html code as you want. By adding WYSIWYG editor to your backend, you will have a visual editor rather than dealing with all code.
However, this task seems not as simple as adding other fields. It requires inserting some javascript and css files to make the editor work. Thus this post may be a good resource for you. Just keep on reading and follow the steps below to learn how to add WYSIWYG editor to Magento backend.
Step 1 : Enable WYSIWYG editor in your field
Open the file "app/code/local/[your_name_space]/[your_module]/Block/Adminhtml/[your_block]/Edit/Tabs/Form.php" and add the below codes.
$fieldset->addField('description', 'editor', array(
'label' => Mage::helper('customerreward')->__('Description'),
'title' => Mage::helper('customerreward')->__('Description'),
'class' => 'required-entry',
'required' => true,
'name' => 'description',
'wysiwyg' => true,// enable WYSIWYG editor
));
Step 2: Add js and css files to controller action
You can follow either of these ways:
Step 2.1 : Use PHP code in your controller action:
Open the file "app/code/local/[your_name_space]/[your_module]/controllers/Adminhtml/[controller_name]Controller.php" add the below codes.
$this->getLayout()->getBlock('head')
->setCanLoadExtJs(true)
->setCanLoadTinyMce(true)
->addItem('js','tiny_mce/tiny_mce.js')
->addItem('js','mage/adminhtml/wysiwyg/tiny_mce/setup.js')
->addJs('mage/adminhtml/browser.js')
->addJs('prototype/window.js')
->addJs('lib/flex.js')
->addJs('mage/adminhtml/flexuploader.js')
->addItem('js_css','prototype/windows/themes/default.css')
->addItem('js_css','prototype/windows/themes/magento.css');
Step 2.2 : Use layout file:
Open the file "app/design/adminhtml/default/default/layout.xml" and add the below codes
<referencename="head">
<actionmethod="setCanLoadExtJs"><flag>1</flag></action>
<actionmethod="setCanLoadTinyMce"><flag>1</flag></action>
<actionmethod="addJs"><script>lib/flex.js</script></action>
<actionmethod="addJs"><script>mage/adminhtml/flexuploader.js</script></action>
<actionmethod="addJs"><script>mage/adminhtml/browser.js</script></action>
<actionmethod="addJs"><script>prototype/window.js</script></action>
<actionmethod="addItem"><type>js_css</type><name>prototype/windows/themes/default.css</name></action>
<actionmethod="addItem"><type>js_css</type><name>prototype/windows/themes/magento.css</name></action>
<actionmethod="addItem"><type>js</type><name>mage/adminhtml/wysiwyg/tiny_mce/setup.js</name><params/></action>
<actionmethod="addItem"><type>js</type><name>tiny_mce/tiny_mce.js</name><params/></action>
</reference>
Now, you can view this form shown in your Magento admin backend.
However, this task seems not as simple as adding other fields. It requires inserting some javascript and css files to make the editor work. Thus this post may be a good resource for you. Just keep on reading and follow the steps below to learn how to add WYSIWYG editor to Magento backend.
Step 1 : Enable WYSIWYG editor in your field
Open the file "app/code/local/[your_name_space]/[your_module]/Block/Adminhtml/[your_block]/Edit/Tabs/Form.php" and add the below codes.
$fieldset->addField('description', 'editor', array(
'label' => Mage::helper('customerreward')->__('Description'),
'title' => Mage::helper('customerreward')->__('Description'),
'class' => 'required-entry',
'required' => true,
'name' => 'description',
'wysiwyg' => true,// enable WYSIWYG editor
));
Step 2: Add js and css files to controller action
You can follow either of these ways:
Step 2.1 : Use PHP code in your controller action:
Open the file "app/code/local/[your_name_space]/[your_module]/controllers/Adminhtml/[controller_name]Controller.php" add the below codes.
$this->getLayout()->getBlock('head')
->setCanLoadExtJs(true)
->setCanLoadTinyMce(true)
->addItem('js','tiny_mce/tiny_mce.js')
->addItem('js','mage/adminhtml/wysiwyg/tiny_mce/setup.js')
->addJs('mage/adminhtml/browser.js')
->addJs('prototype/window.js')
->addJs('lib/flex.js')
->addJs('mage/adminhtml/flexuploader.js')
->addItem('js_css','prototype/windows/themes/default.css')
->addItem('js_css','prototype/windows/themes/magento.css');
Step 2.2 : Use layout file:
Open the file "app/design/adminhtml/default/default/layout.xml" and add the below codes
<referencename="head">
<actionmethod="setCanLoadExtJs"><flag>1</flag></action>
<actionmethod="setCanLoadTinyMce"><flag>1</flag></action>
<actionmethod="addJs"><script>lib/flex.js</script></action>
<actionmethod="addJs"><script>mage/adminhtml/flexuploader.js</script></action>
<actionmethod="addJs"><script>mage/adminhtml/browser.js</script></action>
<actionmethod="addJs"><script>prototype/window.js</script></action>
<actionmethod="addItem"><type>js_css</type><name>prototype/windows/themes/default.css</name></action>
<actionmethod="addItem"><type>js_css</type><name>prototype/windows/themes/magento.css</name></action>
<actionmethod="addItem"><type>js</type><name>mage/adminhtml/wysiwyg/tiny_mce/setup.js</name><params/></action>
<actionmethod="addItem"><type>js</type><name>tiny_mce/tiny_mce.js</name><params/></action>
</reference>
Now, you can view this form shown in your Magento admin backend.
PHP CMS Frameworks
October 12, 2014
Read more →
CakePHP
Simple Cakephp 2.x AuthComponent example
In this article, we are going to discuss about How to create a simple AuthComponent in CakePHP 2.x. To make restricted access level site in cakephp we need to implement AuthComponent in cakephp. To apply AuthComponent in cakephp 2.x is similar like to apply AuthComponent in Cakephp 1.x. I think you know cakephp.
Here I described the Authcomponent implementation system for Cakephp 2.x
Step 1 :
Create a users table like bellow
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`firstname` varchar(255) NOT NULL,
`lastname` varchar(255) DEFAULT NULL,
`address` text,
`mobile` varchar(255) DEFAULT NULL,
`status` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
Step 2 :
Create respective UserController, UserModel and view files.
Step 3:
For User Password hashing you need to add the SimplePasswordHasher component in your model table:
// app/Model/User.php
App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
// ...
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher();
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
Step 4:
Open your AppController and write the bellow code
// app/Controller/AppController.php
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array(
'controller' => 'members',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'pages',
'action' => 'display',
'home'
),
'authorize' => array('Controller')
)
);
public function isAuthorized() {
$userDetails = AuthComponent::user();
if($userDetails['group_id'] == 1) return true;
if(!empty($this->permissions[$this->action]))
{
if($this->permissions[$this->action] == '*') return true;
if(in_array($userDetails['group_id'], $this->permissions[$this->action]))
{
return true;
}
}else{
$this->Session->setFlash(__('You are not authorize to access that location.'));
return false;
}
}
}
Step 5:
Go to your user controller and add the following methods:
// app/Controller/UsersController.php
public function beforeFilter() {
parent::beforeFilter();
// Allow all users to register and logout.
$this->Auth->allow('add', 'logout');
}
public function login() {
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
}else
{
$this->Session->setFlash('Data Validation Failure', 'default', array('class' => 'cake-error'));
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
Step 6:
Create login.ctp file with bellow code:
//app/View/Users/login.ctp
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend>
<?php echo __('Please enter your username and password'); ?>
</legend>
<?php echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>
All done now you can check the AuthComponent action by accessing your application:
Here I described the Authcomponent implementation system for Cakephp 2.x
Step 1 :
Create a users table like bellow
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`firstname` varchar(255) NOT NULL,
`lastname` varchar(255) DEFAULT NULL,
`address` text,
`mobile` varchar(255) DEFAULT NULL,
`status` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
Step 2 :
Create respective UserController, UserModel and view files.
Step 3:
For User Password hashing you need to add the SimplePasswordHasher component in your model table:
// app/Model/User.php
App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
// ...
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher();
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
Step 4:
Open your AppController and write the bellow code
// app/Controller/AppController.php
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array(
'controller' => 'members',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'pages',
'action' => 'display',
'home'
),
'authorize' => array('Controller')
)
);
public function isAuthorized() {
$userDetails = AuthComponent::user();
if($userDetails['group_id'] == 1) return true;
if(!empty($this->permissions[$this->action]))
{
if($this->permissions[$this->action] == '*') return true;
if(in_array($userDetails['group_id'], $this->permissions[$this->action]))
{
return true;
}
}else{
$this->Session->setFlash(__('You are not authorize to access that location.'));
return false;
}
}
}
Step 5:
Go to your user controller and add the following methods:
// app/Controller/UsersController.php
public function beforeFilter() {
parent::beforeFilter();
// Allow all users to register and logout.
$this->Auth->allow('add', 'logout');
}
public function login() {
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
}else
{
$this->Session->setFlash('Data Validation Failure', 'default', array('class' => 'cake-error'));
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
Step 6:
Create login.ctp file with bellow code:
//app/View/Users/login.ctp
<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend>
<?php echo __('Please enter your username and password'); ?>
</legend>
<?php echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>
All done now you can check the AuthComponent action by accessing your application:
PHP CMS Frameworks
October 09, 2014
Read more →
Wordpress
Create Ajax Comments System in WordPress
In this article, we are going to discuss about How to create an ajax comments system in Wordpress. WordPress started in 2003 with a single bit of code to enhance the typography of everyday writing and with fewer users than you can count on your fingers and toes. Since then it has grown to be the largest self-hosted blogging tool in the world, used on millions of sites and seen by tens of millions of people every day.
Here is the code for creating ajax comments system in WordPress.
var commentform = $('#commentform');
// find the comment form
commentform.prepend('<div id="comment-status" ></div>');
// add info panel before the form to provide feedback or errors
var statusdiv = $('#comment-status');
var commentsdiv = $('.commentlist');
// define the infopanel
commentform.submit(function() {
//serialize and store form data in a variable
var formdata = commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl = commentform.attr('action');
//Post Form with data
$.ajax({
type : 'post',
dataType: 'json',
url : formurl,
data : formdata,
error : function(XMLHttpRequest, textStatus, errorThrown) {
statusdiv.html('<p class="wdpajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
},
success : function(data, textStatus) {
console.log(data);
if (data.comment_approved === "1"){
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
commentsdiv.prepend('<li class="comment byuser comment-author-admin bypostauthor even thread-even depth-1" id="comment-1"><div class="comment-body" id="comment-body-1"><div class="comment-avatar-box"><div class="avb"><a href="http://vidibase.com/members/' + data.comment_author + '/" rel="nofollow"><img src="http://i0.wp.com/vidibase.com/wp-content/plugins/buddypress/bp-core/images/mystery-man.jpg" class="avatar user-1-avatar avatar-60 photo" width="60" height="60" alt="Avatar Image"></a></div></div><div class="comment-content"><div class="comment-meta"><p><a href="http://vidibase.com/members/' + data.comment_author + '/" rel="nofollow">' + data.comment_author + '</a> said on <a href="#"><span class="time-since">Just now</span></a></p></div><div class="comment-entry"><p>' + data.comment_content + '</p></div><div class="comment-options"></div><div class="clear"> </div></div></li>');
}else{
statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
commentform.find('textarea[name=comment]').val('');
}
}
});
return false;
});
Add the below code in functions.php file
add_action('comment_post', 'ajaxify_comments',20, 2);
function ajaxify_comments($comment_ID, $comment_status){
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
//If AJAX Request Then
switch($comment_status){
case '0':
//notify moderator of unapproved comment
wp_notify_moderator($comment_ID);
case '1': //Approved comment
$commentdata=&get_comment($comment_ID, ARRAY_A);
$post=&get_post($commentdata['comment_post_ID']);
wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
echo json_encode($commentdata);
break;
default:
echo "error";
}
exit;
}
}
Here is the code for creating ajax comments system in WordPress.
var commentform = $('#commentform');
// find the comment form
commentform.prepend('<div id="comment-status" ></div>');
// add info panel before the form to provide feedback or errors
var statusdiv = $('#comment-status');
var commentsdiv = $('.commentlist');
// define the infopanel
commentform.submit(function() {
//serialize and store form data in a variable
var formdata = commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl = commentform.attr('action');
//Post Form with data
$.ajax({
type : 'post',
dataType: 'json',
url : formurl,
data : formdata,
error : function(XMLHttpRequest, textStatus, errorThrown) {
statusdiv.html('<p class="wdpajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
},
success : function(data, textStatus) {
console.log(data);
if (data.comment_approved === "1"){
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
commentsdiv.prepend('<li class="comment byuser comment-author-admin bypostauthor even thread-even depth-1" id="comment-1"><div class="comment-body" id="comment-body-1"><div class="comment-avatar-box"><div class="avb"><a href="http://vidibase.com/members/' + data.comment_author + '/" rel="nofollow"><img src="http://i0.wp.com/vidibase.com/wp-content/plugins/buddypress/bp-core/images/mystery-man.jpg" class="avatar user-1-avatar avatar-60 photo" width="60" height="60" alt="Avatar Image"></a></div></div><div class="comment-content"><div class="comment-meta"><p><a href="http://vidibase.com/members/' + data.comment_author + '/" rel="nofollow">' + data.comment_author + '</a> said on <a href="#"><span class="time-since">Just now</span></a></p></div><div class="comment-entry"><p>' + data.comment_content + '</p></div><div class="comment-options"></div><div class="clear"> </div></div></li>');
}else{
statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
commentform.find('textarea[name=comment]').val('');
}
}
});
return false;
});
Add the below code in functions.php file
add_action('comment_post', 'ajaxify_comments',20, 2);
function ajaxify_comments($comment_ID, $comment_status){
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
//If AJAX Request Then
switch($comment_status){
case '0':
//notify moderator of unapproved comment
wp_notify_moderator($comment_ID);
case '1': //Approved comment
$commentdata=&get_comment($comment_ID, ARRAY_A);
$post=&get_post($commentdata['comment_post_ID']);
wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
echo json_encode($commentdata);
break;
default:
echo "error";
}
exit;
}
}
PHP CMS Frameworks
September 28, 2014
Read more →
CakePHP
Steps to add file download option in Cakephp
In this article, we are going to discuss about How to add file download option in CakePHP. CakePHP is an open source web application framework. It follows the Model-View-Controller (MVC) approach and is written in PHP, modeled after the concepts of Ruby on Rails, and distributed under the MIT License. CakePHP uses well-known software engineering concepts and software design patterns, as Convention over configuration, Model-View-Controller, Active Record, Association Data Mapping, and Front Controller.
To add the file download option in CakePHP, include the below action in your controller, from which controller you want to execute the download
function file_download($file_name = null) {
$this->autoRender = false;
$this->set('fileName', $file_name);
header('Content-Type: application/download');
$url = WWW_ROOT.DS.'fileFolderName'.DS.$file_name;
header("Content-Disposition: attachment; filename=".basename($url));
header("Content-Length: " . filesize($url));
$fp = fopen($url, "r");
fpassthru($fp);
fclose($fp);
}
Now add the following link in your View file from where you want to download the file
echo $this->Html->link(__('Download', true), array('controller' => 'mycontroller','action' => 'pdf_download', $file['file_name']));
/* Here $file['file_name'] is the name of your file. */
To add the file download option in CakePHP, include the below action in your controller, from which controller you want to execute the download
function file_download($file_name = null) {
$this->autoRender = false;
$this->set('fileName', $file_name);
header('Content-Type: application/download');
$url = WWW_ROOT.DS.'fileFolderName'.DS.$file_name;
header("Content-Disposition: attachment; filename=".basename($url));
header("Content-Length: " . filesize($url));
$fp = fopen($url, "r");
fpassthru($fp);
fclose($fp);
}
Now add the following link in your View file from where you want to download the file
echo $this->Html->link(__('Download', true), array('controller' => 'mycontroller','action' => 'pdf_download', $file['file_name']));
/* Here $file['file_name'] is the name of your file. */
PHP CMS Frameworks
September 24, 2014
Read more →
CodeIgniter
CodeIgniter - Change the URL and Email as Hyperlink automatically
In this article, we are going to discuss about How to change the URL and Email as Hyperlink in CodeIgniter. We might have seen plain text get converted to hypertext when we type it. For example, In gtalk when we type www.phpcmsframework.com it automatically changes as a hyperlink and point to http://www.phpcmsframework.com, Same way, when we type an email address it is automatically converted to mailto:phpcmsframework@gmail.com.
These kind of conversion can be made using PHP string replace function. We have to check the whole string where it has the url or email address, then we have to replace the url with anchor tag.
In CodeIgniter the easiest way to do it is to use the URL helper. First step is to load the URL helper.
$this->load->helper('url');
Then the next thing to do is to use a function
auto_link();
This function makes our life easier. We have to pass the string that we need to find for url and email.
$string = "This is a sample text and its url is www.phpcmsframework.com";
echo auto_link($string);
The output of the above code is Today I visited a useful blog about web development and its url is www.phpcmsframework.com
The same way email id is also auto linked. We can also restrict the automation only to url or email. This can be done by
echo auto_link($string,'email');
echo auto_link($string,'url');
In case if we want the link to open in a new tab, we can do it by adding a third parameter which can be either TRUE or FALSE.
echo auto_link($string, 'both', TRUE);
Here second parameter 'both' indicates that both 'email' and 'url' has to be automatically converted to hypertext.
These kind of conversion can be made using PHP string replace function. We have to check the whole string where it has the url or email address, then we have to replace the url with anchor tag.
In CodeIgniter the easiest way to do it is to use the URL helper. First step is to load the URL helper.
$this->load->helper('url');
Then the next thing to do is to use a function
auto_link();
This function makes our life easier. We have to pass the string that we need to find for url and email.
$string = "This is a sample text and its url is www.phpcmsframework.com";
echo auto_link($string);
The output of the above code is Today I visited a useful blog about web development and its url is www.phpcmsframework.com
The same way email id is also auto linked. We can also restrict the automation only to url or email. This can be done by
echo auto_link($string,'email');
echo auto_link($string,'url');
In case if we want the link to open in a new tab, we can do it by adding a third parameter which can be either TRUE or FALSE.
echo auto_link($string, 'both', TRUE);
Here second parameter 'both' indicates that both 'email' and 'url' has to be automatically converted to hypertext.
PHP CMS Frameworks
September 17, 2014
Read more →
Symfony
Procedure to Manually authenticate user in Symfony 2 framework
In this article, we are going to discuss about How to manually authenticate users in Symfony 2 PHP Framework. Normally in each and every framework authencation in handled automatically. Sometimes, however you may want to perform authentication manually from the controller.
Imagine implementing automated login for a user upon visiting a URL like: /autologin/{secret}. I am not considering here the security of such a solution – you are discourage to do it this way, unless the information available for this kind of "logins" is not confidential.
Here is a fragment from my security.yml:
security:
firewalls:
secured_area:
pattern: ^/
form_login:
check_path: /login_check
login_path: /login
The actual authentication is very straight-forward. Since I'm redirecting at the end of request, I don't even need the user to be authenticated in this action. All that is needed is to persist the information about authenticated user to the session. This means storing serialized class that implements TokenInterface. Normally this is done by Symfony framework in ContextListener. In my scenario I'm using form login that uses UsernamePasswordToken, so in short here is what I need to do:
Pay attention to "secured_area" string – it matches the firewall name from the security.yml and is used to create the token and when creating a session key.
/**
* @Route("/autologin/{secret}")
*/
public function autologinAction($secret) {
$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('MiedzywodzieClientBundle:Reservation');
$result = $repository->matchLoginKey($secret);
if (!$result) {
return $this->render('MiedzywodzieClientBundle:Default:autologin_incorrect.html.twig');
}
$result = $result[0];
$token = new UsernamePasswordToken($result, $result->getPassword(), 'secured_area', $result->getRoles());
$request = $this->getRequest();
$session = $request->getSession();
$session->set('_security_secured_area', serialize($token));
$router = $this->get('router');
$url = $router->generate('miedzywodzie_client_default_dashboard');
return $this->redirect($url);
}
Imagine implementing automated login for a user upon visiting a URL like: /autologin/{secret}. I am not considering here the security of such a solution – you are discourage to do it this way, unless the information available for this kind of "logins" is not confidential.
Here is a fragment from my security.yml:
security:
firewalls:
secured_area:
pattern: ^/
form_login:
check_path: /login_check
login_path: /login
The actual authentication is very straight-forward. Since I'm redirecting at the end of request, I don't even need the user to be authenticated in this action. All that is needed is to persist the information about authenticated user to the session. This means storing serialized class that implements TokenInterface. Normally this is done by Symfony framework in ContextListener. In my scenario I'm using form login that uses UsernamePasswordToken, so in short here is what I need to do:
- Find user
- Create the Token
- Store Token in the session
Pay attention to "secured_area" string – it matches the firewall name from the security.yml and is used to create the token and when creating a session key.
/**
* @Route("/autologin/{secret}")
*/
public function autologinAction($secret) {
$em = $this->getDoctrine()->getEntityManager();
$repository = $em->getRepository('MiedzywodzieClientBundle:Reservation');
$result = $repository->matchLoginKey($secret);
if (!$result) {
return $this->render('MiedzywodzieClientBundle:Default:autologin_incorrect.html.twig');
}
$result = $result[0];
$token = new UsernamePasswordToken($result, $result->getPassword(), 'secured_area', $result->getRoles());
$request = $this->getRequest();
$session = $request->getSession();
$session->set('_security_secured_area', serialize($token));
$router = $this->get('router');
$url = $router->generate('miedzywodzie_client_default_dashboard');
return $this->redirect($url);
}
PHP CMS Frameworks
September 10, 2014
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
-
▼
2014
(86)
-
▼
December
(8)
- AllVideos - Joomla Video and Multimedia Extension ...
- Codeigniter - Run Multiple Sites from single install
- Steps to Add Icon for New Products in Magento
- Steps to install DebugKit in CakePHP on Ubuntu 14.04
- Steps to Add HTTP authentication to your Drupal site
- Restrict Access to WordPress files using htaccess
- YII Controller methods - render and renderPartial
- Create Custom Toolbar for ZendDeveloperTools - Zen...
-
►
November
(8)
- Steps to Install Magento On Ubuntu
- Steps to Install CodeIgniter On LinuxMint and Ubuntu
- Steps to Install CakePHP on Ubuntu 14.04
- Fix Too Many Redirects Loop Error in WordPress
- Access Rules and Access Control in YII
- Drupal 7 - Download Adaptive Theme free
- Create Secure Joomla Extensions
- Joomla - Duplicate Meta Description in Google Webm...
-
▼
December
(8)

