Posts Tagged ‘ php ’

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/

    Ajax in WordPress Plugin

    Introduction

    Ajax (Asynchronous JavaScript And XML) is a technology that allows a web page to update some of its information without a full page reload. It is used in the Administration sections of WordPress for auto-save of post edits, adding new categories, and other purposes. Some WordPress Plugins also use AJAX for things like voting on post ratings and map refreshes.

    This article, aimed at plugin developers, describes how to add Ajax to a plugin. Before reading this article, you should be familiar with the following:

    * Ajax – Overview of the technology
    * Writing a Plugin – How to write a plugin
    * Plugin API – Filters and actions – what they are and how to use them
    * How to add HTML to the appropriate WordPress page, post, or screen — for instance, if you want to add Ajax to administration screens you create, you will need to understand how to add administration menus to WordPress; if you want to add Ajax to the display of a single post, you’ll need to figure out the right filters and actions to add HTML to that spot on viewer-facing blog screens. This article does not cover these topics.
    * You will also need to know something about client-side JavaScript programming, PHP programming, and HTML, in order to use Ajax in WordPress.

    It turns out that the techniques for adding Ajax to a plugin are quite different, depending on whether you want the Ajax functionality to be part of the WordPress administration screens, or to appear on the viewer-facing side of WordPress. So, this article treats those two possibilities separately (after discussing common considerations).

    Ajax Implementation Basics

    There are three steps in an Ajax request, in general:

    1. The user does something (such as clicking or dragging the mouse), and JavaScript embedded in the HTML of the web page responds by composing a “request” and sending it to a special URL on the web server. Due to security restrictions, the URL the request goes to must be on the same web site that the file containing the JavaScript came from.
    2. A script or program on the web server (in WordPress, this will generally be one or more PHP functions) processes the request and sends information back to the browser.
    3. The returned information is displayed using JavaScript.

    Unfortunately, much of Ajax is JavaScript, which runs in the user’s web browser, and the different web browsers have not all implemented the Ajax calls and responses in the same manner. So, to make things easier, most Ajax developers choose to use a tested cross-browser library that wraps the particular browser idiosyncracies in a standard class with a documented API. In this article, we’ll use one such library, SACK (Simple Ajax Code-Kit), which is included in WordPress. The Further Reading section (see bottom of page) has several references for how to use JQuery to do AJAX — JQuery is another library included in WordPress, and the concepts are pretty much the same, but the syntax is a bit different.

    So, we’ll need to make sure both the SACK library and the JavaScript functions that compose the Ajax request get included in the HTML head section of the web page where the Ajax request will take place; the sections below will show how to do that for both the administration and viewer-facing sides of WordPress.

    When creating an Ajax request using the SACK library, we’ll need to supply the following information; the sections below will fill in the details of what this information should be for the administration side and the viewer-facing side:

    * Request URL: The URL on the server that will process the Ajax request.
    * Custom request variables: SACK allows us to set arbitrary request variables, which are sent via POST or GET to the server. Cookie information can also be sent.
    * What to do if there is an error: a JavaScript function to call if there is an Ajax error.

    By default, SACK assumes that the returned information from the server is JavaScript code, which is executed when it comes in (asynchronously). In the examples below, we’ll use this default behavior, so the PHP functions that are processing Ajax requests will need to compose their results into JavaScript commands. If you want to do something else with the returned information in your plugin, you might want to visit the SACK Project Home Page, download the zip file, and read the documentation, because there are definitely other possibilities.

    One other detail is that the PHP function that processes the Ajax request should use the PHP die function at the end.

    Ajax on the Administration Side

    Since Ajax is already built into the core WordPress administration screens, adding more administration-side Ajax functionality to your plugin is fairly straightforward, and this section describes how to do it. As mentioned above, if you want to use Ajax on the blog-viewer-facing side of WordPress, you can completely skip this section of the article.

    Here’s a short example. All this will be in one file.

    First, add some javascript that will trigger the AJAX request:

    jQuery(document).ready(function($) {

    var data = {
    action: ‘my_special_action’,
    whatever: 1234
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    jQuery.post(ajaxurl, data, function(response) {
    alert(‘Got this from the server: ‘ + response);
    });
    });

    <?php
    }

    Then, set up a PHP function that will handle that request:

    <?php

    add_action('wp_ajax_my_special_action', 'my_action_callback');

    function my_action_callback() {
    global $wpdb; // this is how you get access to the database

    $whatever = $_POST['whatever'];

    $whatever += 10;

    echo $whatever;

    die();
    }

    That's it! You will need to add a few details, such as error checking and verifying that the request came from the right place ( using check_ajax_referer() ), but hopefully the example above will be enough to get you started on your own administration-side Ajax plugin.
    NOTE: Since Version 2.8, The javascript global variable ajaxurl can be used in case you want to seperate your javascript code from php files into javascript only files.

    Ajax on the Viewer-Facing Side

    As of WordPress 2.8, there is a new hook similar to 'wp_ajax_my_action':

    'wp_ajax_nopriv_my_action' executes for users that are not logged in.

    So, if you want it to fire for both visitors and logged-in users, you can do this:

    add_action('wp_ajax_my_action', 'my_action_callback');
    add_action('wp_ajax_nopriv_my_action', 'my_action_callback');

    Note: In WP 2.8, if a user is not logged in ('wp_ajax_nopriv_my_action'), then GET requests are ignored (and return -1). This bug was fixed in WP 2.9.
    Note 2: Unlike on the admin side, the "ajaxurl" javascript variable does not get automatically defined for you. Use this PHP code to generate the URL you need to call instead:

    echo admin_url('admin-ajax.php');

    Ajax on the Viewer-Facing Side ( WordPress 2.6 , 2.7, 2.8 )

    Implementing Ajax on the viewer-facing side in older versions of WordPress is slightly more ad-hoc than doing Ajax on the administration side and this section describes how to do it.

    As an example, let's consider a plugin that allows a blog viewer to vote on or rate something (which could be a generic poll plugin, a post rating plugin, or something else like that). When the blog viewer submits a vote, we want the submission to go via Ajax, so that the viewer doesn't have to wait for the page to refresh; after the vote is registered, we'll want to update the running vote total display. For this example, we'll assume the voting and display are text-based, for simplicity, and we'll assume you've either edited the theme or used a WordPress filter or action to add HTML to the appropriate WordPress viewer-facing screen. The added HTML will look something like this:

    Your vote:

    (previous results output from your PHP function)

    Next, we need to define the JavaScript function myplugin_cast_vote, the onClick action for the button, which will read the information the user entered, compose a request with SACK, and send it to the plugin for processing. As mentioned in the introductory section, this JavaScript function and the SACK library need to get added to the HTML head section of the web page the user is viewing. One way to do that is to add it to all viewer-facing screens using the wp_head action (you could also be a little more selective by using some of the is_xyz() Conditional Tags tests). Let’s drop this in a plugin file myplugin.php:

    add_action(‘wp_head’, ‘myplugin_js_header’ );

    function myplugin_js_header() // this is a PHP function
    {
    // use JavaScript SACK library for Ajax
    wp_print_scripts( array( ‘sack’ ));

    // Define custom JavaScript function
    ?>

    //

    <?php
    } // end of PHP function myplugin_js_header

    Next activate the plugin and reload the HTML where the form is. By looking at the HTML source you should see the SACK Javascript library being loaded:

    The next step is to fill in the body of the myplugin_cast_vote JavaScript function, which is supposed to read the vote from the form field, compose an Ajax request with SACK, and send the request to the server. Given the list of generic SACK information from the introductory section, here is what we need to set up for this example:

    * Request URL: We need to send our request to a plugin PHP file. This should be the main plugin PHP file. In case you want it to be a separate PHP file, bare in mind that you won’t be able to access the WordPress global variables, e.g. $wpdb, since separate files have absolutely no visibility to any part of WordPress at all.
    * Custom request variables: We need to send the vote and the ID of the div where the results go to the server, and also the function that will be called to process the vote in this simple example.

    Putting this together, the body of the JavaScript function becomes:

    function myplugin_cast_vote( vote_field, results_div )
    {
    var mysack = new sack(
    “/wp-admin/admin-ajax.php” );

    mysack.execute = 1;
    mysack.method = ‘POST’;
    mysack.setVar( “action”, “my_special_action” );
    mysack.setVar( “vote”, vote_field.value );
    mysack.setVar( “results_div_id”, results_div );
    mysack.onError = function() { alert(‘Ajax error in voting’ )};
    mysack.runAJAX();

    return true;

    } // end of JavaScript function myplugin_cast_vote

    add_action(‘wp_ajax_my_special_action’, ‘my_action_callback’);
    add_action(‘wp_ajax_nopriv_my_special_action’, ‘my_action_callback’);

    Take special note of the Javascript code which has an “action” variable. Also take note that it is calling the admin-ajax.php file. Then note that my_special_action is part of the first parameter in the add_action call (wp_ajax_my_special_action). These are all significant.

    The final step in this example is to define my_action_callback, which is what gets called when the Ajax request gets to the server. This will need to read the posted information, verify that the vote is valid, add the vote to the database, figure out what the new running totals are, and send that back to the browser. Leaving aside all the details of processing the vote, here’s what needs to go into the file:

    That’s it! You will need to add a few details, such as error checking, escaping quotes, processing the vote, and verifying that the request came from the right place, but hopefully the example above will be enough to get you started on your own viewer-side Ajax plugin.

    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

    Optimizing WordPress for Search Engines

    You have this amazing WordPress site, but for some reason the search engines just don’t show you much love. You post killer content, make it easy for users to share via their social networks, and people are subscribing to your RSS feed, indicating that they’re like what they’re reading. If you’ve tried everything to drive traffic to your website, and search engines still ignore your site, maybe you need to evaluate how search engine friendly your website is.

    . Optimizing WordPress for Search Engines

    I will go over a few steps you should take to optimize your WordPress installation for search engines. While WordPress has good SEO features out of the box, these tips will help you maximize your search engine results while also making sure your site is the best it can be.

    1. Optimize your titles

    By default, WordPress usually puts the title of your blog before the actual post title. Since most search engines only display the first 50-64 characters of your <title> tag, you want the actual blog post title to come first.

    For example:

    Tips for Making WordPress Friendly to Search Engines - YourSiteName.com

    is better than:

    YourSiteName.com - Tips for Making WordPress Friendly to Search Engines

    Always be sure that the title of your post comes before anything else. Two main reasons are:

    1. Search engines will like you more if the title of the post comes first. This helps them put more importance to the keywords in the title.

    2. A descriptive and optimized title is one of the most important aspects of your page SEO. The title lets the search engine and users know exactly what this page is about before they visit it.

    Optimize your titles

    Use the All In One SEO plugin to keep the proper title formats over an entire blog without having to edit any template files. The above screenshot shows the settings we currently use on WPSwitch.

    2. Use good meta descriptions

    Most bloggers who use WordPress never do much on the SEO side for meta descriptions because they believe that the auto generated descriptions that comes standard with WordPress is good enough; but that’s not truly the case if you’re concerned about effective keyword indexing on search engines.

    Use good meta descriptions

    Your best chance of getting a high ranking on a per-post basis is by manually typing in a good description for every article you write. Again, I would suggest using the All In One SEO plugin as it allows you to do this very easily. By combining a keyword-rich title with a matching description, you are bound to see an increase in search traffic.

    Use good meta descriptions

    As you can see in the two screenshots above, by optimizing meta descriptions, one of our pages is able ranked highly (withing the first 5-10 results in Google) for a particular search term. Now that you know the importance of a detailed and keyword-rich description, I hope you see some great results.

    3. Rewrite your URLs with permalinks

    Permalinks are enhancements to your existing URLs that can improve search engine optimization by presenting your post, page, and archive URLs as something like:

    http://sixrevisions.com/tools/managing-your-fonts/

    rather than

    http://sixrevisions.com/?p=423

    Changing the default web addresses/URLs that WordPress generates to something more readable is effective to search engine optimization because it is presumed that URLs are taken into consideration when indexing and prioritizing search results. Often, these URLs are called “pretty URLs” because they’re much more readable and gives the users a clue as to what the web page will be about (as in the above comparison of URLs).

    Making your permalinks friendlier and readable requires little more than a short trip to your WordPress admin panel. Once you are there, go to Settings > Permalinks and edit the settings as shown in this image below:

    Use good meta descriptions

    I prefer to include the category in my title and write the URLs like this:

    /%category%/%postname%

    This would result in a format that looks like:

    http://example.com/the-category/the-post-title

    if you want it even shorter you can exclude the category and just use the following value for the Custom Structure setting:

    /%postname%/

    If you are now just setting up a new WordPress site, then you are set to go. If your site has been up for a while, than I suggest using the redirection plugin so that your visitors will not get the 404 page after you rewrite your URLs to pretty URLs.

    4. Use breadcrumbs

    Using breadcrumbs on a WordPress site is often overlooked but can be a huge benefit for your readers and for SEO. Links with good key words that relate to the post topic and links to internal web pages is one of the ways search engines determine the relevance of a web page to search terms.

    Use breadcrumbs

    By using breadcrumbs, you make it easier for the readers to navigate and help the search engines to discover the structure of your website. On WPSwitch, we use the Breadcrumbs Plugin written by Joost De Valk. It only takes about five minutes to set up. (Find more helpful WordPress plugins).

    5. Generate an XML Sitemap for search engines

    An XML Sitemap is a listing of all the pages and posts on your website. This helps the search engine crawlers get a machine-readable structure of your websites. Having a properly structured sitemap has great benefits in the search engines.

    Thanks to the massive amount of plugins, generating a sitemap with WordPress is super easy. I suggest using the XML Sitemaps.

    Generate an XML Sitemap for search engines

    This plugin will generate a special XML sitemap that will assist search engines like Google, Bing, Yahoo and Ask.com in more extensively and accurately indexing your posts and pages. The plugin supports various WordPress generated pages as well as custom URLs. Additionally, it notifies all major search engines every time you create a post about the new content by pinging them.

    6. Describe your post images meaningfully

    Another often-neglected item in WordPress SEO is using proper and keyword-accurate alt and title attributes with images in a post or page. Adding a short description of your image using proper keywords can boost your search engine hits through image searches like the one from Google Images. Since you are using WordPress, adding alt and title attribute values to images is easy.

    While saving your image, be sure to give a short and simple name with a dash between each keyword. For example, if you have a picture of a California Redwood tree, name it appropriately, such as california-redwood-tree.jpg or california_redwood_tree.jpg instead of something vague and non-descriptive like postimage03.jpg or screenshot20.jpg.

    (read about tools for optimizing your images).

    Once you place your image in a WordPress post or page, it will automatically use the title given as the proper alt description.

    Describe your post images meaningfully

    If it does not fill it in automatically, you can type a description in the title input field. By implementing these image attributes, it will also make it easier for people who use a screen reader to browse your site.

    In summary: don’t neglect your images, name them properly, and assign meaningful title and alt attributes to them.

    7. Link to related posts

    One favorable method for helping search engines find content that is relevant to a given web page is adding a “related posts” section that links to other posts that have a connected subject.

    By doing so, you also have the primary benefit of showing your readers other posts that they may want to read as well.

    Many WordPress plugins will automatically generate a list of related posts for each of your posts. There are way to many too mention here, but you can find a list in the WordPress plugins section at WordPress.org just by searching “related posts“.

    WPSwitch currently usees the Yet Another Related Posts Plugin and it works very well. This is our favorite because it gives you a templating system that allows control over how the related posts are displayed.

    8. Use good keywords in post headings

    Search engines give more weight to keyword items depending on what type of heading that is being used. To get the most juice out of your titles, make sure the post title is an <h1>.

    The name of your blog should only be an <h1> on your front page. On single, post, and category pages, it should be no more than an <h3>, some even choose to use other HTML elements such as a <p> element to keep the markup semantic. The title of your site does not need to carry as much weight as the topic you are writing about.

    To make sure your site name is only an <h1> on the home page, you can use the code below and modify it to work with your theme in the header.php file. This checks to see if you are on the home page or other pages and decides what heading tag to use. Most people use this link for the logo of the site linking back to the index.

    <div id="logo">
    <?php if(is_home()) : ?>
    <h1>
      <a href="<?php echo get_option('home'); ?>"><?php bloginfo('name'); ?></a>
    </h1>
    <?php else : ?>
    <a href="<?php echo get_option('home'); ?>"><?php bloginfo('name'); ?></a>
    <?php endif;  ?>
    </div>

    When fixing your headings on posts or pages find the code that looks like this:

    <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>

    Headings are super easy to edit and are found in the single.php and page.php and various archive pages of your WordPress theme. If your current theme does not use headings in this manner, I suggest you take a few minutes to make this easy change.

    9. Avoiding duplicate content with robots.txt

    With WordPress showing the same posts on multiple pages like the index, tag pages, archives, author pages, and category pages, it is very easy to have duplicate content. Duplicate content, in the eyes of search engines, is frowned upon. By creating a robots.txt file, you can completely avoid this issue.

    If you want to create your own robots.txt file, you can use the following:

    User-agent: *
     	Allow: /
    
    Disallow: /wp-content/
     	Disallow: /trackback/
     	Disallow: /wp-admin/
     	Disallow: /archives/
     	Disallow: /*?
     	Disallow: /*.js$
     	Disallow: /*.inc$
     	Disallow: /*.css$
     	Disallow: */trackback/
     	Disallow: /c/
     	Disallow: /author/
     	Disallow: /tag/
    
    User-agent: Mediapartners-Google
     	Allow: /
    
    User-agent: Adsbot-Google
     	Allow: /
    
    User-agent: Googlebot-Image
     	Allow: /
    
    User-agent: Googlebot-Mobile
     	Allow: /
    
    #User-agent: ia_archiver-web.archive.org
     	#Disallow: /
    
    Sitemap: http://wpswitch.com/robots.txt

    This is directly from the current Robots.txt we’re using over at WPSwitch. If you use this, be sure to change the Disallow: /c/ to whatever category structure you are using like /category/, for example.

    We also disabled indexing of all .js, css, and .inc files that shouldn’t be search-engine crawlable.

    A much easier way if you are not code-savvy is to use the Robots Meta plugin. This modifies the default one made by WordPress from your original install.

    Summary

    I covered just a few easy ways to create WordPress sites that search engines will love. I know this seems like a lot of busy work, but if you sit down for a few hours, the return of your time investment will be worth your time. If you feel overwhelmed by the many things listed here, you don’t have to do them all at once. Take a few minutes out of every day and do them one at a time. By the end of the week, you will have an SEO optimized blog that you and the search engines will be proud of showing in their search results.

    Source : http://sixrevisions.com/wordpress/optimizing-wordpress-for-search-engines/

    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>”;

    } ?>