Friday, 2 November 2012

Sites which help in boosting your seo rankings

In this post iam trying to share with you some of the important sites where you can post articles related to your site and which can boost your SEO rankings.

1) Social networking sites

facebook- create a page in for your website and get as many likes as you can, post articles regularly.
twitter- create an account in twitter and tweet latest events
Linkedin- create a company page in linkedin and share articles regularly
Gogleplus- googleplus has a great role in boosting your seo rank. you have to create a google page and share articles maximum you can.
Blogs: create a google blog for your website it can boost your seo rank
digg- share links in digg account

2)Image sharing sites

 It is important to post images in most popular image listing sites which can increase possibility of high ranking in google.iam listing some of the top image sharing sites here.upload images with requires title,tag and description and see the result




3) Slide sharing sites

It is important to post powerpoint presentaions  in most popular slide listing sites which can increase possibility of high ranking in google.iam listing some of the top slide sharing sites here.upload images with requires title,tag and description and see the result:-


4) Forums
 This is mainly used to get backlinks to your site. post and comment in famous forums . while posting don't forget to insert a link to your website n coments or posts. But in certain forums we cannnot insert links, but  in certain sites we can post links if we comment or pos in that forum regularly.


5) Business directory listing websites

It is important o register your company in a business directry listing websites, because it will help to list your company in top of google ranks.

https://www.yelp.com

Hope after posting in all these sites you will get a better rank... best of luck :-)

Friday, 12 October 2012

SEARCH ENGINE OPTIMIZATION (SEO)


SEARCH ENGINE OPTIMIZATION (SEO)
...........................

SEO stands for “search engine optimization.” It is the process of getting traffic from the “free,” “organic,” “editorial” or “natural” listings on search engines. All major search engines such as Google, Yahoo and Bing have such results, where web pages and other content such as videos or local listings are shown and ranked based on what the search engine considers most relevant to users.

There are two types of SEO Ranking factors:-
1) ON THE PAGE SEO
2)OFF THE PAGE SEO


ON THE PAGE SEO
.....................

CONTENT
...........
QUALITY :Are pages well written & have substantial quality content?

RESEARCH:Have you researched the keywords people may use to find your content?

WORDS: Do pages use words & phrases you hope they'll be found for?

ENGAGE : Do visitors spend time reading or "bounce" away quickly?

FRESH: Are pages fresh & about "hot" topics?

HTML
...........

TITLES: Do HTML title tags contain keywords relevant to page topics?

DESCRIPTION:Do meta description tags describe what pages are about?

HEADERS:Do headlines and subheads use header tags with relevant keywords?

ARCHITECTURE
..............

CRAWL: Can search engines easily "crawl" pages on site?

SPEED: Does site load quickly?

URLS:Are URLs short & contain meaningful keywords to page topics?


OFF THE PAGE SEO
........................

LINKS
...........

QUALITY:Are links from trusted, quality or respected web sites?

TEXT:Do links pointing at pages use words you hope they'll be found for?

NUMBER:Do many links point at your web pages?

SOCIAL
........

REPUTATION: Do those respected on social networks share your content?

SHARES:Do many share your content on social networks?

TRUST
.............

AUTHORITY:Do links, shares & other factors make site a trusted authority?

HISTORY:Has site or its domain been around a long time, operating in same way?

PERSONAL
..............

COUNTRY:What country is someone located in?

LOCALITY:What city or local area is someone located in?

HISTORY:Does someone regularly visit the site? Or "liked" it?

SOCIAL:What do your friends think of the site?


SEO NEGATIVE FACTORS
.....................

VIOLATIONS
................

THIN : Is content "thin" or "shallow" & lacking substance?

STUFFING:Do you excessively use words you want pages to be found for?

HIDDEN:Do colors or design "hide" words you want pages to be found for?

CLOAKING:Do you show search engines different pages than humans?

PAID LINKS:Have you purchased links in hopes of better rankings?

LINK SPAM:Have you created many links by spamming blogs, forums or other places?


BLOCKING
................

Have many people blocked your site from search results?

Has someone blocked your site from their search results?



Friday, 5 October 2012

Sending Email in Codeigniter


Here iam describing about sending mail using smtp server in codeigniter.:- Below is the controller code:-


function Index()
    {
    $config = Array(
      'protocol' => 'smtp',
      'smtp_host' => 'ssl://smtp.googlemail.com',
      'smtp_port' => 465,
      'smtp_user' => 'youraccount@gmail.com',
      'smtp_pass' => 'password'
       
    );
     
    $this->load->library('email', $config);    //loading email libraray
    $this->email->set_newline("\r\n"); /* for some reason it is needed */
     
    $this->email->from('name@gmail.com', 'Aditya Lesmana Test');
    $this->email->to('name@gmail.com');
    $this->email->subject('This is an email test');
    $this->email->message('haai');
     
    if($this->email->send())
    {
      echo 'Your email was sent, success';
    }
    else
    {
      show_error($this->email->print_debugger());
    }
     
    }

Pagination in Codeigniter


CodeIgniter’s Pagination class is very easy to use, and it is 100% customizable, either dynamically or via stored preferences.
Here is a simple example showing how to create pagination in one of your controller functions:

In the Controller page, just code like this :-
public function news(){
$this->load->helper('form');
$this->load->helper('url');
$data['urls']=base_url();
$data['news'] = $this->news_model->get_news();
$data['count']=count($data['news']);

$this->load->library('pagination');// loading the pagination library
$config['base_url'] = $data['urls'].'index.php/admin/news/';// configuring url to which page is located
$config['total_rows'] = $data['count'];// total count of records fetched
$config['per_page'] = 10; //count wanted per page
$this->pagination->initialize($config);// initializing the configs 
$data['pagelinks']= $this->pagination->create_links();//creating links

$this->load->view('templates/headermain',$data);
$this->load->view('admin/news',$data);
$this->load->view('templates/footermain');

}

then you have to just place te below code in view page to display the pagination:-
  <?php  echo $pagelinks; ?> 
your pagination comes like this :-



Monday, 24 September 2012

Uploading multiple files in codeigniter

In this page Iam describing about uploading multiple images in codeigniter:-



public function uploadfiles(){
$this->load->helper('form');
$this->load->helper('url');
$data['urls']=base_url();
$this->load->view('templates/headermain',$data);
$this->load->view('admin/uploadfiles',$data);
$this->load->view('templates/footermain',$data);
$save=$this->input->post('saveForm');
if($save){
$error=0;
 $this->load->library('upload');  // NOTE: always load the library outside the loop

 /*Because here we are adding the "$_FILES['userfile']['name']" which increases the count, and for next loop it raises an exception, And also If we have different types of fileuploads */
 for($i=0;$i<count($_FILES);$i++)///loop through count
 {

   $_FILES['userfile']['name']    = $_FILES['filename'.$i]['name'];
   $_FILES['userfile']['type']    = $_FILES['filename'.$i]['type'];
   $_FILES['userfile']['tmp_name'] = $_FILES['filename'.$i]['tmp_name'];
   $_FILES['userfile']['error']       = $_FILES['filename'.$i]['error'];
   $_FILES['userfile']['size']    = $_FILES['filename'.$i]['size'];

   $config['file_name']     = 'test_'.$i;
   $config['upload_path'] = 'uploads/'; 
   $config['allowed_types'] = 'jpg|jpeg|gif|png';
$config['max_size'] = '1000'; 
$config['max_width'] = '1920'; 
$config['max_height'] = '1280';
   $config['overwrite']     = FALSE;

  $this->upload->initialize($config);

  if($this->upload->do_upload())
  {
    $error += 0;
  }else{
    $error += 1;
  }
 }

 if($error > 0){ echo "error"; }else{ echo "success"; }
}
}


Uploading image and generating thumbnail in Codeigniter

In this page Iam explaining how to upload image using codeigniter.
Before doing the code make sure that you created afolder named uploads in the rootfolder. and also a folder named thumbs inside this uploads folder.
So in the file uploading html page code should be like this:-

<?php echo form_open_multipart('admin/imageadd'); ?>
 <div class="row">
                            <div class="row150">
                                <h6>Image
                                <span class="req">*</span></h6>
                            </div>
                            <div class="row350">
                                <input type="file" name="userfile"  size="40" maxlength="90" tabindex="3" class="browse"/>
                            
                            </div>
                        </div>

<input name="saveForm" type="submit" value="." class="iconSave" />

                        
In the controller page code should be like this:-

public function imageadd(){
$save=$this->input->post('saveForm');
if($save){
$config['upload_path'] = 'uploads/'; 
$config['allowed_types'] = 'gif|jpg|jpeg|png'; 
$config['max_size'] = '1000'; 
$config['max_width'] = '1920'; 
$config['max_height'] = '1280';

$this->load->library('upload', $config); 
if(!$this->upload->do_upload()) 
$this->upload->display_errors(); 
else { 
$fInfo = $this->upload->data(); //uploading
  $this->gallery_path = realpath(APPPATH . '../uploads');//fetching path

$config1 = array(
      'source_image' => $fInfo['full_path'], //get original image
      'new_image' => $this->gallery_path.'/thumbs', //save as new image //need to create thumbs first
      'maintain_ratio' => true,
      'width' => 150,
      'height' => 100
       
    );
    $this->load->library('image_lib', $config1); //load library
    $this->image_lib->resize(); //generating thumb
}

$imagename=$fInfo['file_name'];// we will get image name here
}

After this if u look at the uploads folder you can see the image file there and its thubnail image inside the thumb folder...

Updating and deleting data in codeigniter

In this page iam describing about updating data in a codeigniter. Here iam explaining with the help of an example, so that you can understand it easily:-

UPDATING DATA

Usually there araise situation whereyou want to update the content added.
Generally we have to pass id of record from a record listing to a page to edit a particular record. In codeigniter we can do with built in function like this :-
 <?php echo anchor('admin/updatenews/' .$news_item['news_id'],"Update", array('title' => $ads_id = $news_item['news_id']));?>

so here id will be passed through the url:-
url wll be looking something like this:-
http://localhost/CodeIgniter/index.php/admin/updatenews/24

In codeigniter you can retrieve data like this:-
$newsid = $this->uri->segment(3);

you will get $newsid like this.


public function updatenews(){

$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$this->form_validation->set_rules('txtTitle', 'title', 'required');
$this->form_validation->set_rules('txtContent', 'content', 'required');
$data['urls']=base_url();
 $newsid = $this->uri->segment(3);
$news=$this->news_model->getnewsitem($newsid);//retreiving newsitem
$data['news']=$news;

$this->load->view('templates/headermain',$data);
$this->load->view('admin/updatenews',$data);
$this->load->view('templates/footermain',$data);
$save=$this->input->post('saveForm');
if($save){

$list=array('title'=>$title,'content'=>$content,'publish'=>$publish,'id'=>$newsid);//
$this->news_model->updatenews($list);//pasing as array to the model
redirect('admin/news',$data); 
}

so you have to write afunction in model like this :-


public function updatenews($list)

$dateup=date('Y-m-d H:i:s');
$data = array(
'published'=>$list['publish'],
'title' =>$list['title'],
'content' => $list['content'],
'date_update'=>$dateup
);

$this->db->where('news_id',$list['id']);
                   $this->db->update('news',$data); 
                   return 1;
}

and your update html view would be like:-

  <?php

$attributes=array('newsid'=>$news[0]['news_id']);
                      echo form_open_multipart('admin/updatenews',$attributes); ?>// here attributes can be passed like this




<h6>Title
                             </h6>
                          
                            <div class="row450">
                       Title:-      <input type="text" name="txtTitle"  size="40" maxlength="90" tabindex="2" value="<?php echo $news[0]['title']; ?>"  class="txtAdd_new">
                            </div>
content:-
<textarea name="txtContent" id="txtContent" rows="10" cols="40" tabindex="6"><?php echo $news[0]['content']; ?></textarea>


DELETING DATA

For deleting data you can use this function :-

 $this->db->where('news_id',$list[$i]);
                   $this->db->delete('news',$data); 





Listing data in codeigniter

In this page  , Iam describing about doing basic functions in codeigniter like listing data, inserting data, deleting data, updating data,uploading images,generating thumbnail of images.etc. If you are doing a simple project website in codeigniter this page will be useful for you.

Listing data
............................

Here iam describing an example of a news adding website. so in that project we will certainly have a page where all data will be listed. For details about where to add controller,model and view refer my previous page:- http://phpdudes.blogspot.in/2012/09/codeigniter-sample-project.html

First you have to write method in controller:-

public function news(){
$this->load->helper('form');
$this->load->helper('url');
$data['urls']=base_url();//basic root url
$data['news'] = $this->news_model->get_news();// retreive newslist from model
$data['count']=count($data['news']);
$this->load->view('templates/headermain',$data);//loading the header
$this->load->view('admin/news',$data);
$this->load->view('templates/footermain');//loading the footer

}
So you have a function named get_news in the news model:-


public function get_news()
{

$query = $this->db->get('news');
return $query->result_array();

}

So in the view page you have to code like this:-

  foreach($news as $news_item){
                   
                        ?>
                        <li>
                           <input type="hidden" name="id<?php echo $i;?>" value="<?php echo $news_item['news_id'];?>" />
            <div class="row250"><?php echo $news_item["title"];?></div>
<?php } ?>

Friday, 21 September 2012

CodeIgniter- A sample project

CodeIgniter is a toolkit for people who build web applications using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task. codeigniter is similar o cakephp which is another framework of php.

INSTALLATION
           
You can download codeigniter latest vesion from their site http://codeigniter.com/downloads/
after download you copy it to the wamp->www folder.

  • At first step, you have to configure database for the project.
  • You can configure database at pplications/config folder.

CONFIGURATION
       Just like most MVC frameworks, codeigniter also have model,view ,controller folders You can create corresponding models,views and controllers inside each  folder.

Here iam explaining to create a sample project in codeigniter.

SAMPLE PROJECT

In this project iam creating a news listing website.

create a database named news and create a table named news 


CREATE TABLE news (
id int(11) NOT NULL AUTO_INCREMENT,
title varchar(128) NOT NULL,
text text NOT NULL,
PRIMARY KEY (id),
KEY slug (slug)
);
change the default controller in routes.php like this

$route['default_controller'] = 'news/index';
$route['(:any)'] = 'news/index/$1';



First create a controller named news and save it as news.php inside controller folder.

<?php

class News extends CI_Controller {



public function __construct()// constuctor
{
parent::__construct();
$this->load->model('news_model');// load news_model at startup
}

public function index($page = 'index')
{
$data['news'] = $this->news_model->get_news();// function writen in model
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer', $data);

}

}
?>
Here we are loading three view files ,so we have to create them.

1) create a header.php named file and save it inside view folder in a folder named templates and paste folllowing code into it:-
<html>
<head>
<title>News listing</title>
</head>
<body>
<h1> News</h1>

2) create a footer.php named file and save it inside the view folder ina folder named templates and pate the following code into it:-
<strong>&copy; 2012</strong>
</body>
</html>

Thus we are successful in creating a layout for our files.

3) Next we have to create view file for news index. for this create a folder named news inside view folder. and then create a php file named index.php.

But before that we want to prepare a model for news,so that we can fetch data from the database.

create a model named news_model.php and save in the folder model.

<?php
class News_model extends CI_Model {

public function __construct()
{
$this->load->database();// loading the databse
}

public function get_news($title = FALSE)
{
if ($title === FALSE)
{
$query = $this->db->get('news');//getting all news
return $query->result_array();// returing array of data
}
$query = $this->db->get_where('news', array('title' => $title));// getting news with conditions
return $query->row_array();// returing array of data
}

}
?>

so now it's time to create index view for news.

<?php foreach ($news as $news_item): ?>

    <h2><?php echo $news_item['title'] ?></h2>
    <div id="main">
        <?php echo $news_item['text'] ?>
    </div>
    

<?php endforeach ?>

Here news will be fetched one byone...

For adding data to database
...................................................

Here iam explaining how to add data to databse using codeigniter.

first create html view as create.php in folder news inside view folder

<h2>Create a news item</h2>

<?php echo validation_errors(); ?>

<?php echo form_open('news/create') ?>

<label for="title">Title</label> 
<input type="input" name="title" /><br />

<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" /> 

</form>




create a function in contoller named create

public function create()
{
$this->load->helper('form');// helper library default of codeigniter
$this->load->library('form_validation');// helper library default of codeigniter
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');// we have to set criteria of each form elemen, it will evaluate automaticallly
$this->form_validation->set_rules('text', 'text', 'required');
if ($this->form_validation->run() === FALSE)// if valiadtion false then return error message
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
$this->load->view('news/success');// success message will be shown
}
}

Now  it's time to create model function

public function set_news()
{
$this->load->helper('url');

$data = array(
'title' => $this->input->post('title'),
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);// data will be inserted to database
}

Download from here:- https://github.com/litto/Codeigniter3-Sample-Project-with-CRUD

Tuesday, 18 September 2012

htaccess writing for websites


A .htaccess (hypertext access) file is a directory-level configuration file supported by several web servers, that allows for decentralized management of web server configuration.
The original purpose of .htaccess - reflected in its name - was to allow per-directory access control, by for example requiring a password to access the content. Nowadays however, the .htaccess files can override many other configuration settings including content type and character set, CGI handlers, etc.
These files are placed inside the web tree, and are able to override a subset of the server's global configuration for that directory, and all sub-directories.
With the help of htaccess we can even block users from different ip's.
Iam here describing some of the basic htaccess examples :-


1)Redirecting index.html to index.php

RewriteEngine On
RewriteRule index.html  index.php

Here index.html in url is redirected to index.php

2)Redirecting services-servicename-8.html to services.php?id=8

RewriteEngine On
RewriteRule services-([a-zA-Z0-9\-]+)-([0-9]+).html services.php?id=$2 [NC]

3)Redirecting services-8-servicename.html to services.php?id=8


RewriteEngine On
RewriteRule services-([0-9]+)-([a-zA-Z0-9\-]+).html services.php?id=$1 [NC]

Look at the examples of 2 and 3

In the 2nd rule is explained like :- if a url comes like services-any keywordname-number.html,then it shoul redirect to sevices.php?id=number in the second partition, because id is provided their.

In the 3rd rule is explained like :- if a url comes like services-idnumber-sevicename.html then it shoul redirect to services.pho?id=number in the first partition, because id is provided there.


if url is like  services-([a-zA-Z0-9\-]+)-([a-zA-Z0-9\-]+)-([0-9]+).html 

then redirecting url shoul be like services.php?id=$3 [NC]

$3-> because id is provided in the third partition

4) Redirecting a folder to another folder

RewriteEngine on
RewriteRule ^(.*)/category-old/(.*)$ $1/category-new/$2 [R,L] 
Here request for folder named category-old should redirect o category-new folder


Extracting Zip in purephp

When we are doing dynamic sites, their araise situation where we want to extract zipped files. so iam explaining here one way to extract zip files using corephp.
 for doing this first you have to ensure that your server has zip extension enabled. then if it is enabled simply follow the steps which iam explaining:-

1) First you have to include a zip library. here iam using pclzip library.
just download file from http://www.phpconcept.net/pclzip/pclzip-downloads



2)Now you have to include it in your zip uploading page like :-
include("pclzip.lib.php");

3) Uploading html code is similar to the image uploading itself
 <form action="theme-create.php" method="post" enctype="multipart/form-data">
 <div class="row">
                            <div class="row150">
                                <h6>Upload zip:
                                <span class="req">*</span></h6>
                            </div>
                            <div class="row350">
                                <input type="file" name="txtFile1"  size="40" maxlength="90" tabindex="3" class="browse"/>
                            
                            </div>
                        </div>
</form>

4) create a class named Uploader and copy below code to it 
<?php
/*
 * Date:8-16-2012
 * Login Form , entry to the application
 * Auhthor : Litto chacko
 * Email:littochackomp@gmail.com
*/
    class Uploader
    {
        private $destinationPath;
        private $errorMessage;
        private $extensions;
        private $allowAll;
        private $maxSize;
        private $uploadName;
private $seqnence;
        
        function __construct($path){
            $this->destinationPath  =   $path;
            $this->allowAll =   false;
        }
        
        function allowAllFormats(){
            $this->allowAll =   true;
        }
        
        function setMaxSize($sizeMB){
            $this->maxSize  =   $sizeMB * (1024*1024);
        }
        
        function setExtensions($options){
            $this->extensions   =   $options;
        }
        
function setSameFileName(){
$this->sameFileName = true;
$this->sameName = true;
}
        function getExtension($string){
            $ext = "";
            try{
                    $parts = explode(".",$string);
                    $ext = strtolower($parts[count($parts)-1]);
            }catch(Exception $c){
                    $ext = "";
            }
            return $ext;
}
        
        function setMessage($message){
            $this->errorMessage =   $message;
        }
        
        function getMessage(){
            return $this->errorMessage;
        }
        
        function getUploadName(){
            return $this->uploadName;
        }
        function setSequence($seq){
$this->imageSeq = $seq;
}
function sameName($true){
$this->sameName = $true;
}
        function uploadFile($fileBrowse){
            $result =   false;
            $size   =   $_FILES[$fileBrowse]["size"];
            $name   =   $_FILES[$fileBrowse]["name"];
            $ext    =   $this->getExtension($name);
            if(!is_dir($this->destinationPath)){
                $this->setMessage("Destination folder is not a directory ");
            }else if(!is_writable($this->destinationPath)){
                $this->setMessage("Destination is not writable !");
            }else if(empty($name)){
                $this->setMessage("File not selected ");
            }else if($size>$this->maxSize){
                $this->setMessage("Too large file !");
            }else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){
                $util   =   new Utilities();
if($this->sameName==false){
                $this->uploadName   =  $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$util->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
                }else{
$this->uploadName= $name;
}
                if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
                    $result =   true;
                }else{
                    $this->setMessage("Upload failed , try later !");
                }
            }else{
                $this->setMessage("Invalid file format !");
            }
            return $result;
        }
        
        function deleteUploaded(){
            unlink($this->destinationPath.$this->uploadName);
        }
        
    }

?>


5) So in the action side you have to do code like this... create afolder named themes in the same folder.. so that extracted files will be extracted to this folder

          $uploader   =   new Uploader($absDirName.'/');//object of uploader
            $uploader->setExtensions(array('zip'));
            $uploader->setSequence('theme');
            $uploader->setMaxSize(10);
            if($uploader->uploadFile("txtFile1")){
        
                 $image1     =   $uploader->getUploadName(); 
                
            } 
    

$file_to_open=$absDirName.'/'.$image1;
$zip = new PclZip($file_to_open);// creating object of pclzip
$target="/themes/";
$unique_folder="theme";
chmod($target.'/'.$txtTitle,0777);//changing permission of folder to writable
if ($zip->extract(PCLZIP_OPT_PATH, $target) == 0) {//extracting zip files
   $message    =   new Message('problem in extracting files','error');
            $message->setMessage();
              header('Location:themes.php');
            exit;
6) Now zip file will be extracted

Thursday, 28 June 2012

Captcha in simple php


When we build websites with forms their emerge situation where we want to include captcha to prevent it from spammers. here iam including a captcha file which can be used in simple php:-
create a catptcha.php and include the following code in this:-
<?php

session_start();
$text = rand(10000,99999);
$_SESSION["vercode"] = $text;
$height = 25;
$width = 65;

$image_p = imagecreate($width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);
$font_size = 14;

imagestring($image_p, $font_size, 5, 5, $text, $white);
imagejpeg($image_p, null, 80);
?>
and now for calling this capcha in your website call like this:-
<img src="captcha.php" alt="captchaimage">

and now for getting value of this captcha to check get the value by this:-
$text=$_SESSION["vercode"] ;
unset($_SESSION["vercode"]);
and now get the captcha entered by user by
$captcha        = $_POST['captcha'];

now check the values and do validation.

Captcha in cakephp



When we build websites with forms their emerge situatiion where we want to include captcha to prevent it from spammers. here iam including a captcha controller which can be used in cakephp.
<?php

class CaptchaController extends AppController{

public $uses = array('SessionManager','Validator','Captcha','Flash');
public $components=array('Session');

function init(){
$this->SessionManager->Session=$this->Session;
}
function index(){
$this->init();
/*
$text = $this->SessionManager->get('captchaText');
$height = 25;
$width = 65;

$image_p = imagecreate($width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);
$font_size = 14;
ob_start();
imagestring($image_p, $font_size, 5, 5, $text, $white);
imagejpeg($image_p, null, 80);
exit;*/

$urlRoot=Router::url('/',false);
$image_width = 120;
$image_height = 35;
$characters_on_image = 6;
$dir = Configure::read('FondDir');
$font = $dir.'/monofont.ttf';
$possible_letters = '23456789bcdfghjkmnpqrstvwxyz';
$random_dots = 0;
$random_lines = 20;
$captcha_text_color="0x142864";
$captcha_noice_color = "0x142864";
$code = '';
$i = 0;
ob_start();
while ($i < $characters_on_image) {
$code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
$i++;
}
$this->SessionManager->set('captcha',$code);
$this->Session->write('captcha',$code);
$font_size = $image_height * 0.75;
$image      = @imagecreate($image_width, $image_height);


/* setting the background, text and noise colours here */
$background_color = imagecolorallocate($image, 255, 255, 255);

$arr_text_color = $this->hexrgb($captcha_text_color);
$text_color = imagecolorallocate($image, $arr_text_color['red'],
$arr_text_color['green'], $arr_text_color['blue']);

$arr_noice_color = $this->hexrgb($captcha_noice_color);
$image_noise_color = imagecolorallocate($image, $arr_noice_color['red'],
$arr_noice_color['green'], $arr_noice_color['blue']);


/* generating the dots randomly in background */
for( $i=0; $i<$random_dots; $i++ ) {
imagefilledellipse($image, mt_rand(0,$image_width),
mt_rand(0,$image_height), 2, 3, $image_noise_color);
}


/* generating lines randomly in background of image */
for( $i=0; $i<$random_lines; $i++ ) {
imageline($image, mt_rand(0,$image_width), mt_rand(0,$image_height),
mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}


/* create a text box and add 6 letters code in it */
$textbox = imagettfbbox($font_size, 0, $font, $code);
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code);


/* Show captcha image in the page html page */
header('Content-Type: image/jpeg');// defining the image type to be shown in browser widow
imagejpeg($image);//showing the image
imagedestroy($image);//destroying the image instance


exit;
}

function hexrgb ($hexstr)
{
 $int = hexdec($hexstr);

 return array("red" => 0xFF & ($int >> 0x10),
  "green" => 0xFF & ($int >> 0x8),
  "blue" => 0xFF & $int);
}


}

?>
and after including this in your controller page .. so after that you have to call captchja somewhere so you can call like this
img src="<?php echo  $urlRoot;?>captcha/" alt="Captcha Security Code" class="captcha" />


and in the action file where you want to get this value,simply call like this
$captcha = $this->SessionManager->get('captcha');

and you can check the captcha value with the user entered captcha value and can submit the form..

Inserting images from customized usergallery in tinymiceeditor


when developing a large web interface site, there araise situation where we had to use certain text editors in our forms. generally when our project is something like blogs, we have to insert images from user gallery itself. but in tiny mice editor it doesn't have feautre for adding images from our customized gallery by default. there is lot of plugins available for doing this in tiny miceeditor,but it is costly. so we have to include it by externally. so here iam explaining of including an image inserter for tinymice editor in cakephp. first you downlad the tiny mice editor from their site and include in your  app/webroot/js folder. then create a form like this:-

<a href="javascript:void(0)" id="imageButton" class="imageButton" onclick="return openGallery(this);">INSERT IMAGE</a>
<div class="col150">Content:- <span class="required">*</span></div>
<div class="col30 txtCenter">:</div></div>
<div class="rows"><textarea name="postcontent" tabindex="6" maxlength="90" id="postcontent">
</textarea></div>

please include the following js code under your form:-
<script type="text/javascript">
var urlRoot='<?php echo $urlRoot;  ?>';
function openGallery(obj){// this is the function called by the insert image link

contentBox(obj);// sets the content box
showImages(1); // calls the function show images
return false;
}

function contentBox(obj){

var id = obj.id;
var it = $('#'+id);
var pos = it.position();
if($("#editLayerBox")){
$("#editLayerBox").remove();
}
var div='';
var elim = 'editLayerBox';
div='<div id="editLayerBox" class="editLayerBox"></div>';
$(document.body).append(div);
//$("#"+elim).css("position","fixed");
var left=Number(pos.left)-140;
var top = Number(pos.top)-500;
    $("#"+elim).css("top", pos.top+'px');
    $("#"+elim).css("left",left+'px');
$("#"+elim).html('Loading');
}
function showImages(start){// it calls an action written in the userreg controller called image gallery.this function will be explained later

$.post(urlRoot+'userreg/imagegallery/',{start:start},function(data){
$("#editLayerBox").html(data);
});
}
function insertImage(){// function to insert image to the tiny mce editor
var width = $('#imgWidth').val();
var height = $('#imgHeight').val();
var image = $('#imgSelected').val();
var path = $('#imgPath').val();

if(image==''){
alert("You did't select any picture !");
}else{
var html='<img src="'+path+''+image+'"  width="'+width+'" height="'+height+'" class="innerImageFile"  />';

tinyMCE.execCommand('mceInsertContent',false,html);
closeEditBox();
}
}
function fillSize(w,h,id,t){// setting the file sizesand image selected
$('#imgWidth').val(w);
$('#imgHeight').val(h);

$('#imgSelected').val(id);
}
function closeEditBox(){// closing the edit box
if($("#editLayerBox")){
$("#editLayerBox").remove();
}
return false;
}
</script>

Here you see that some classes are called in js function .don't forget to include those styles in css. because the image should be displayed in a popup box and it completely depends on tghe css you include. just add these lines to css:-
.editLayerBox{ width:680px; height:auto;background:#FFFFFF; position:absolute; left:0px; top:0px; text-align:center;}
.layerOuter{ height:auto; overflow:hidden; border:1px solid #999999; padding:5px; text-align:left;}
.layerOuter .topRow{  height:24px; line-height:24px ; border:1px solid #f0f0f0; border-top:0px; padding:2px;}
.layerOuter .topRow .close{ border:0px; width:20px; height:20px; background:url(../img/close.jpg) no-repeat; float:right; border:1px solid #f0f0f0;}
.layerOuter .contBox{ height:auto; overflow:hidden; margin:2px 0px; padding:5px; border:1px solid #f0f0f0;}
.editorHelper{ height:25px;padding:3px 0px; border:1px dotted #e0e0e0; background:#FFFFFF;}
.editorHelper .imageButton{ height:24px; line-height:24px; padding-left:30px; float:left; font-weight:500; background:url(../img/icon-gallery.jpg) no-repeat #FFFFFF; margin-left:10px; border:1px dotted #e0e0e0;}
.editorHelper .linkButton{ height:24px; line-height:24px; padding-left:30px; float:left; font-weight:500; background:url(../img/icon-links.jpg) no-repeat #FFFFFF; margin-left:10px;}
.editorHelper a{ color:#FF0000; font-weight:600; border:1px dotted #e0e0e0; padding:0px 10px


now it's time to talk about the action and view fo the image displaying. just include this code in your usercontroller and customize the path as you required. here is the imagegallery action in usercontroller:-
function imagegallery(){
$this->init();
$this->layout='layer';
$data = $this->data;
$page = $data['start'];



$this->set('userid',$user_id);
$urlRoot=Router::url('/',false);
$this->set('urlRoot',$urlRoot);
$limit = 10;
$order = 'Image.image_id ASC';
$cond = array('Album.user_id'=>$user_id);
$this->Image->belongsTo=array('Album'=>array('className'=>'Album','foreignKey'=>'album_id'));
$total = $this->Image->find('count',array('conditions'=>$cond));
$records = $this->Image->find('all',array('conditions'=>$cond,'order'=>$order,'page'=>$page,'limit'=>$limit));

$cnt = ceil($total/$limit);
$pages = $this->Pages->getPages($page,$cnt,$limit);
$next = $this->Pages->getNext($page,$cnt,$limit);
$prev = $this->Pages->getPrev($page,$cnt,$limit);
$first = $this->Pages->getFirst($page,$cnt,$limit);
$last = $this->Pages->getLast($page,$cnt,$limit);
$uploadDir =WWW_APP_MAIN_ROOT.'/store/';
         $uploadDir.='user-'.$user_id.'/gallery/';//here you have to set the path of file
         $this->set('filepath',$uploadDir);
          $uploadDir1 =$url.'/store/';
         $uploadDir1.='user-'.$user_id.'/gallery/';
         $this->set('filepath2',$uploadDir1);

$mediaBaseDir = Configure::read('Albumdir');
$uploadDir=$mediaBaseDir;

$this->set('pages',$pages);
$this->set('first',$first);
$this->set('last',$last);
$this->set('next',$next);
$this->set('prev',$prev);
$this->set('page',$page);
$this->set('limit',$limit);
$this->set('total',$total);
$this->set('records',$records);
$this->set('util',$this->Utility);
$this->set('rootUrl',$this->rootUrl);
$this->set('uploadDir',$uploadDir);
}
next is the view file . here include this code in your imagegallery.ctp
<?php
 $rootUrl=Router::url('/',false);
 $filepath1='http://'.$_SERVER['SERVER_NAME'].$filepath2;
?>
<div class="rows">

<ul class="imagesLayer">

<?php


for($i=0;$i<count($records);$i++){

$imageSize = getimagesize($filepath.$records[$i]['Image']['imagename']);
$w = $imageSize[0];
$h = $imageSize[1];

?>
<li>
<div class="row1">
<img src="<?php echo $urlRoot;?>thumb2/album/?uid=<?php echo $userid;?>&img=<?php echo $records[$i]['Image']['imagename'];?>&width=140&height=100"  alt="THUMB" title="" />
</div>
<div class="row2">
<input type="radio" name="radImage" value="<?php echo $records[$i]['Image']['imagename'];?>" onclick="fillSize('<?php echo $w;?>','<?php echo $h;?>','<?php echo $records[$i]['Image']['imagename'];?>','<?php echo addslashes(htmlentities($records[$i]['Image']['imagename']));?>')" /> SELECT IMAGE
</div>

</li>
<?php
}
?>
</ul>
<?php
if($total>0){
?>
<div class="rows imgSelectionRow">
Width <input type="text" size="10" id="imgWidth" value="120" />
Height <input type="text" size="10" id="imgHeight" value="120" />
<input type="button" name="imgAdd" class="button" value="ADD IMAGE" onclick="insertImage();" />
<input type="hidden" name="imgSelected" id="imgSelected" value="" />
<input type="hidden" name="imgPath" id="imgPath" value="<?php echo $filepath1;?>" />
</div>

<ul class="pagination">
<li>
<a href="javascript:void();" onclick="return showImages('<?php echo $first;?>')">First</a>
<a href="javascript:void();" onclick="return showImages('<?php echo $prev;?>')">Prev</a>
<?php
for($i=0;$i<count($pages);$i++){

?>
<a href="javascript:void();" onclick="return showImages('<?php echo $pages[$i]?>')" <?php if($page==$pages[$i]){?> class="visited"<?php }?>><?php echo $pages[$i]?></a>
<?php
}
?>
<a href="javascript:void();" onclick="return showImages('<?php echo $next;?>')">Next</a>
<a href="javascript:void();" onclick="return showImages('<?php echo $last;?>')">Last</a>
</li>
<li>
Total : <?php echo $total;?> records
</li>
</ul>
<?php } else{
?>
<span class="required">Sorry no records found !</span>
<?php
}?>
</div>
Hope you suceed in it.................