Wednesday 19 June 2013

Example code - CakePHP

CAKEPHP FOLDER STRUCTURE

After you've downloaded and extracted CakePHP, these are the files and folders you should see:

  • app
  • cake
  • vendors
  • plugins
  • .htaccess
  • index.php
  • README

You'll notice three main folders:

  • The app folder will be where you work your magic: it’s where your application’s files will be placed.
  • The cake folder is where we’ve worked our magic. Make a personal commitment not to edit files in this folder. We can’t help you if you’ve modified the core.
  • Finally, the vendors folder is where you’ll place third-party PHP libraries you need to use with your CakePHP applications.

The App Folder

CakePHP’s app folder is where you will do most of your application development. Let’s look a little closer at the folders inside of app.
config
Holds the (few) configuration files CakePHP uses. Database connection details, bootstrapping, core configuration files and more should be stored here.
controllers
Contains your application’s controllers and their components.
libs
Contains 1st party libraries that do not come from 3rd parties or external vendors. This allows you to separate your organization's internal libraries from vendor libraries.
locale
Stores string files for internationalization.
models
Contains your application’s models, behaviors, and datasources.
plugins
Contains plugin packages.
tmp
This is where CakePHP stores temporary data. The actual data it stores depends on how you have CakePHP configured, but this folder is usually used to store model descriptions, logs, and sometimes session information.
Make sure that this folder exists and that it is writable, otherwise the performance of your application will be severely impacted. In debug mode, CakePHP will warn you if it is not the case.
vendors
Any third-party classes or libraries should be placed here. Doing so makes them easy to access using the App::import('vendor', 'name') function. Keen observers will note that this seems redundant, as there is also a vendors folder at the top level of our directory structure. We'll get into the differences between the two when we discuss managing multiple applications and more complex system setups.
views
Presentational files are placed here: elements, error pages, helpers, layouts, and view files.
webroot
In a production setup, this folder should serve as the document root for your application. Folders here also serve as holding places for CSS stylesheets, images, and JavaScript files.


REQUIREMENTS

 HTTP Server. For example: Apache. mod_rewrite is preferred, but by no means required.
  • PHP 4.3.2 or greater. Yes, CakePHP works great on PHP 4 and 5.
  • Technically a database engine isn’t required, but we imagine that most applications will utilize one. CakePHP supports a variety of database storage engines:
  • MySQL (4 or greater)
  • PostgreSQL
  • Microsoft SQL Server
  • Oracle
  • SQLite

CORE COMPONENTS

CakePHP has a number of built-in components. They provide out of the box functionality for several commonly used tasks.
The Acl component provides an easy to use interface for database and ini based access control lists.
The auth component provides an easy to use authentication system using a variety of authentication processes, such as controller callbacks, Acl, or Object callbacks.
The cookie component behaves in a similar fashion to the SessionComponent in that it provides a wrapper for PHP's native cookie support.
An interface that can be used to send emails using one of several mail transfer agents including php's mail() and smtp.
The request handler allows you to introspect further into the requests of your visitors and inform your application about the content types and requested information.
The security component allows you to set tighter security and use and manage HTTP authentication.
The session component provides a storage independent wrapper to PHP's sessions.
To learn more about each component see the menu on the left, or learn more about creating your own components.
All core components now can be configured in the $components array of a controller.

Step1:   Under the appà configàcore.php file set according to the


A random string used in security hashing methods.
 *///praveen.. url get from https://www.grc.com/passwords.htm----------------------------------------------------->
            Configure::write('Security.salt', 'LwjZfapqsfxkDpCBstGObx6fGnOU5BrQ9ghxjOuRkdYUtpo1MOIcN5JXZo7FLhB');

/**
 * A random numeric string (digits only) used to encrypt/decrypt strings.
 */
            Configure::write('Security.cipherSeed', '123456789');

/**
 * Apply timestamps with the last modified time to static assets (js, css, images).
 * Will append a querystring parameter containing the time the file was modified. This is
 * useful for invalidating browser caches.

Step2:   Under the appà configàdatabase.php  file set the data according to your already created base

class DATABASE_CONFIG {

            public $default = array(
                   'datasource' => 'Database/Mysql',
                   'persistent' => false,
                   'host' => 'localhost',
                   'login' => 'root',
                   'password' => '',
                   'database' => 'cackeDB1',
                   'prefix' => '',
                   //'encoding' => 'utf8',
          );

            public $test = array(
                        'datasource' => 'Database/Mysql',
                        'persistent' => false,
                        'host' => 'localhost',
                        'login' => 'user',
                        'password' => 'password',
                        'database' => 'test_database_name',
                        'prefix' => '',
                        //'encoding' => 'utf8',
            );
}
Step 3:
1)Under the Model folder  you should create tudent.php file


<?php
Class tudent extends AppModel
{
var $name='tudent';
// tudents is table name but here used only tudent singular word of table
public  $validate=array
(
'name'=>array(
'name_must_not_be_blanck'=>array('rules'=>'not empty','message'=>' begins with capital letter'),
'name_must_be_unique'=>array('rule'=>'must unique',
'message'=>'this name already existst'
)
),
'address'=>array(
'body_must_not_be_blank'=>array(
'rules'=>'not empty',
'message'=>' begins with capital letter'
)
)
);
/*
public $validate=array
('name'=>array(
'rule'=>'notEmpty'),
'address'=>array(
'rule'=>'notEmpty'),
'mark'=>array(
'rule'=>'notEmpty')
);*/
}
/*class Employee extends AppModel
{
public $name='employee';*/
?>

Step 4:
2) you shoul create under the controller folder…tudentsController.php file


<?php

Class tudentsController extends AppController{
 var $name='tudents';


public function index()
{
$this->set('a',$this->tudent->find('all'));
}


public function hello()
{

}


//--------------
public function add()
 {
        if($this->request->is('post'))
 {
    if($this->tudent->save($this->request->data))
    {
      $this->Session->setFlash('Your post has been saved');
       $this->redirect(array('action'=>'index'));
     }}
 else
    {
    $this->Session->setFlash('Unable to add your post');
    }
 }


public function edit($id=null)
{$this->tudent->id=$id;
if($this->request->is('get'))
    {
    $this->request->data=$this->tudent->read();
     }
else 
      {if($this->tudent->save($this->request->data))
                
                              {$this->Session->setFlash('your post has been updated');
                                      $this->redirect(array('action'=>'index'));
                              }
else
          {$this->Session->setFlash('Unable to update your post');
          }                                     
       }  
             
}



public function del($id=NULL)
{
$this->tudent->delete($id);
$this->Session->setFlash('The post with id :'.$id.'has been deleted.');
 $this->redirect(array('action'=>index));

/*if($this->request->is('get'))
  {
  throw new MethodNotAllowedException();
 
   }
   if($this->tudent->delete($id))
   {$this->Session->setFlash('The post with id :'.$id.'has been deleted.');
   $this->redirect(array('action'=>index));
   }*/
}
//---------------

 public function           find()
{
$this->set('a',$this->Employee->find('all'));
}
           



}
?>
Step 5:
3) under the view you should create all controller files


3.1) first create index.ctp file




<p><h1>hai praveen </h1>
<br>
<p>
<marquee >welcome to php </marquee>
<table>
<tr>
<!--<th>id</th>--!>
<th> name</th>
<th>address</th>
<th>Mark</th>
<th> Your Action</th>
</tr>

<?php foreach($a as $b) {?>
<tr>

<!--<td>
<?php// echo  $b['tudent'] ['id'] ;?>
</td>--!>

<td>
<?php echo $b['tudent'] ['name']; ?>
</td>

<td>
<?php echo $b['tudent'] ['address']; ?>
</td>

<td>
<?php echo $b['tudent'] ['mark']; ?>
</td>

<td>
<?php echo $this->Html->link( 'Edit' ,array('controller'=>'tudents','action'=>'edit',$b['tudent']['id'])); ?>
</td>

<td>
<?php echo $this->Html->link( 'Delete' ,array('controller'=>'tudents','action'=>'del',$b['tudent']['id']),NULL,'Are you shure you want to delete the data'); ?>
</td>
</tr>
<?php
}
?>
<tr>
<td>
<?php echo $this->Html->link($b['tudent'] ['name'],array('controller'=>'tudents','action'=>'hello',$b['tudent']['id'])); ?>
</td>
<td>
<?php echo $this->Html->link('ADD DATA',array('controller'=>'tudents','action'=>'add',$b['tudent']['id'])); ?>
</td>
<td>
<?php echo $this->Html->link('EDIT DATA',array('controller'=>'tudents','action'=>'edit',$b['tudent']['id'])); ?>
</td>

</tr>
</table>

3.2)second you should create  hello.ctp file

<h3> hello world</h3>
<p>welcome to MVC praveen............</p>

<?php echo $this->Html->link('back',array('controller'=>'tudents','action'=>'index')); ?>

3.3) you should create third ctp file named as add.ctp
<tr>
<td>
<h1>Add employ </h1>
</td>
</tr>
<?php
echo $this->Form->create('tudent',array('action'=>'add'));
echo $this->Form->input('name');
echo $this->Form->input('address',array('rows'=>'1'));
echo $this->Form->input('mark');
echo $this->Form->end('Save Employee');
?>
<br>
<?php echo $this->Html->link('back',array('controller'=>'tudents','action'=>'index')); ?>

3.4) edit.ctp



<h1>Edit post</h1>
<?php
 echo $this->Form->create('tudent',array('action'=>'edit'));
 echo $this->Form->input('name');
 echo $this->Form->input('address');
 echo $this->Form->input('mark');
 echo $this->Form->input('id',array('type'=>'hidden'));
 echo $this->Form->end('Save post');
 ?>

3.5)del.ctp

<?php
 echo $this->Form->create('tudent',array('action'=>'del'));
 echo $this->Form->input('name');
 echo $this->Form->input('address');
 echo $this->Form->input('mark');
 echo $this->Form->input('id',array('type'=>'hidden'));
 echo $this->Form->end('Save post');
 ?>

3.6) find.ctp

<?php
 echo $this->Form->create('tudent',array('action'=>'find'));
 echo $this->Form->input('name');
 echo $this->Form->input('address');
 echo $this->Form->input('mark');
 echo $this->Form->input('id',array('type'=>'hidden'));
 echo $this->Form->end('Save post');
 ?>

Step 6: RUN
Browse url: http://localhost:81/cackephp1/tudents/
http://localhost:81/cackephp1/tudents/hello

WHAT IS CAKEPHP? and Benefits?

CakePHP is a free, open-source, rapid development framework for PHP. It’s a foundational structure for programmers to create web applications. Our primary goal is to enable you to work in a structured and rapid manner–without loss of flexibility.
CakePHP takes the monotony out of web development. We provide you with all the tools you need to get started coding what you really need to get done: the logic specific to your application. Instead of reinventing the wheel every time you sit down to a new project, check out a copy of CakePHP and get started with the real guts of your application.
CakePHP has an active developer team and community, bringing great value to the project. In addition to keeping you from wheel-reinventing, using CakePHP means your application’s core is well tested and is being constantly improved.
Here’s a quick list of features you’ll enjoy when using CakePHP:
  Active, friendly community
Flexible licensing
Compatible with versions 4 and 5 of PHP
Integrated CRUD for database interaction
Application scaffolding
Code generation
MVC architecture
Request dispatcher with clean, custom URLs and routes
Built-in validation
Fast and flexible templating (PHP syntax, with helpers)
View Helpers for AJAX, JavaScript, HTML Forms and more
Email, Cookie, Security, Session, and Request Handling Components
Flexible ACL
Data Sanitization
Flexible Caching
Localization
Works from any web site directory, with little to no Apache configuration involved

Benefits

Why use MVC? Because it is a tried and true software design pattern that turns an application into a maintainable, modular, rapidly developed package. Crafting application tasks into separate models, views, and controllers makes your application very light on its feet. New features are easily added, and new faces on old features are a snap. The modular and separate design also allows developers and designers to work simultaneously, including the ability to rapidly prototype. Separation also allows developers to make changes in one part of the application without affecting others.
If you've never built an application this way, it takes some time getting used to, but we're confident that once you've built your first application using CakePHP, you won't want to do it any other way.

Wednesday 5 June 2013

API integration in php - Domain Check Availability and Suggestions Using Reseller club API

Checks the availability of the specified domain name(s).

Parameters


NameData TypeRequired / OptionalDescription
auth-useridIntegerRequired
auth-userid: Your Live Account Reseller Id
(See the instructions below for finding your
Reseller Id).
api-key (or) auth-passwordStringRequiredapi-key: An alphanumeric code that can be 
used to authenticate your API calls (See the 
instructions below for finding your API Key),
(OR)
auth-password: The password you use to 
login to your Live Account's Reseller Control 
Panel.
domain-nameArray of StringsRequiredDomain name(s) that you need to check the
availability for.
tldsArray of StringsRequiredTLDs for which the domain name availability
needs to be checked.
suggest-alternativeBooleanOptionalPass true if domain name suggestions are
required. Default value is false.

Locating your Reseller IdTop

  1. Login to your Reseller Control Panel. 1
  2. Click the  icon at the top right corner of the page and then click Manage Profile.
  3. In the Reseller Profile Details view that is now displayed, the first field indicates your Reseller Id.

Locating your API KeyTop

  1. Login to your Reseller Control Panel. 2
  2. In the Menu, point to Settings and then click API.
  3. Your unique API Key will be listed under the API Key section.
    You may generate a fresh API Key by clicking the  icon and then confirming Key regeneration.

Example Test URL RequestTop

https://test.httpapi.com/api/domains/available.json?auth-userid=0&api-key=key&domain-name=domain1&domain-name=domain2&tlds=com&tlds=net

ResponseTop

Returns a hash map containing domain name availability status for the requested TLDs:

Available - domain name available for registration

Regthroughus - domain name currently registered through the Registrar whose connection is being used to check the availability of the domain name


Regthroughothers - domain name currently registered through a Registrar other than the one whose connection is being used to check the availability of the domain name. If you wish to manage such a domain name through your Reseller / Registrar Account, you may pass a Domain Transfer API call. 1


Unknown - returned, if for some reason, the Registry connections are not available. You should ideally re-check the domain name availability after some time.

Example: File Name : checkdomain.php

<?php

$api_user_id="Your user id";
$api_key="key";


function domainCallAPI($method, $url, $data = false) {
    $curl = curl_init();

    switch ($method) {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // Optional Authentication: - Need not touch this
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($curl, CURLOPT_USERPWD, "username:password");
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    return curl_exec($curl);
}
?>

<?php
//Example Call to see available domains and suggestions
$url = '';
$tldarray[] = "";
$domainname="";
if (isset($_POST['check']) && isset($_POST['domain']) && $_POST['domain'] != "" && isset($_POST['tld']) && $_POST['tld'] != "") {

    $domainname = $_POST['domain'];
    $tld = "";
    $i = 0;
    foreach ($_POST['tld'] as $arrayitem) {
        $tld.='&tlds=' . $arrayitem;
        $tldarray[$i] = $arrayitem;
        $i++;
    }

// $api_user_id and  $api_key are initialized in config file or directly in in this page
    $url = 'https://test.httpapi.com/api/domains/available.json?auth-userid=' . $api_user_id . '&api-key=' . $api_key . '&domain-name=' . $domainname . $tld . '&suggest-alternative=true';
    $data = "";
    $data = domainCallAPI('GET', $url, $data);
    $datajson = json_decode($data, TRUE);
    $fulldomainname = "";
    //  $flag=0;
    foreach ($tldarray as $arrayitem) {

        $fulldomainname = $domainname . "." . $arrayitem;
        echo '<br/>' . $fulldomainname;
        if ($datajson[$fulldomainname]["status"] == "available") {
            echo '    Available';
            // $flag=1;
        } else {
            echo '    Not Available <br/>';
        }
    }
    // Domain Suggestions
    $stack = array("");
    $i = 0;
    foreach ($datajson[$domainname] as $sugdomain => $sugtld) {
        // echo $sugdomain.'.'.$tld;

        $stack[$i] = $sugdomain;
        $i++;
    }
    echo '<br/>Sugg names : <br/>';
    $i = 0;
    foreach ($stack as $value) {
        foreach ($datajson[$domainname][$value] as $sugdomain => $sugtld) {
            if ($datajson[$domainname][$value][$sugdomain] == "available") {
                echo $value . '.' . $sugdomain;
                echo '<br/>';
                $i++;
                if ($i == 7) {

                    break;
                }
            }
        }

        if ($i == 7) {

            break;
        }
    }
    // domain suggestions end
}
 elseif (isset($_POST['check'])){
 
    if(!isset($_POST['tld'])){
      echo '<br/> Tick Your Domain';
 
    }
     if( !isset($_POST['domain']) || $_POST['domain'] =="" ){
        echo '<br/> Type Domain Name';  
    }else{
        $domainname=$_POST['domain'];
    }

}

?>

<form method="post" action="checkdomain.php">
    <input type="text" name="domain" value="<?php echo $domainname; ?>"/>

    <input type="checkbox" name="tld[]" value="com"  <?php  if(!isset($_POST['check'])){  ?> checked="checked" <?php } elseif (in_array("com", $tldarray)) {  ?> checked="checked" <?php  } ?> />com
    <input type="checkbox" name="tld[]" value="net" <?php if (in_array("net", $tldarray)) {  ?> checked="checked" <?php  } ?> />net
    <input type="checkbox" name="tld[]" value="in" <?php if (in_array("in", $tldarray)) {  ?> checked="checked" <?php  } ?> />in
    <input type="checkbox" name="tld[]" value="biz" <?php if (in_array("biz", $tldarray)) {  ?> checked="checked" <?php  } ?> />biz
    <input type="checkbox" name="tld[]" value="org" <?php if (in_array("org", $tldarray)) {  ?> checked="checked" <?php  } ?> />org
    <input type="checkbox" name="tld[]" value="asia" <?php if (in_array("asia", $tldarray)) {  ?> checked="checked" <?php  } ?> />asia


    <input type="submit" name="check" value="Check"/>
</form> 

I hope all goes well! Look forward to seeing more post from me in the future.

Simple CRUD in Laravel Framework

Creating, reading, updating, and deleting resources is used in pretty much every application. Laravel helps make the process easy using re...