Archive for July, 2010
Router
Thursday, July 29th, 2010
It can request the content of remote sites and show them as if it is content of the site serving the script.
The class rewrite URL of HTML page links so when the user clicks on them it makes the current site script access the respective remote page.
classes, rss
Classes | No Comments »
WordPress 3.0.1
Thursday, July 29th, 2010
After nearly 11 million downloads of WordPress 3.0 in just 42 days, we’re releasing WordPress 3.0.1. The requisite haiku:
Three dot oh dot one
Bug fixes to make you smile
Update your WordPress
This maintenance release addresses about 50 minor issues. The testing many of you contributed prior to the release of 3.0 helped make it one of the best and most stable releases we’ve had.
Download 3.0.1 or update automatically from the Dashboard > Updates menu in your site’s admin area.
Note: If you downloaded 3.0.1 in the first 20 minutes of release (before 2200 UTC), you’ll want to reinstall it, which you can do right from your Updates screen. Our bad.
rss
Uncategorized | No Comments »
WPE Arcade Script
Thursday, July 29th, 2010
WPE Arcade Script is a free PHP script with many nice features and an easy to use use install process. rss
Free PHP Scripts | No Comments »
TreeView
Wednesday, July 28th, 2010
It can generate HTML and Javascript to display a nested tree of folder that may contain entries with link to given URLs.
classes, rss
Classes | No Comments »
Lightweight MVC
Wednesday, July 28th, 2010
It provides based model, view and controller class that should be derived to implement new applications.
classes, rss
Classes | No Comments »
Incredible Services and Products
Wednesday, July 28th, 2010
Okay, okay; this may be a thank you posting for the wonderful sponsors of our massive HTML5 competition, however, it’s important for me to note that I refused to accept sponsors of any product that I didn’t honestly feel was fantastic. What this means is that, as the editor of Nettuts+, I fully endorse each and every one of the following services and products, and, in fact, use many of them on a daily basis! That’s why I asked these companies to sponsor the competition!
1. TechSmith
TechSmith has been extremely generous to Envato in the last few years. Luckily, that has no effect on the fact that the products they provide — everything from Camtasia Studio to Jing Pro, are amazing.
Did you know that I personally use their products every single day? When you watch screencasts from Nettuts+, they were recorded with Camtasia Studio for Mac. When I send out quickie videos and images, I use Jing Pro to distribute them on Twitter. Not only that, but they’re constantly updating their products, and support both Windows and Mac.
“We’ve stayed on top of the screen capture and recording game since the launch of Snagit nearly 20-years-ago.”
2. Media Temple
In addition to being my personal web host of choice, Media Temple is hugely respected around the web as being one of the premier web hosts. Whether hosting jQuery, or Starbucks, or even Django’s site, MediaTemple can handle the load! They come highly recommended.
“Media Temple hosts websites. Big and Small. For years we’ve taken complex technology and simplified it for the everyday website owner. Our products are designed to be powerful, affordable and relevant. Please take a look around; perhaps (mt) is a good choice for your next project.”
3. FormStack
Do we recommend FormStack? Well consider this; the submission form to enter the HTML5 competition…was created with FormStack. Their service is incredibly simple to use.
“Formstack’s easy form builder gives businesses and organizations an easy way to build any type of online form, integrate it with their website and begin collecting data. ”
4. Wufoo
At Envato, we use Wufoo as well. If you haven’t heard Chris, from CSS-Tricks praise Wufoo enough, let us assure you that their service comes with the highest recommendation from Nettuts+. I even use them on my own personal sites!
“What is Wufoo? Wufoo strives to be the easiest way to collect information over the Internet. Our HTML form builder helps you create contact forms, online surveys, and invitations so you can collect the data, registrations and online payments you need without writing a single line of code.
5. FusionCharts
FusionCharts has long been regarded as the premier solution for rendering animated graphs and charts for your business. Just browse through their various demos if you don’t believe me!
“FusionCharts v3 helps you create animated and interactive Flash charts for web and desktop applications. It livens up your applications by converting monotonous data into exciting visuals. “
6. Pagelime
We’ve published PageLime tutorials a couple of times on Nettuts+ recently. The huge advantage with their service is that zero coding is required on your part. This makes it significantly appealing to non-tech savvy folks. Most recently, they’ve launched a reseller program, as well as a new navigation manager.
“Pagelime is a brandable CMS that lets your clients manage their content. No installation, no coding to integrate, and no wasted time. Just add the cms-editable CSS class to any HTML element on your site and Pagelime does the rest.”
7. Campaign Monitor
There’s a reason why Facebook, Ebay, and Twitter utilize Campaign Monitor’s services: they’re the best! In fact, their email CSS guide has been proven to be a bible for me, when creating designs optimized for email. They even contributed a tutorial to Nettuts+ not too long ago on the state of CSS3 in email designs.
Send beautiful email campaigns, track the results, and manage your subscribers.”
8. Snippets
If you’ve watched my tutorials, you might have noticed a little scissors icon in my menu bar. That’s for Snippets. It’s an incredible code snippet management tool for Mac, that I use on a daily basis. Even better, it has support for Snipplr uploading — which Envato recently purchased!
“Snippets is a powerful application for Mac OS X that stores the most valuable pieces of code you can reuse in different projects many times.”
9. Querious
In need of a kick-ass MySQL database management app for Mac? I was, and Querious proved to be the best tool for the job. I use it often in my SQL-based video tutorials.
“Querious is a MySQL database management application written from the ground up for Mac OS X. Unlike mindless Mac OS X ports of applications originally made for Windows or Linux, Querious works the way you’d naturally expect it to as a Mac OS X app.”
10. Miva Merchant
Miva Merchant has been around for a long time, and is one of the top providers of e-commerce solutions on the web.
Miva Merchant is a leading supplier of e-commerce software and services to small and medium-sized businesses. We provide online merchants, developers, web designers and web hosts with the information and technology needed to be successful in today’s online selling environment.
11. Rockable Press
Envato’s publishing branch, Rockable Press, is in full force these days — especially with the release of our CEO’s newest book, “How to Build a Successful Blog Business,” which I’m currently reading through. To be objective…it’s fantastic.
“At Rockable Press, we produce simple, straight forward how-to guides and resources for web and creative professionals. We are a small web publishing outfit operated by Envato with authors based around the world. ”
12. jQuery Enlightenment
To this day, jQuery Enlightement holds the spot as my most recommended book on jQuery. Written by Cody Lindley, the book is succinct, and cuts out all of the fluff. As a result, you learn everything you need to know…as quickly as possible. Not only that, but he utilizes JSBin to provide clickable code examples for all of the demos. This has proven to be an extremely smart decision on his part, and you’ll surely see others adopting this same method in the future.
“jQuery Enlightenment was written to express, in short-order, the concepts essential to intermediate and advanced jQuery development. Its purpose is to instill in you, the reader, practices that jQuery developers take as common knowledge. Each chapter contains concepts essential to becoming a seasoned jQuery developer.”
13. WP Structure Theme
Chris Robinson is far and away one of the best authors on ThemeForest, and this theme is a perfect example of his talents.
“Months in development WP Structure is a highly flexible and heavily optioned premium theme, to be used for almost anything business, portfolio, blog, magazine & more!”
learn, php, rss, tutorials
PHP Tutorials | No Comments »
An AJAX Click to Appreciate Badge
Wednesday, July 28th, 2010
When you publish something online, there are not that many ways to determine whether people like what you have to say. Comments, the cornerstone of blogging, are too demanding, and users often prefer not to post one. If you’ve dropped by Behance, you’ve probably noticed their appreciate badge, which is a neat solution to this exact problem. With it people share their appreciation for somebody’s work.
Today we are implementing such a badge, which you can include in every page of your website with a bit of jQuery magic. So go ahead and download the zip from the button above (PSD included!) and continue with the tutorial.
The Database Schema
The script we are doing today uses two tables. The first holds one record for each of the pages which have the appreciate button enabled. The second one stores the IP of the person that voted along the unique ID of the page. This way we can easily determine whether the person has previously voted for the page and display the appropriate version of the button (active or disabled).

Table Schema appreciate_pages
The hash field holds an MD5 sum of the URL of the page. This way we add an UNIQUE index which will speed up the selects we run on the records, as well ensure there are no duplicate records in the table. The appreciated column holds the number of appreciations of the pages.

Table Schema appreciate_votes
The appreciate_votes table contains the IP of the person that has voted (in the form of an integer), and the id of the page from the appreciate_pages table. The timestamp is automatically updated to the current time when an insert occurs.
You can create these two tables by running the code from tables.sql in the SQL section of phpMyAdmin from the downloadable archive, part of this tutorial.
Step 1 – XHTML
Lets start with the XHTML part of the tutorial. The markup of the page is extremely simple. To have the appreciate button functioning, you just need to provide a container in which the button is inserted, and an optional element, which holds the total number of clicks on the button. You can safely omit the latter one, leaving you with only one div to code.
page.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>An AJAX Click To Appreciate Badge</title> <link rel="stylesheet" type="text/css" href="styles.css" /> <link rel="stylesheet" type="text/css" href="appreciateMe/appreciate.css"/> </head> <body> <div id="countDiv"></div> <div id="main"></div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> <script src="appreciateMe/plugin.js" type="text/javascript"></script> <script src="script.js" type="text/javascript"></script> </body> </html>
In the page above, you can see that I am including two stylesheet files. The first is styles.css, which is used to style the page, and appreciate.css, which is located in the plugin directory, and is responsible for the styling of the appreciate button.
Before the closing body tag, you can see that I also include the jQuery library from Google’s CDN repository, the plugin.js file and script.js, which uses the plugin to create the button on the page. You will only need to change the contents of script.js to make the script working on your pages.
Step 2 – PHP
PHP handles the database interactions and is on the backend of the AJAX requests. Most of the script logic is located in c script.php which you can see below. But first lets take a look at connect.php, which handles the database connection.
appreciateMe/connect.php
$db_host = 'localhost';
$db_user = 'YourUsername';
$db_pass = 'YouPassword';
$db_name = 'NameOfDB';
@$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
if (mysqli_connect_errno()) {
die('<h1>Could not connect to the database</h1>');
}
$mysqli->set_charset("utf8");
Up until now, we’ve always used the old mysql extension for database connections under PHP, as it is a bit easier to use and I wanted to keep the code compatible with PHP 4. However, with the recent announcement that WordPress (our favorite blogging engine) will be dropping support for that version of PHP, I decided that it is time to also make the switch to the new version – MySQLi (MySQL improved).
As you can see from the code above, the only major difference with the old way we connected to a database, is that here we create a MySQLi object instead of using the mysql_ functions. Also, as you will see in a moment, when we query the database a MySQL resource object is returned, which in turn has its own set of methods. This might sound intimidating, but it will become perfectly clear once you see it in action.
appreciateMe/script.php
/* Setting the error reporting level */
error_reporting(E_ALL ^ E_NOTICE);
include 'connect.php';
if(!$_GET['url'] || !filter_input(INPUT_GET,'url',FILTER_VALIDATE_URL)){
exit;
}
$pageID = 0;
$appreciated = 0;
$jsonArray = array();
$hash = md5($_GET['url']);
$ip = sprintf('%u',ip2long($_SERVER['REMOTE_ADDR']));
// $result is an object:
$result = $mysqli->query("SELECT id,appreciated FROM appreciate_pages WHERE hash='".$hash."'");
if($result)
{
list($pageID,$appreciated) = $result->fetch_row();
// fetch_row() is a method of result
}
// The submit parameter denotes that we need to write to the database
if($_GET['submit'])
{
if(!$pageID)
{
// If the page has not been appreciated yet, insert a new
// record to the database.
$mysqli->query("
INSERT INTO appreciate_pages
SET
hash='".$hash."',
url='".$mysqli->real_escape_string($_GET['url'])."'"
);
if($mysqli->affected_rows){
// The insert_id property contains the value of
// the primary key. In our case this is also the pageID.
$pageID = $mysqli->insert_id;
}
}
// Write the vote to the DB, so the user can vote only once
$mysqli->query("
INSERT INTO appreciate_votes
SET
ip = ".$ip.",
pageid = ".$pageID
);
if($mysqli->affected_rows){
$mysqli->query("
UPDATE appreciate_pages
SET appreciated=appreciated+1 WHERE id=".$pageID
);
// Increment the appreciated field
}
$jsonArray = array('status'=>1);
}
else
{
// Only print the stats
$voted = 0;
// Has the user voted?
$res = $mysqli->query("
SELECT 1 FROM appreciate_votes
WHERE ip=".$ip." AND pageid=".$pageID
);
if($res->num_rows){
$voted = 1;
}
$jsonArray = array('status'=>1,'voted'=>$voted,'appreciated'=>$appreciated);
}
// Telling the browser to interpret the response as JSON:
header('Content-type: application/json');
echo json_encode($jsonArray);
The script handles two different types of AJAX requests – read only request (which returns a JSON object with information about the number of appreciations of the page, and whether the current user has clicked the button), and write requests (which save the visitor’s vote to the database, and if necessary, save the page URL and hash as well).
As you an see in the code snippet above, one of the first things that the script does is to calulate the MD5 hash of the page. This is used as a unique key in the database, as URLs have unlimited length which is incompatible with MySQL’s UNIQUE keys. As an MD5 hash is unique for most practical purposes, we can safely use it in our selects and inserts, instead of the long URL addresses.
In the last line of the code, we convert the $jsonArray array into a valid JSON object with the inbuilt json_encode PHP function, and output it with a applicatoin/json content type.
Step 3 – jQuery
Inside the appreciateMe directory you can find the plugin.js file. You must include it in the page you wish to show the Appreciate button on. It uses AJAX to request data from the PHP backend and uses the response it receives to create the markup of the button.
appreciateMe/plugin.js
function(){
$.appreciateButton = function(options){
// The options object must contain a URL and a Holder property
// These are the URL of the Appreciate php script, and the
// div in which the badge is inserted
if(!'url' in options || !'holder' in options){
return false;
}
var element = $(options.holder);
// Forming the url of the current page:
var currentURL = window.location.protocol+'//'+
window.location.host+window.location.pathname;
// Issuing a GET request. A rand parameter is passed
// to prevent the request from being cached in IE
$.get(options.url,{url:currentURL,rand:Math.random()},function(response){
// Creating the appreciate button:
var button = $('<a>',{
href:'',className:'appreciateBadge',
html:'Appreciate Me'
});
if(!response.voted){
// If the user has not voted previously,
// make the button active / clickable.
button.addClass('active');
}
else button.addClass('inactive');
button.click(function(){
if(button.hasClass('active')){
button.removeClass('active').addClass('inactive');
if(options.count){
// Incremented the total count
$(options.count).html(1 + parseInt(response.appreciated));
}
// Sending a GET request with a submit parameter.
// This will save the appreciation to the MySQL DB.
$.getJSON(options.url,{url:currentURL,submit:1});
}
return false;
});
element.append(button);
if(options.count){
$(options.count).html(response.appreciated);
}
},'json');
return element;
}
})(jQuery);
The script basically creates a new method in the main jQuery object. This differs from the plugins that we usually do, in that this type of plugins are not called on a set of elements (no need to select elements). You can just call $.appreciateButton() while passing a configuration object as a parameter. This is exactly what we’ve done in script.js add a button to the page:
script.js
$(document).ready(function(){
// Creating an appreciate button.
$.appreciateButton({
url : 'appreciateMe/script.php', // URL to the PHP script.
holder : '#main', // The button will be inserted here.
count : '#countDiv' // Optional. Will show the total count.
});
});
The configuration object, which is passed as a parameter, has to contain a url and a holder properties, whereas count is optional. Notice that I’ve specified the path to script.php relatively, as appreciateMe is a child directory of the one the page is currently in.
However, if you plan to add the script to a site with a variable path structure, you should probably specify an absolute path. Either add a leading slash, or provide a complete URL with http://.
Step 4 – CSS
Now that we have all the markup and code in place, it is time to turn to the styling. The CSS rules that style the appreciate badge are located in appreciate.css. You could optionally copy these rules to your main stylesheet file, if you’d like to avoid the extra request, but beware that you will need to change the paths to the background images.
appreciateMe/appreciate.css
.appreciateBadge{
width:129px;
height:129px;
display:block;
text-indent:-9999px;
overflow:hidden;
background:url('sprite.png') no-repeat;
text-decoration:none;
border:none;
}
.appreciateBadge.active{
background-position:left top;
}
.appreciateBadge.active:hover{
background-position:0 -129px;
}
.appreciateBadge.inactive{
background-position:left bottom;
cursor:default;
}
There are three versions of the appreciate badge image. A default one, a hover one, and an inactive one. All three of these reside in the same file – sprite.png, one below the other. With this technique you can switch between the versions instantaneously by offsetting the background image of the hyperlink.
styles.css
#main{
margin:80px auto;
width:130px;
}
#countDiv{
color:#eee;
font-size:35px;
margin-right:120px;
position:absolute;
right:50%;
top:265px;
}
You can find the rest of the styles, which refine the looks of page.html, in styles.css. Only two sets of styles affect the appreciate button directly. The #main div, which contains the button and centers it on the page, and #countDiv in which the total number of appreciations is inserted.
With this our Click to Appreciate Badge is complete!
Conclusion
Before being able to run this script on your server, you first have to replace the MySQL credentials in connect.php with your own. Also, you will need to run the contents of tables.sql in the SQL tab of phpMyAdmin, so the two tables are created. Lastly, depending on your URL paths, you may have to change the URL property of appreciateMe/script.php in the script.js JavaScript File.
learn, php, rss, Tutorial
PHP Tutorials | No Comments »
CSS: Noob to Ninja – The Complete Video Series
Wednesday, July 28th, 2010
This exclusive premium video series will take you from a state of absolute CSS “noobness,” all the way up to ninja-status, capable of taking advantage of the latest CSS3 techniques. The series begins with the basics: the syntax, properties, etc. However, each new video expands upon the previous, as you work your way up and improve your skills. In this final week, you’ll complete the series, as you gain access to Parts 8-12: five new episodes.
In these final video tutorials, you’ll learn about a variety of CSS3 techniques, how to use custom fonts, working with CSS frameworks, and how to extend CSS with applications like LESS. Don’t fall behind! Become a Premium member!
The Full Screencast Series: Exclusive to Premium Members
- Part 1: Preparation
- Part 2: CSS Properties
- Part 3: Typography
- Part 4: Floats
- Part 5: Positioning
- Part 6: Semantics, List Items, and Menus
- Part 7: CSS Organizational Techniques
- Part 8: Rounded Corners, Box Shadows, and Text Shadows
- Part 9: CSS3 Gradients
- Part 10: Custom Fonts with @font-face
- Part 11: Taking Advantage of CSS Frameworks
- Part 12: Extending CSS with LESS

Join Net Premium

For those unfamiliar, the family of TUTS sites runs a premium membership service. For $9 per month, you gain access to exclusive premium tutorials, screencasts, and freebies from Nettuts+, Psdtuts+, Aetuts+, Audiotuts+, and Vectortuts+! For the price of a pizza, you’ll learn from some of the best minds in the business. Become a Premium member!
learn, php, rss, tutorials
PHP Tutorials | No Comments »
Start Using HTML5 WebSockets Today
Wednesday, July 28th, 2010
One of the cool new features of HTML5 is WebSockets, which let us talk to the server without using AJAX requests. In this tutorial, we’ll review the process of running a WebSocket server in PHP, and then building a client to send and receive messages to it over the WebSocket protocol.
What are WebSockets?
WebSockets is a technique for two-way communication over one (TCP) socket, a type of PUSH technology. At the moment, it’s still being standardized by the W3C; however, the latest versions of Chrome and Safari have support for WebSockets.
What do WebSockets Replace?
Websockets can replace long-polling. This is an interesting concept; the client sends a request to the server – now, rather than the server responding with data it may not have, it essentially keeps the connection open until the fresh, up-to-date data is ready to be sent – the client next receives this, and sends another request. This has its benefits: decreased latency being one of them, as a connection which has already been opened does not require a new connection to be established. However, long-polling isn’t really a piece of fancy technology: it’s also possible for a request to time-out, and thus a new connection will be needed anyway.
Many Ajax applications makes use of the above – this can often be attributed to poor resource utilization.
Wouldn’t it be great if the server could wake up one morning and send its data to clients who are willing to listen without some sort of pre established connection? Welcome to the world of PUSH technology!
Step 1: Get the WebSocket Server
This tutorial will focus more on the client building rather than server implementation.
I’m using XAMPP on Windows 7 to run the PHP server locally. Grab a copy of phpwebsockets which is a WebSocket server in PHP. (Note: I experienced some problems with this version, I made some changes to it and will including it in the source files) There are various WebSocket implementations; if one doesn’t work, you can try another or just continue with the tutorial.
- jWebSocket (Java)
- web-socket-ruby (ruby)
- Socket IO-node (node.js)
Start the Apache server

Step 2: Change URLs and Ports
Change the server according to your setup, for example in setup.class.php:
public function __construct($host='localhost',$port=8000,$max=100)
{
$this->createSocket($host,$port);
}
Browse through the files and make changes where appropriate.
Step 3: Start Building the Client
Lets get a basic template up; this is my client.php file:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>WebSockets Client</title>
</head>
<body>
<div id="wrapper">
<div id="container">
<h1>WebSockets Client</h1>
<div id="chatLog">
</div><!-- #chatLog -->
<p id="examples">e.g. try 'hi', 'name', 'age', 'today'</p>
<input id="text" type="text" />
<button id="disconnect">Disconnect</button>
</div><!-- #container -->
</div>
</body>
</html>
So in this code we’re creating a simple template: we have a box for the chat log, an input box, and one disconnect button.
Step 4: Add Some CSS
Nothing fancy, just space some elements out.
body {
font-family:Arial, Helvetica, sans-serif;
}
#container{
border:5px solid grey;
width:800px;
margin:0 auto;
padding:10px;
}
#chatLog{
padding:5px;
border:1px solid black;
}
#chatLog p {
margin:0;
}
.event {
color:#999;
}
.warning{
font-weight:bold;
color:#CCC;
}
Step 5: WebSocket Events
First, let’s try and understand the idea of WebSocket events.

The Events
We’ll be using three events:
- onopen: When a socket has opened
- onmessage: When a message has been received
- onclose: When a socket has been closed
But how can we implement this?
First create a WebSocket object
var socket = new WebSocket("ws://localhost:8000/socket/server/startDaemon.php");
And checking for events is as simple as:
socket.onopen = function(){
alert("Socket has been opened!");
}
But what about when we receive a message?
socket.onmessage = function(msg){
alert(msg); //Awesome!
}
However, let’s avoid using alert boxes, and actually integrate what we’ve learned into the client page.
Step 6: JavaScript
Ok, so let’s get started. First we put our code in jQuery’s document ready function, then we check whether the user has a WebSockets-enabled browser. If they do not, we append a link to Chrome in the HTML.
$(document).ready(function() {
if(!("WebSocket" in window)){
$('#chatLog, input, button, #examples').fadeOut("fast");
$('<p>Oh no, you need a browser that supports WebSockets. How about <a href="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');
}else{
//The user has WebSockets
connect();
function connect(){
//the connect function code is below
}
});
As you can see, if the user has WebSockets then we call a connect() function. This is the core of the functionality: we’ll start with the open, close and receive events.
We’ll define the URL of our server
var socket; var host = "ws://localhost:8000/socket/server/startDaemon.php";
Wait, where’s the http in that URL? Oh right, it’s a WebSocket URL, so it’s using a different protocol. Here’s a breakdown of the pieces of our URL:

Let’s continue with our connect() function. We will put our code within a try/catch block; so if something goes wrong, we can let the user know. We create a new WebSocket, and pass the message to a message function which I’ll explain later. We create our onopen, onmessage and onclose functions. Note that we also show the user the socket status; this is not necessary, but I’m including it here as it can be helpful for debugging.
- CONNECTING = 0
- OPEN = 1
- CLOSED = 2
function connect(){
try{
var socket;
var host = "ws://localhost:8000/socket/server/startDaemon.php";
var socket = new WebSocket(host);
message('<p class="event">Socket Status: '+socket.readyState);
socket.onopen = function(){
message('<p class="event">Socket Status: '+socket.readyState+' (open)');
}
socket.onmessage = function(msg){
message('<p class="message">Received: '+msg.data);
}
socket.onclose = function(){
message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
}
} catch(exception){
message('<p>Error'+exception);
}
}
The message() function is fairly simple, it takes in some text that we want to show the user and appends it to the chatLog. We create the appropriate class for paragraph tags in the socket event functions which is why there is only one closing paragraph tag in the message function.
function message(msg){
$('#chatLog').append(msg+'</p>');
}
So Far…
If you’ve been following up to this point, well done! We’ve managed to create a basic HTML/CSS template, create and establish a WebSocket connection and keep the user updated as progress was made with the connection.

Step 7: Sending Data
Now rather than having a submit button, we can detect when the user presses return on their keyboard, and run the send function. The ’13′ you see below is the ASCII key for the enter button.
$('#text').keypress(function(event) {
if (event.keyCode == '13') {
send();
}
});
And here’s the send() function:
function send(){
var text = $('#text').val();
if(text==""){
message('<p class="warning">Please enter a message');
return ;
}
try{
socket.send(text);
message('<p class="event">Sent: '+text)
} catch(exception){
message('<p class="warning"> Error:' + exception);
}
$('#text').val("");
}
Remember what you see above may be a chunky bit of code, but in reality, the code we really need is:
socket.send(); //Thanks JavaScript
The extra code is doing a number of things: detecting if the user didn’t enter anything but still hit return, clearing the input box, and calling the message functions.
Step 8: Closing the Socket
Closing the socket is fairly straightforward: attach a click handler to our disconnect button and we’re done!

$('#disconnect').click(function(){
socket.close();
});
The Completed JavaScript
$(document).ready(function() {
if(!("WebSocket" in window)){
$('#chatLog, input, button, #examples').fadeOut("fast");
$('<p>Oh no, you need a browser that supports WebSockets. How about <a href="http://www.google.com/chrome">Google Chrome</a>?</p>').appendTo('#container');
}else{
//The user has WebSockets
connect();
function connect(){
var socket;
var host = "ws://localhost:8000/socket/server/startDaemon.php";
try{
var socket = new WebSocket(host);
message('<p class="event">Socket Status: '+socket.readyState);
socket.onopen = function(){
message('<p class="event">Socket Status: '+socket.readyState+' (open)');
}
socket.onmessage = function(msg){
message('<p class="message">Received: '+msg.data);
}
socket.onclose = function(){
message('<p class="event">Socket Status: '+socket.readyState+' (Closed)');
}
} catch(exception){
message('<p>Error'+exception);
}
function send(){
var text = $('#text').val();
if(text==""){
message('<p class="warning">Please enter a message');
return ;
}
try{
socket.send(text);
message('<p class="event">Sent: '+text)
} catch(exception){
message('<p class="warning">');
}
$('#text').val("");
}
function message(msg){
$('#chatLog').append(msg+'</p>');
}
$('#text').keypress(function(event) {
if (event.keyCode == '13') {
send();
}
});
$('#disconnect').click(function(){
socket.close();
});
}//End connect
}//End else
});
Step 9: Run the WebSocket Server
We will need command line access. Luckily, XAMPP has a handy shell option. Click ‘Shell’ on the XAMPP control panel, and type in:
php -q path\to\server.php
You have now started a WebSocket server!

Finished
When the page loads, a WebSocket connection will attempt to be established (try editing the code so the user has connect/disconnect option). Then, the user can enter messages and receive messages from the server.

That’s it!
Thanks for reading; I hope you enjoyed this tutorial! Remember, as exciting as WebSockets may be, things may change. You can refer here to keep up to date on the W3C WebSocket API.
learn, php, rss, tutorials
PHP Tutorials | No Comments »
XML-RPC Client
Tuesday, July 27th, 2010
It can send HTTP requests to a given XML-RPC server to call a function passing given parameters.
The class supports calling servers that require basic HTTP authentication.














