Archive for the ‘ php ’ Category

Installing CakePHP on Ubuntu

CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications. Using commonly known design patterns like MVC and ORM within the convention over configuration paradigm, CakePHP reduces development costs and helps developers write less code.

Installation is actually quite an easy task. But I couldn’t find good information at the beginning. So here I am writing for you. I am using Ubuntu 9.10. This will work for any *nix systems.


Step 1:

In order to work with cakephp you need to have Apache server , MySql Database and PHP. To get them

sudo apt-get install apache2 mysql-server php5


Step 2:

Download the Latest version or the stable version of Cakephp. You can get it from here download
I am using 1.2 version of cakephp


Step 3:

Copy and Extract the compressed file to the webroot(/var/www) and rename to cakephp or some project_name. Open http://localhost/cakephp in your browser. You will see something like this.

cakephp installation step3cakephp installation step3


Step 4:

Enable write permission for app/temp
sudo chmod -R 777 cakephp/app/tmp


Step 5:

Enable mod_rewrite. More about mod_rewrite here.

sudo a2enmod rewrite


Step 6:

Edit the file /etc/apache2/sites-enabled/000-default and change AllowOverride None to AllowOverride All. You can use any text editor. I am using vi editor.

sudo vi /etc/apache2/sites-enabled/000-default

<Directory /var/www>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>


Step 7:

Changing the value of security.salt in app/config/core.php. At line 151 or near to it you can see something like this
Configure::write(‘Security.salt’, ‘DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi’);

Just change the value of it.I have come up with this value
Configure::write(‘Security.salt’, ‘UubWwvniR2G0FgaC9miDYhG93b0qyJfIxfs2guVo’);


Step 8:

Database Configuration. The database configuration file is located at cakephp/app/config/database.php.default
change the file name to database.php
sudo mv database.php.default database.php

Then edit the following

sudo vi cakephp/app/config/database.php

class DATABASE_CONFIG {

var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => 'sudeep',
'database' => 'cakephp',
'prefix' => '',
);

You can connect to any database you want. Make sure that username and password of your database are correct.


Step 9:

Restart Apache server to see changes
sudo /etc/init.d/apache2 restart


Step 10:

Open http://localhost/cakephp/ in your browser.If all goes well you should be able to cakephp page in colors, something like this.

cakephp installation step10cakephp installation step10

NetBeans IDE Vs Eclipse PDT 2.0 IDE for PHP, Java script, CSS, HTML

NetBeans IDE 7.0M1:

  • Free IDE.
  • Support php, javascript, css, html, java, SVN and lots…
  • Common function of php will show automatically or by pressing ctrl + space.
  • For HTML, it checks div correctly, if there is any unmatched tag like then it will colored and show that problematic line. So you could easily fix that
  • If your file’s extension is .php but you write … netbeans automatically colored the css code in here according to css style.
  • Common javascript functions are shown correctly or using ctrl + space.
  • Indentation format is very good in netbeans. If you select a block of code, that may contains css, javascript, html or php code, netbeans format that code very clearly and placed indentation nicely.
  • Eclipse PDT 2.0

  • Free IDE.
  • Support php, javascript, css, html, java, SVN and lots…
  • Common function of php will show automatically or by pressing ctrl + space.
  • Eclipse couldn’t render div matching properly.
  • If your file’s extension is .php and in that file you write css code within …. eclipse couldn’t render that according to CSS color rather it shows only black color.
  • Common javascript functions are shown correctly or using ctrl + space.
  • Eclipse is not good as netbeans. Specially when you’ll mix html + php code Eclipse makes those more ugly.
  • Bookmark and Share

    Ref: http://mahmudahsan.wordpress.com/2009/01/25/eclipse-vs-netbeans-ide-for-php/

    WordPress, HTML, CSS, PHP, Javascript And More Cheat Sheets

    Cheat sheets are really helpful in revising the codes as there are so many codes which we cannot remember always but cheat sheets are of great help in keeping yourself updatedwith the codes.

    Cheat sheets are also helpful for beginner developers and designers in learning and remembering codes better. A truly great resource for upcoming developers.

    The purpose of this post is to provide all the cheat sheets useful for designers and developers at one place. A mega collection of cheat sheets which contains HTML, CSS, JAVA, PHP, Database SQL, WordPress, Aspx, SEO and many more other useful cheat sheets which you will find in this post. Most of the cheat sheets are available in printable format for a handy use of these resources.

    HTML/XHTML/XML

    CSS

    PHP

    ASP

    Database/SQL

    JavaScript

    WordPress

    SEO

    REWRITE And .HTACCESS

    Photoshop

    Windows

    Mac

    Browser Shortcut Cheats

    Bookmark and Share

    WordPress Plugin’s You Would Like

    A very useful set of WordPress plugins you would like to test. I have scanned through the WordPress plugin directory and found 5 very useful plugins definitely worth taking a look at.

    Keeping in mind that they are new to WordPress plugin directory, their stability should be considered as BETA. So do create a backup before going live.

    1. WP Content Slideshow:

    WP Content Slideshow shows up to 5 Posts in a very nice and powerfull Javascript Slideshow. On the left side of the Slideshow it displays an image for every post. On the right side, there are all the titles (and a small description under the title) of the posts. The Slideshow highlights the active post and repeats automatically after getting to the 5th post. You have a powerfull Administration Area to adjust the category, the number of posts, the width and height, and many colours for the Slideshow!

    Download: WP Content Slideshow
    Compatibility: 2.6+

    2. Sidebar Genrator:

    Now you can create as many sidebars as you need for any page you want. Thats right, page/post specific sidebars. You can easily seperate your site into sections, or make every single page have specific sidebar content on it. Great for CMS sites.

    Download: Sidebar Generator
    Compatibility: 2.8.0+

    3. Quick Adsense:

    Quick Adsense is an Ads management WordPress plugin. It offers a quicker & flexible way to insert Adsense or any Ads code into a blog post. Besides, it can randomly place the Ads anywhere within a post. It comes with a simple setting page, and it does not overwhelm you with complicated customizable options.

    Download: Quick Adsense
    Compatibility: 2.5 – 2.8.4 (maybe 2.8.5)

    4. Members:

    Members is a plugin that extends your control over your blog. It’s a user, role, and content management plugin that was created to make WordPress a more powerful CMS. The plugin is created with a components-based system — you only have to use the features you want.

    Download: Members
    Compatibility: 2.8+

    5. Custom Login page:

    With the Custom Login Page, you can change the background image of your login page, the background image/color of your login form div, the main logo image of your login page, and add custom CSS. All through a simple interface. Remember to view the Help tab at the top of the settings page of the plugin.

    Download: Custom Login Page
    Compatibility: 2.0.2+

    Bookmark and Share

    PHP5 tips

    

    History of PHP

    Rasmus Lerdorf(1995)

    PHP ( Personal Homepage)

    PHP3 ( 1998)

    Zeev suraski and Andi Gutmans(Zend)

    PHP4 ( 2000) Becoming very popular in web

    Expand to OOP ( Java, C#, VB.NET)

    Hence PHP5 emerge which is OOP support.

     

    What newly at PHP5 ?

    New and improved MySQLextension

    PHP 5 bundles SQLite

    SimpleXMLextension (XML)

    Iteratorsand SPL

    Error Handling and Debugging

    Streams, Filters, and Wrappers

     

     

    What needing diinstall ?

    Web Server (Apache, IIS)

    PHP5 Module

    Database Server (MySQL, PostgreSQL)

    Apache2Triad

    Sokkitv4.0

    Editor (Edit Plus / ZendStudio)

     

     

    Declaration Variable

    <?

    $testing = 5; //integer

    echo gettype($testing);

    $testing = “five”; //string

    echo gettype($testing);

    $testing = 5.0; //double

    echo gettype($testing);

    $testing = true; //boolean

    echo gettype($testing);

    ?>

     

     

    Declaration of Constanta

    <?

    define(“USERNAME”,”Algho”);

    echo “User Name :”.USERNAME;

    ?>

     

    Casting

    <?

    $varpublic= 3.14;

    $vardouble= (double)$varpublic;

    echo gettype($vardouble); //double

    $varstring= (string)$varpublic;

    echo gettype($varstring); //string

    ?>

    Operator

    Arithmetic (+, -, *, /)

    Concatenation (.)

    Assigment(+=, -=, /=, *=, %=, .=)

    Comparison (==, !=, >, <, >=, <=)

    Logical (||, &&, !)

     

     

    If Statement

     

    <?

    $mood = “sad”;

    if ($mood == “happy”){

    echo “your happy!”;

    }elseif($mood== “sad”){

    echo “wow your suffer!”;

    }else{

    echo “not happy and not suffer but $mood”; }

    ?>

     

     

    Switch Statement

    <?

    $mood = “sad”;

    switch($mood){

    case “happy”:

    echo “Mood you good!”;

    break;

    case “sad”:

    echo “Mood you bad…”;

    break;

    default:

    echo “Mood you $mood”;

    }

    ?>

     

     

    While Statement

     

    <?

    $counter = 1;

    while($counter<=12){

    echo “$counter * 2 is ” .($counter*2).”<br>”;

    $counter++;

    }

    ?>

     

     

    Do Statement

     

    <?

    $num=201;

    do{

    echo (“Execution number: $num<br>\n”);

    $num++;

    }while($num>200 && $num<400);

    ?>

    For Statement

    <?

    for($counter=1;$counter<=12;$counter++){

    echo “$counter * 2 is : ” .($counter*2).”<br>”;

    }

    ?>

     

     

    Break Statement

     

    <?

    $counter=1;

    while($counter<10){

    if($counter==5){

    echo “stop f counter values 5 <br>”;

    break;

    }

    echo $counter.”<br>”;

    $counter++;

    }

    ?>

     

    Continue Statement

    <?

    for($counter=1;$counter<=10;$counter++){

    if($counter==5) continue;

    echo “counter result : $counter<br>”;}

    ?>

     

    Usage of Function.

    <? //functionbyvalue.php

    function tax($salary){ //definisi

    $salary = $salary-(($salary/100)*20);

    return $salary;

    }

     

    $salary = 2000;

    echo tax($salary); //hasil1600

    echo $salary; //hasil2000

    ?>

     

     

    Function Passing by Reference

    <? //functionbyreference.php

    function tax(&$salary){ //definisi

    $salary = $salary-(($salary/100)*20);

    return $salary;

    }

    $salary = 2000;

    echo tax($salary); //hasil1600

    echo $salary; //hasil1600

    ?>

    Setting default parameter function

    <?

    function tax($salary=2000){ //definisi

    $salary = $salary-(($salary/100)*20);

    return $salary;

    }

    echo tax();

    ?>

     

     

    Scope Variable

    <?

    $welcomemessage= “Hello World”; //global

    function translate(){

    $welcomemessage= “Halo Dunia”; //local

    return $welcomemessage;

    }

    translate();

    echo $welcomemessage;

    ?>

     

    Nesting Function

    <? //nestingfunction.php

    function pension($total){

    function tax($salary){

    return $salary -(($salary/100)*20);

    }

    $posttax= tax($total);

    return tax(tax($total)-($posttax/100)*3);

    }

    $total = 2000;

    echo pension($total);

    ?>

     

    Array

     

    Defenition of array() function

    $users = array(“tom”,”sharon”,”jhon”,”hary”);

     

    Identifier of array

    $user[] = “tom”; $user[] = “sharon”;

    $user[] = “jhon”; $user[] = “hary”;

     

    Example used array

    <? //foreach.php

    $user= array(“tom”,”bert”,”sharon”,”jhon”);

    foreach($user as $key=>$value){

    echo “Array Ke-“.$key.” isinya: “.$value.”<br>”; }

    ?>

     

    Statement While List

    <? //whilelist.php

    $user= array(name>”bob”,occupation=>”programmer”,age=>30,hobby=>”swimming”);

    while(list($index,$value) = each($user)){

    echo $index.” : “.$value.”<br>”;

    }

    ?>

     

    Function In Array

     

    implode -> combination array to string

    explode -> breaking string to array

    sort() -> sort array scr asc

    rsort() -> sort array scr desc

    ksort() -> sort index string array scr asc

    array_pop() -> delete array in the last character

    array_push() -> added array

     

     

    Example Used Array

    <? //explodeimplode.php

    $city[0]=”padang”;

    $city[1]=”dharmasraya”;

    $city[3]=”bukittinggi”;

    $strcombination= implode(“-“,$city);

    echo “after combination: “.$strcombination.”<br>”;

    $cityarray= explode(“-“,$strcombination);

    foreach($cityarrayas $key=>$value){

    echo “Array to-“.$key.” = “.$value.”<br>”;

    }

    ?>

     

    Take Data From Form (HTML)

    //formuser.php

    <html><body>

    <form action=”lihat.php” method=”POST”>

    Name: <input type=”text” name=”name”><br>

    Addres: <input type=”text” name=”addres”><br>

    Password: <input type=”password” name=”password”><br>

    Gender:

    <input name=”gender” type=”radio” value=”male”>Male

    <input name=”gender” type=”radio” value=”female”>Female<br>

    Boldness:<br><textareaname=”boldness”></textarea><br>

    <input type=”submit”> <input type=”reset”>

    </form>

    </body></html>

     

    <? //lihat.php

    echo “<html></body>”; //file lihat.php

    if (empty($_POST[“nama”])) $ket.=”name still empety,”;

    if (empty($_POST[“password”])) $ket.=”password still empety,”;

    if (empty($_POST[“hobi”])) $ket.=”hobby still empety,”;

    if (empty($_POST[“alamat”])) $ket.=”addres still empety,”;

    if (empty($_POST[“gender”])) $ket.=”gender still empety,”;

    if (empty($_POST[“pilihan”])) $ket.=”choice still empety “;

    if (empty($_POST[“keterangan”])) $ket.=”boldness still empety “;

    if (isset($ket)){

    echo “Error :”.$ket;

    exit;

    }

    echo “your name: “.$_POST[“nama”].”<br>”;

    echo “your addres: “.$_POST[“alamat”].”<br>”;

    echo “your Password: “.$_POST[“password”].”<br>”;

    echo “your gender: “.$_POST[“gender”].”<br>”;

    echo “your Hobby:

    foreach($_POST[“hobi”] as $key=>$value){

    echo “Hobby to-“.$key.”= “.$value.”<br>”;

    }

    echo “choice your President : “.$_POST[“pilihan”].”<br>”;

    echo “Boldnes:”.$_POST[“boldness”];

    echo “</body></html>”;

    ?>

    

    Register Global If Close ?

     

    Hence we cannot overcome variable directly

    $_GET[“varname”]

    $_POST[“varname”]

    $_SESSION[“varname”]

    $_COOKIE[“varname”]

    $_REQUEST[“varname”]

    $_FILES[“varname”]

     

     

    Used Session (HTML)

    <html><body>

    <form action=”prosessession.php” method=”POST”>

    User Name :<input type=”text” name=”username”><br>

    Password :<input type=”password” name=”password”><br>

    <input type=”submit”>

    </form>

    </body></html>

     

     

    Used Session (PHP)

    <? //prosessession.php

    session_start();

    $username = $_POST[“username”];

    $password = $_POST[“password”];

    if ($username==”erick” && $password==”webdb”){

    $_SESSION[“user”] = $username;

    header(“Location: succseslogin.php”);

    }else {

    echo “Sorry, you failed to login”;

    }

    ?>

     

     

     

    Set Cookies

    <? //setcookie.php

    setcookie(“username[one]”,”erick”,time()+60);

    setcookie(“username[two]”,”jhon”,time()+60);

    setcookie(“username[three]”,”bart”,time()+60);

    echo “Cookie telahdiset… <a href=’lookcookie.php’>cookie</a>”;

    ?>

    Look Cookies

    <? //lihatcookie.php

    echo “After send Cookie : <br>”;

    if (isset($_COOKIE[“username”])){

    while(list($index,$value) = each($_COOKIE[“username”])){

    echo “Name to-“.$index.” = “.$value.”<br>”;

    }

    }

    ?>

     

    Used Header Authentication

    <? //headerauth.php

    if(!isset($PHP_AUTH_USER)){

    header(“WWW-Authenticate: Basic realm=\”My Realm\””);

    header(“HTTP/1.0 401 Unauthorized”);

    echo(“Textto send if user hits Cancel button\n”);

    exit;

    }else {

    echo “<p>Hello $PHP_AUTH_USER</p>”;

    echo “<p>You entered $PHP_AUTH_PW as pwd</p>”;

    } ?>

     

     

     

     

     


    Create simple WordPress plugins

    Creating a Simple WordPress Plugin

    You can use this as a code snippet for your projects. I am going to create a simple plugin that does nothing but display “Hello World”. I’ll leave the actual functionality of the plugin to you

    Create a new php file in your plugin directory called my-hello-world.php, and type the following plugin code:

    <?php
    /*
    Plugin Name: Hello World
    Plugin URI: http://lonewolf-online.net/
    Description: Sample Hello World Plugin
    Author: Tim Trott
    Version: 1
    Author URI: http://lonewolf-online.net/
    */function sampleHelloWorld()
    {
    echo “<h2>Hello World</h2>”;
    }
    ?>

    The lines inside /* and */ are used by WordPress to find out about the plugin. We have one function called sampleHelloWorld which does exactly that.

    Now, traditionally we would have had to open up the sidebar of the theme you are using, find the location of where you want the Hello World displayed, and hard code the function in. Upload to the server and test. If for some reason there is a problem with your plugin (or a third party plugin) then your site would almost certainly stop working. Changing the location from the left to the right sidebar means editing both files accordingly. This isn’t very good.

    Widgets

    Widgets take away the need for editing the sidebar files of a theme and allow for a drag and drop interface in the admin panel. Lets have a look at how we can wiget enable our plugin.

    Open up the Hello World plugin file again and add these lines:

    function widget_myHelloWorld() {
    ?>
    <h2 class=”widgettitle”>My Widget Title</h2>
    <?php sampleHelloWorld(); ?>
    <?php
    }function myHelloWorld_init()
    {
    register_sidebar_widget(__(‘Hello World’), ‘widget_myHelloWorld’);
    }
    add_action(“plugins_loaded”, “myHelloWorld_init”);

    The first function here is what will be displayed on the sidebar when its set-up correctly. Notice that we are calling on our old function. This is upgrading the existing plugin to be widget enabled. You can if you like replace the function call with the function statements and combine the two functions.

    The second function is called by WordPress when the plugin is activated. It calls a WordPress function that will register a new widget which will be called “Hello World” which will call our new widget function.

    Add action just tells WordPress to call myHelloWorld_init when the plugin is loaded.

    Enhancements for Theme Compatibility

    While this widget will function fine, we can make some improvements to enable greater theme compatibility – not everyone uses the same themes as you test on.

    WordPress will pass parameters to your widget, which contain information about the sidebar and the CSS classes. We should process these parameters and output the correct tags, or you risk breaking some themes.

    The first thing we need to do is change our sampleHelloWorld function so that it will accept parameters, then to process these parameters into variables. This is done using the extract function.

    function widget_myHelloWorld($args) {
    extract($args);
    ?>
    <h2 class=”widgettitle”>My Widget Title</h2>
    <?php sampleHelloWorld(); ?>
    <?php
    }

    These two lines will allow us to reference some variables and output correct html structure for the theme being used. The most important variables are before_widget, after_widget, before_title and after_title. Previously we have surrounded the widget title with a hard coded H2 tag with a css class widgettitle, but many themes do not support these tags. They may use a div, or a h1 or a span, so we need our widget to be flexible.

    function widget_myHelloWorld($args) {
    extract($args);
    echo $before_widget;
    echo $before_title;?>My Widget Title<?php echo $after_title;
    sampleHelloWorld();
    echo $after_widget;
    }

    These changes will allow our plugin to use the same tags as the theme author informs us we need to use, and will allow your widget to look the same as the other widgets in the sidebar.

    To configure these options inside a theme, please see the section below on theme support.

    Complete Plugin:

    <?php
    /*
    Plugin Name: Hello World
    Plugin URI: http://lonewolf-online.net/
    Description: Sample Hello World Plugin
    Author: Tim Trott
    Version: 1
    Author URI: http://lonewolf-online.net/
    */function sampleHelloWorld()
    {
    echo “<h2>Hello World</h2>”;
    }function widget_myHelloWorld($args) {
    extract($args);
    echo $before_widget;
    echo $before_title;?>My Widget Title<?php echo $after_title;
    sampleHelloWorld();
    echo $after_widget;
    }

    function myHelloWorld_init()
    {
    register_sidebar_widget(__(‘Hello World’), ‘widget_myHelloWorld’);
    }
    add_action(“plugins_loaded”, “myHelloWorld_init”);
    ?>

    Testing your Plugin

    If you check your plugins page now, you should now have a new plugin listed called Hello World which you can activate. On the Presentation tab, select widgets, and you should see your new widget available to be dragged onto a sidebar. Save your changes and admire your new work.

    t is more than likely that your WordPress Widget will need to have some user configurable settings, so why not include a settings form within your widget?These settings pages (admin panels, configuration screen and so on…) are accessed from within the Presentation » Widgets screen from WordPress 2 and from Design » Widgets in WordPress 2.5. When you add a widget to a sidebar, you may notice a little icon on the right hand side of the widget. Clicking on this will open up the widget admin panel where your users can customize your widget to their needs.

    Lets use the code from the Hello World widget of the last tutorial and change it around so that we have a settings page. We will see how to create the settings page, how to store/save and retrieve/load settings using the WordPress database and how to handle user inputs.

    <?php
    /*
    Plugin Name: Hello World
    Plugin URI: http://lonewolf-online.net/
    Description: Sample Hello World Plugin
    Author: Tim Trott
    Version: 1
    Author URI: http://lonewolf-online.net/
    */function sampleHelloWorld()
    {
    echo “<h2>Hello World</h2>”;
    }

     

    function widget_myHelloWorld($args) {
    extract($args);
    echo $before_widget;
    echo $before_title;?>My Widget Title<?php echo $after_title;
    sampleHelloWorld();
    echo $after_widget;
    }

    function myHelloWorld_init()
    {
    register_sidebar_widget(__(‘Hello World’), ‘widget_myHelloWorld’);
    }
    add_action(“plugins_loaded”, “myHelloWorld_init”);
    ?>

    The first thing we are going to create is the icon on the Widget sidebar screen, and get it to open up a blank screen which we will later fill with input controls.

    We need to create a function that will be used to display and process the options. The convention is to use the plugin name appended with _control for the control panel page.

    function myHelloWorld_control()
    {
    }

    We will come back to this function a bit later on. For now, we will just get WordPress to use our blank form.

    In the _init function where we register the sidebar widget, we need to add another function call that will tell WordPress that we have a control panel associated with our plugin.

    function myHelloWorld_init()
    {
    register_sidebar_widget(__(‘Hello World’), ‘widget_myHelloWorld’);
    register_widget_control(   ‘Hello World’, ‘myHelloWorld_control’, 300, 200 );
    }

    This extra function specifies the title of the page, the function that will be called (in this example it does nothing yet) and the widget control panel screen will be 300 pixels wide by 200 pixels tall. You can test this now, or continue and add some content.

    WordPress Options

    Before we get started on the admin panel, lets first have a look at how we can use the WordPress options database to store values. WordPress has a nice function that will do all the hard work for you called update_option. This function simply takes a key name and the data to store under that key, be it a string, integer or an array. You should try and use a unique, but meaningful, key name to avoid conflicts with other plugins or WordPress itself. I also use a prefix of “widget_” to identify that the settings are for a widget.

    The WordPress options database is a table called by default wp_options, and maintains a list of key name and value pairs.

    update_options(“widget_myHelloWorld”, “This is a test”);

    This will update the key named widget_myHelloWorld in the WordPress database and set the value to “This is a test”. You can retrieve the information at a later date using the get_option function. This function only takes one parameter – the key name to retrieve.

    $title = get_option(“widget_myHelloWorld”);
    echo $title;

    In this example we would expect to see “This is a test” on the screen.

    Constructing our Admin Page

    I am going to create the admin panel in four stages in this tutorial, you may wish to merge these all into one, or do them in a different order – its entirely up to you.

    1. Create the Form Controls

    To begin with you are going to need a form design. In this example we are going to simply use a text box and a label. I’ll leave the for design to you!

    Each line on the form should be contained within a paragraph block to keep a nice uniform spacing between all elements. By default the items will be centred on the form, so if you need them to be left or right aligned, you will need to specify this in the p tag.

    This is the code for my simple html form. You must use unique name and id attributes on the form. You will notice that there is no <form> element in the code. This is because a form element is provided by WordPress which encompass all the widgets that have been loaded.

    function myHelloWorld_control()
    {
    ?>
    <p>
    <label for=”myHelloWorld-WidgetTitle”>Widget Title: </label>
    <input type=”text” id=”myHelloWorld-WidgetTitle” name=”myHelloWorld-WidgetTitle” value=”” />
    </p>
    <?php
    }

    If you test now you should have a label and text box centred on the widget control form. It is more than likely that you will need more than one form control, however I will let you work on that now you have a grasp of the basics.

    2. Get Existing Data and Default Values

    The next stage it to populate the form controls with either default values, or values obtained from the database with the get_options function.

    Lets get the data from the database, perform a test on it to see if we have valid data, fill the data with default values if necessary then populate the form controls.

    function myHelloWorld_control()
    {
    $options = get_option(“widget_myHelloWorld”);
    if (!is_array( $options ))
    {
    $options = array(
    ‘title’ => ‘My Widget Title’
    );
    }?>
    <p>
    <label for=”myHelloWorld-WidgetTitle”>Widget Title: </label>
    <input type=”text” id=”myHelloWorld-WidgetTitle” name=”myHelloWorld-WidgetTitle” value=”<?php echo $options[‘title’];?>” />
    </p>
    <?php
    }

     

    The first new line in this code will get the previously stored values from the database. We then test the output variable to see if it is null (no data was retrieved from the database) and if it is we create a new array with one element for the widget title. This method will guarantee that we have a valid value for the title (or an other setting) from the database or a default value. We can then use the title stored in the array to output into the text box value attribute.

    3. Get User Input and Store the New Settings

    We need some way of capturing the value a user may type in the box and storing it in the database to be re-used. For this we will need another form element that will identify our data when it is submitted. This new element is a hidden value which we will test against.

    function myHelloWorld_control()
    {
    $options = get_option(“widget_myHelloWorld”);
    if (!is_array( $options ))
    {
    $options = array(
    ‘title’ => ‘My Widget Title’
    );
    }if ($_POST[‘myHelloWorld-Submit’])
    {
    $options[‘title’] = htmlspecialchars($_POST[‘myHelloWorld-WidgetTitle’]);
    update_option(“widget_myHelloWorld”, $options);
    }

     

    ?>
    <p>
    <label for=”myHelloWorld-WidgetTitle”>Widget Title: </label>
    <input type=”text” id=”myHelloWorld-WidgetTitle” name=”myHelloWorld-WidgetTitle” value=”<?php echo $options[‘title’];?>” />
    <input type=”hidden” id=”myHelloWorld-Submit” name=”myHelloWorld-Submit” value=”1″ />
    </p>
    <?php
    }

    In this new code segment, we look at the PHP POST variable for an element called myHelloWorld-Submit (the same as the hidden field) and if we found it we extract the widget title from the post variable. It is important to ensure that the code we are about to insert into the database does not contain any malicious code, so we can use the htmlspecialchars function to help prevent SQL injections. We then make a call to update_option to save the new values to the database.

    4. Using the Data

    What is the point of doing all this and not using the data? None what so ever. Using the data within the widget is just as easy (in fact its the same) as using the data on the form.

    In our code that outputs the widget title, you simply need to get the values for the database with get_option, make sure we have valid information and then output the value. We have already seen this in action on the widget control stage, so I will just go straight to the full code listing for this tutorial.

    Complete Code

    <?php
    /*
    Plugin Name: Hello World
    Plugin URI: http://lonewolf-online.net/
    Description: Sample Hello World Plugin
    Author: Tim Trott
    Version: 2
    Author URI: http://lonewolf-online.net/
    */function sampleHelloWorld()
    {
    echo “<h2>Hello World</h2>”;
    }

     

    function widget_myHelloWorld($args) {
    extract($args);

    $options = get_option(“widget_myHelloWorld”);
    if (!is_array( $options ))
    {
    $options = array(
    ‘title’ => ‘My Widget Title’
    );
    }

    echo $before_widget;
    echo $before_title;
    echo $options[‘title’];
    echo $after_title;

    //Our Widget Content
    sampleHelloWorld();
    echo $after_widget;
    }

    function myHelloWorld_control()
    {
    $options = get_option(“widget_myHelloWorld”);<br/>
    if (!is_array( $options ))
    {
    $options = array(
    ‘title’ => ‘My Widget Title’
    );
    }

    if ($_POST[‘myHelloWorld-Submit’])
    {
    $options[‘title’] = htmlspecialchars($_POST[‘myHelloWorld-WidgetTitle’]);
    update_option(“widget_myHelloWorld”, $options);
    }

    ?>
    <p>
    <label for=”myHelloWorld-WidgetTitle”>Widget Title: </label>
    <input type=”text” id=”myHelloWorld-WidgetTitle” name=”myHelloWorld-WidgetTitle” value=”<?php echo $options[‘title’];?>” />
    <input type=”hidden” id=”myHelloWorld-Submit” name=”myHelloWorld-Submit” value=”1″ />
    </p>
    <?php
    }

    function myHelloWorld_init()
    {
    register_sidebar_widget(__(‘Hello World’), ‘widget_myHelloWorld’);
    register_widget_control(   ‘Hello World’, ‘myHelloWorld_control’, 300, 200 );
    }
    add_action(“plugins_loaded”, “myHelloWorld_init”);
    ?>

    Bookmark and Share