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 →
Drupal
Steps to configure google maps with nodes in Drupal
In this article, we are going to discuss about How to configure google maps with nodes in Drupal. Drupal is a free software package that allows you to easily organize, manage and publish your content, with an endless variety of customization.
Step 1: Install Locations Module
Step 2: Install Gmap Module
Step 3: Enable Gmap Location Module Which is part of Gmap Module.
Step 4: Set the Google Map Key Here admin/settings/gmap
Step 5: Go here admin/settings/location/main and select default country and check Use a Google Map to set latitude and longitude
Step 6: Go to content type edit tab and select Locations Collapsible tab, under that go to Number Of Locations and set min, max, Number of locations that can be added at once as 1,1,1 respectively
Step 7: Go to your nodes click on edit and you can see location settings, there give the address and longitude and latitude which you can pick from map or you can set. Longitude and Latitude are very important to locate a node in map
Step 8: Save the node.
Step 9: admin/settings/gmap_location go here, under node map select marker action as open link.
Step 10: Now go to map/node you can see all your nodes here.
Step 11: If you want to enable map for nodes go to blocks, enable the block called Location Map
That's it you are done.
Step 1: Install Locations Module
Step 2: Install Gmap Module
Step 3: Enable Gmap Location Module Which is part of Gmap Module.
Step 4: Set the Google Map Key Here admin/settings/gmap
Step 5: Go here admin/settings/location/main and select default country and check Use a Google Map to set latitude and longitude
Step 6: Go to content type edit tab and select Locations Collapsible tab, under that go to Number Of Locations and set min, max, Number of locations that can be added at once as 1,1,1 respectively
Step 7: Go to your nodes click on edit and you can see location settings, there give the address and longitude and latitude which you can pick from map or you can set. Longitude and Latitude are very important to locate a node in map
Step 8: Save the node.
Step 9: admin/settings/gmap_location go here, under node map select marker action as open link.
Step 10: Now go to map/node you can see all your nodes here.
Step 11: If you want to enable map for nodes go to blocks, enable the block called Location Map
That's it you are done.
PHP CMS Frameworks
September 03, 2014
Read more →
Symfony
Integrate Zend Framework components with Symfony2
In this article, we are going to discuss about How to integrate Zend framework components with Symfony2 framework. Symfony2 is a full stack of PHP Development Framework by using the features of PHP 5.3. Zend Framework is a component library that is super a lot and have a MVC layer. When 2 Framework is incorporated, imagine how powerful right?
Hm ... of course the principle of use at will (Use What you Need, Forget Everything Else) should still be used. The need for very complete component in Zend Framework can be used in Symfony with me registers the Zend Framework components in Symfony autoloader Framewok.
Zend Framework library that will we 'list'-right in Symfony2, we have saved in the folder \FrameworkSymfonyApp\vendor\namapackage as follows:
Well, after that, we document in its Symfony2 autoloader:
$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
...
));
$loader->registerPrefixes(array(
....
'Zend_' => __DIR__.'/../vendor/zf'
));
Ok, next is testing time. I will try to use his class Validator Zend Framework, first, we make the first of his class Dependency Injection as follows:
<?php
namespace Testmodule\DependencyInjection;
class TestDependencyContainer
{
private $validator;
public function __construct($validator)
{
$this->validator = $validator;
}
public function run($email)
{
$msg = " not valid ";
if ($this->validator->isValid($email)) {
$msg = " valid ";
}
return $msg;
}
}
Then we try to call on Controller:
<?php
namespace Testmodule\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class TestController extends Controller
{
/**
* @Route("/{email}", name="_test")
* @Template()
*/
public function indexAction($email)
{
$sc = new ContainerBuilder();
$sc->register('validatorEmail', 'Zend_Validate_EmailAddress');
$sc->register('test','Testmodule\DependencyInjection\TestDependencyContainer')
->addArgument(new Reference('validatorEmail'));
$emailisValid = $sc->get('test')->run(
$email
);
return array('emailcheckvalid' => "email $email is $emailisValid ");
}
}
Hmm, if successful, its staying in the view as shown below:
{% extends "Testmodule::layout.html.twig" %}
{% block content %}
Heiiii,... <strong><em><span style="color: red;"> {{emailcheckvalid}} </span> </em></strong>
{% endblock %}
Hm ... of course the principle of use at will (Use What you Need, Forget Everything Else) should still be used. The need for very complete component in Zend Framework can be used in Symfony with me registers the Zend Framework components in Symfony autoloader Framewok.
Zend Framework library that will we 'list'-right in Symfony2, we have saved in the folder \FrameworkSymfonyApp\vendor\namapackage as follows:
Well, after that, we document in its Symfony2 autoloader:
$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
...
));
$loader->registerPrefixes(array(
....
'Zend_' => __DIR__.'/../vendor/zf'
));
Ok, next is testing time. I will try to use his class Validator Zend Framework, first, we make the first of his class Dependency Injection as follows:
<?php
namespace Testmodule\DependencyInjection;
class TestDependencyContainer
{
private $validator;
public function __construct($validator)
{
$this->validator = $validator;
}
public function run($email)
{
$msg = " not valid ";
if ($this->validator->isValid($email)) {
$msg = " valid ";
}
return $msg;
}
}
Then we try to call on Controller:
<?php
namespace Testmodule\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class TestController extends Controller
{
/**
* @Route("/{email}", name="_test")
* @Template()
*/
public function indexAction($email)
{
$sc = new ContainerBuilder();
$sc->register('validatorEmail', 'Zend_Validate_EmailAddress');
$sc->register('test','Testmodule\DependencyInjection\TestDependencyContainer')
->addArgument(new Reference('validatorEmail'));
$emailisValid = $sc->get('test')->run(
);
return array('emailcheckvalid' => "email $email is $emailisValid ");
}
}
Hmm, if successful, its staying in the view as shown below:
{% extends "Testmodule::layout.html.twig" %}
{% block content %}
Heiiii,... <strong><em><span style="color: red;"> {{emailcheckvalid}} </span> </em></strong>
{% endblock %}
PHP CMS Frameworks
September 01, 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
- CIBB - Basic Forum With Codeigniter and Twitter Bootstrap
- Building an Offline AI App with Laravel and Ollama
- Build an AI-Driven personalisation engine in Joomla using User Behaviour data
- Building a RAG System in Laravel from Scratch
- Steps to create a Contact Form in Symfony With SwiftMailer
- Drupal 7 - Create your custom Hello World module
- Build an AI Code Review Bot with Laravel — Real-World Use Case
- Symfony Framework - Introduction
- Laravel and Prism PHP: The Modern Way to Work with AI Models
- Prototype Javascript validation in Magento forms
