Home > Tags > Languages
Page 2

Pushing Updates to the Web Page with HTML5 Server-Sent Events

The HTML5 Server-Sent event model allows you to push realtime data updates from the server to the browser.

In this tutorial we will work through the process, with the EventSource object handling received data and writing it to the page. We will use HTML5 and JavaScript at client side, with PHP at server side.

With existing models such as AJAX, the code in a Web page would continually ask the server to supply new data, but the onus was on the client to request the information. With Server-Sent requests, you can stream data from your server, with updates pushed from there without the code at client side having to keep requesting it. Once your page initiates the Server-Sent event, the server script can continue sending updates. Your JavaScript code can write this new data into the page whenever it receives it.

Create an HTML5 Page

Create your HTML5 page as follows:

<!DOCTYPE html> <html> <head> </head> <body> </body> </html>

Add an Element to Display the Server-Sent Data

We will display the data received from the server in a dedicated page element, so add the following in the body section of your page:

<div id="serverData">Here is where the server sent data will appear</div>

You can put any content you like in your element, as long as it has an ID attribute so that you can identify it in your script. The placeholder text should only appear when the page first loads, but will disappear when the script runs.

Add a Script to the Page

Because we want the function to continue receiving and handling updates, we add the script section in the body of the page. Of course your own pages may execute functions on user interaction, but for the purposes of this demonstration add the following script at the end of your page, before the closing body tag:

<script type="text/javascript"> //functions here </script>

The script will execute when the browser renders the page, so the Server-Sent events will be initiated straight away. Next add the JavaScript code inside this script section:

//check for browser support if(typeof(EventSource)!=="undefined") { //create an object, passing it the name and location of the server side script var eSource = new EventSource("send_sse.php"); //detect message receipt eSource.onmessage = function(event) { //write the received data to the page document.getElementById("serverData").innerHTML = event.data; }; } else { document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events."; }

The script first checks that the browser supports the EventSource model. If it doesn’t, an error message is written to the server data page element instead. If the browser does support the function, the Server-Sent process begins. First, the script creates an object of the EventSource class, passing it the URL of the server side script that will be providing the streamed data updates. Then the script sets up an event listener function to execute when the EventSource object receives an update from the server. When this happens, the script simply gets a reference to the update page element and writes the new data to it.

Create a Server Side Script

We now need to create the server side PHP script to send updates to the page. Create a new file and save it “send_sse.php” or another name of your choice, as long as you amend the JavaScript EventSource code above to reflect the correct name and location. Enter the following outline in your PHP file:

<?php //streaming code ?>

Begin your PHP script by setting the headers as follows:

header('Content-Type:...
more →
MIke says: It's really horrible when you make a tutorial that is the #1 google result, and it isn't even correct. As stated in the...

PHP User Survey Part V: Administration Layer

In the last piece on our PHP online user poll, we look at the administrative service and how the site supervisor enters, deletes and manages the poll data.

The first poll administrative page checks if the administrator is logged in. You can choose from Session variables or Cookies to check the site administrator login status.

Once the application has confirmed the identity of the site administrator, the page lists the available polls.

The first step is to use the class methods and variables in the class.polls.php file:

<?php require_once("class.polls.php");

The next steps include instantiating the poll object and retrieving the poll data:

// instantiate polls class $oPolls = new polls; // get polls and poll count $aPolls = $oPolls->getPolls("created_dt desc", $iCursor); $iCnt = $oPolls->getPollsCount();

We create an array to hold and display the data from the polls table in the database:

// check for polls if (count($aPolls)) { // build page data array $i = 0; while ($i < count($aPolls)) { $aData[$i]["Id"] = $aPolls[$i]["Poll Id"]; $aData[$i]["Name"] = $aPolls[$i]["Question"]; $aData[$i]["Status"] = $aPolls[$i]["Status"]; $aData[$i]["Created"] =$aPolls[$i]["Created Date"]; ++$i; } }

For a given poll ID number, we can delete, activate or deactivate a selected poll:

// check for id if ($id) { // assign poll id $oPolls->setPollId($id); // check operation type if (!strcmp($op, "del")) { // try delete poll and redirect $oPolls->deletePoll(); header("Location: ".SELF); } elseif (!strcmp($op, "act")) { // try activate poll and redirect $oPolls->activatePoll();...
more →
Logo Design Contest says: Good to read about administration concept which makes an incredible changes in the environment of reputable firms.

PHP User Survey Part IV: Presentation Layer

So far in this series, we have developed the data layer (database tables) and the business layer (PHP methods) for manipulating the data.

In this piece, we will look at the presentation layer that is used to display the poll question and poll results.

The HTML header will check for the presence of a cookie (in case the user has voted previously) and refresh the page if it has timed out.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <? if (!empty($_COOKIE["cACCOUNT"])) { ?> <meta http-equiv="Refresh" content="<?php print TIMEOUT / 2 ?>; url=devdrivepoll.php" /> <? } ?> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Developer Drive Poll</title> </head>

We will include the file that pulls the poll data from the database tables:

<? require_once("class.polls.php"); // class functions for polls

We can now instantiate a new “polls” class and start pulling the active poll data:

// instantiate polls class $oPolls = new polls; // get poll data $aPoll = $oPolls->getActivePolls($iCursor); $iCnt = $oPolls->getPollsCount(true);

Since we are using the same page to display results as we are to show the form, we will check to see if the user has already voted and record their results.

if ($_POST) { // assign poll...
more →
Wojciech Soczyński says: This series is quite informative, but unfortunately it teaches new users some bad habits which they should avoid coding real...

Create Your Own CRUD App with MySQL and PHP

You’re may be wondering what exactly CRUD is.

CRUD simply stands for Create, Read, Update and Delete and it is the one of the fundamental principles of programming logic that can be expanded and applied to larger projects.

For example, let’s imagine we’re creating a social network and we like to have the ability for users to create accounts, edit and update information for those accounts and also delete said accounts; that is CRUD at work.

Now let’s get started using PHP & MySQL, to create an app that can store video game titles.

Create the Database

First let’s create a database named mygames to store our data. I’ll be using phpMyAdmin to take care of that but you can use any MySQL database management interface.

Refrain from using spaces or special characters when making names, also to ensure multi-language support change the database collation to utf-8_unicode_ci (case-insensitive).

Now that we have created the database we need to create a table that will have all the necessary fields to input and store our data. We’ll name the table videogames and give this table 7 fields.

The first field will be called id, this will be our unique identifier and will help us know which video game we’re editing, adding or deleting. The type is int(11), which basically means an integer with a length of 11 digits. The last thing we have to do for our id field is to make sure that Auto Increment (A_I) is checked, this function is self-explanatory.

Our second field is called title type will be varchar(255) meaning a string that won’t be longer than 255 characters. Also set the collation of this field to utf-8_unicode_ci.

The next field will be release_date, the only thing we’ll do for this field is set the type to date.

The fourth field, publisher will be a varchar(50) and the collation will be utf- 8_unicode_ci.

Field number five will be called system and this too will be varchar(50) and collation will be utf-8_unicode_ci.

The next field is rating where the type is int(1) and the default value will be 0.

Our final field is called num_players and the type will be int(2) with a default value of 1.

Connect to our Database

Our database is ready to properly store and sort information so just add some entries to your videogames table to give it some data to work with.

Next we need to create a folder for our project so in your local/remote server folder create a folder called mygames. In this folder make another folder called includes, and using the text editor of your choice create a blank PHP file in this folder and name it db.php.

Using this db.php file we will establish a connection between our PHP code and the database we just created. There are a couple of ways we can do this but the most easiest and reusable method in my mind is using a PDO (PHP Data Object). Using this method we can use the same file over and over again, needing only to change a couple things.

This is going to be the structure of our db.php file:

<?php $dbinfo = 'mysql:dbname=mygames;host=localhost'; $user = 'root'; $pass = 'root'; //If you need to change database information, just change values above. $db = new PDO($dbinfo, $user, $pass); $db->exec('SET CHARACTER SET utf8');

The first 3 lines are variables that store our database information (username, password etc.). These values are user specific, so they will change in your case whether you’re using XAMP, WAMP, MAMP or such the like.

The fourth variable $db is our connection to the database; our code will be using this variable to do everything in our code. The last line ensures that we can support all languages by setting the character set to utf8. Now we can go to our index.php file and start adding some code that will communicate with the database.

This is our PHP code block for the index.php page:

<?php require_once 'includes/filter-wrapper.php'; require_once 'includes/db.php'; $sql = $db->query('SELECT id, title, release_date, publisher, rating, system, num_players FROM videogames ORDER BY title ASC'); $results = $sql->fetchAll(PDO::FETCH_OBJ); ?>

The first line includes a filter wrapper, which I’ll explain more of what it does in part 2 of this tutorial. Depending on what version of PHP you have running on your server you may or may not need this but let’s keep it in there for now.

The second line includes our db.php file that we created earlier, so now on our index page is now connected with our database.

The third line is our query that we make to the database; we’re selecting all the entries in the database by their respective fields and sorting them by their title in alphabetical order.

Now that we have them selected we need to get them out of the database and store it somehow so we can display it on our index page.

Our last line of code takes care of that. Using the variable $results, we fetch all the entries from the database and they are stored in that variable. Think of the results variable receiving a box with all the entries from our database in there. The entries are stored in an array, which gives us the freedom to just display one by its unique identifier (id) or to just display them all.

In part two we’ll create the html needed to display our data and we’ll tackle editing, adding and deleting entries all within our app.

...
more →
Rodrigo de Almeida Rodriguez says: Hi! great tutorial! See http://crudin.smarc.com.br/en It´s a framework that generates in real time a complete CRUD system All...

Common Mistakes to Avoid When Coding in PHP

Despite the high expectations placed on them at times, developers are human. They were the last time we checked anyways.

As humans, we are bound to make mistakes from time to time. And simple, common mistakes often slip past our filters the more comfortable we become with something.

Think about it, when you first started writing code you most likely checked every line to make sure things were perfect. As you grow more comfortable with the process, little things often get overlooked and mistakes are made.

But knowing what these common mistakes are and how to avoid them can really help speed up the development process and keep our clients smiling.

Below you will see some of the more common mistakes that are made with PHP, even by advanced developers…

Poor Housekeeping

People can get lazy and code can get messy.

To keep it organized you can use things like comments and indents. I know, these are basic best practices but think to yourself, when was the last time you hacked up your code without commenting?

I thought so.

How about breaking your code into modules based on function? Many agree that as a rule of thumb your function should not exceed one page on your screen unless it is necessary.

Another good housekeeping practice is to backup all of your files before you upload changes. Sure you may be in a hurry, but the time it takes to make a quick backup is far less than having to go back and undo a disaster.

Forgetting Your Punctuation

One of the best things about PHP is that you don’t need expensive software to write code in. Any text editor will do.

Unfortunately, a basic text editor won’t tell you if something isn’t right.

One of the most common, and basic, mistakes made when coding in PHP is to either forget or misplace a quote, brace or semi-colon causing a syntax error. Before you try to run anything, make sure that every:

[ has a ] ( has a ) { has a }

Now check to make sure that all string keys are enclosed with matching quotes. Remember, “ does not match with ‘.

While you are at it, double check the semi-colons to make sure they aren’t missing or misplaced.

Forgetting to Validate Input

By now you should know that user provided data cannot be trusted. Allowing this from your users is one way that cross-site scripting, buffer overflows and injection flaws can all be used to attack your site. Unfortunately, it is also one of the most common mistakes people make when coding in PHP.

In the following lines of code, notice that the three variables are not validated:

$birthdate = $_GET['birthdate']; <br> $birthmonth = $_GET['birthmonth']; <br> $birthyear = $_GET['birthyear']; <br>

By adding the following lines of code we use preg_match to perform a regular expression match against the input. In our birthdate and birthmonth variables it is checking to verify that a one or two digit number between zero and nine was entered. For birthyear, it needs to be a four digit number between zero and nine:

if (!preg_match("/^[0-9]{1,2}$/", $birthdate)) die("That is not a valid date, please check that again."); <br> if (!preg_match("/^[0-9]{1,2}$/", $birthmonth)) die("That is not a valid month, please check that again."); <br> if (!preg_match("/^[0-9]{4}$/", $birthyear)) die("That is not a valid year, please check that again."); <br>

We are able to make sure that the proper type of characters are input by the users are actually numerals and only numerals that we expect to be entered. Anything else results in an error being thrown back to the user.

So I call on our readers to share with us some of the most simple mistakes we have made over the years. And don’t worry, we’re all human here.

...
more →
Andrew woods says: The preg_match function is part of a suite of functions that's use Perl compatible regular expressions. That's where the 'p' in...

Wrapping Your Head Around Canvas: Part 1

HTML5 is no longer a ‘way of the future ‘ as it is more common place now that most of us, if not all of us, are starting to implement it into the things we create.

One of the newest features that have most of you cooing, aside from the new video and audio tags, is Canvas. It has been dubbed a convenient replacement for the use of flash in the browser, and it translates well across multiple devices.

The name of the HTML tag sums up the basis of its implementation. Canvas provides a 2D drawing API for images, text, lines, shapes, and so on. At times it brings back memories of using MS Paint; I know I’m not alone in this sentiment when I see websites like canvaspaint.org.

The fact of the matter is when you dig down into it, you can do so much more with Canvas, and it could possibly be one of the biggest improvements to HTML.

You’re only truly limited by your understanding of the API and imagination. What you’ll be able to do at the end of this series will be up to you, but I hope that if this canvas series doesn’t help you most of everything about HMTL5 Canvas it will at least provide a springboard for you to dive deep into the API.

Let’s Begin with the Basics

Browser Support

One of the biggest questions facing us is of course browser support. Most browsers have been working on creating more modern versions to keep up with all of the new elements that HTML5 and CSS3 have introduced. Now even IE9 supports most if not all of the new technologies that drive these languages. Unfortunately for those of you that are stuck with using versions of IE like 6, 7, and 8, JavaScript may be more help in those situations. As a matter of fact, there is a JavaScript compatibility fix for IE8 called The ExplorerCanvas project. All you have to do is include the extra JS file before any of the canvas tags in your page. You can exclude this snazzy little piece of JS from the other browsers that already render Canvas by using conditional comments.

<!--[if IE]><script src="excanvas.js"></script><![endif]-->

Getting Started with Canvas

You would execute canvas as you would any other new HTML tag by using the <canvas> tag. The basic working size is 300px by 150px and will show up empty or invisible. It’s a good idea to put in some fallback content in case the browser does not support canvas.

<canvas id="yourCanvas" width="300" height="150"> I'm sorry you're browser doesn't seem to support Canvas at this time. </canvas>

Think of canvas like your new drawing pad and now that it is setup, we can begin to draw in that space. Keep in mind that when you are using canvas, you are not drawing on the canvas element itself, but instead you are drawing on the 2d context in which it renders. This would be where JavaScript API comes into play. You’ll find your canvas element by using getElementByID and then you can initialize the context that you would like. Remember to place your <script> tags either before or after, like so:

<script> var canvas = document.getElementById('myCanvas'); </script>

Then you can specify the context (ctx for short):

<script> var canvas = document.getElementById('myCanvas'); ctx = canvas.getContext('2d'); </script>

Now let’s build a simple rectangle after our context variable:

<script> var canvas = document.getElementById('myCanvas'); ctx = canvas.getContext('2d'); ctx.fillRect(0, 0, 150, 100); </script>

Congratulations! You just finished writing you first bit of canvas equivalent to the ‘hello world’ statement.

With that achievement notched in your HTML5 dev belt let’s take a closer look into the 2D API. Creating basic lines and shapes is what lies at the core of canvas, as you saw in the previous code above. Using the fillStyle or strokeStyle you can render the colors and strokes of the shapes more easily. When approaching the color values, keep in mind that they are the same as the CSS values rgb(), rgba(), and hsla().

So to draw a basic solid rectangle we would use fillRect, and use strokeRect to create the same rectangle with only borders. Easy right? I mean so far this all seems to be pretty straight forward. now let me introduce you to clearRect. You can implement this property to clear a portion of your drawn rectangle. Using the X, Y, width, and height properties can and will be used in all three of these methods below, you can even change your line thickness. Let’s take a look:

ctx.fillStyle = '#CCCCCC'; ctx.strokeStyle = '#000000'; ctx.lineWidth = 2;

Now let’s create our boxes:

ctx.fillRect (0, 0, 150, 50); ctx.strokeRect(0, 60, 150, 50); ctx.clearRect (30, 25, 90, 60); ctx.strokeRect(30, 25, 90, 60);

Paths

Creating paths is just as simple as creating basic shapes. Paths allow you to create custom shapes, the catch 22 is that you have to create the outlines, then you can add strokes, and finally add the fill. To get started with your custom shape you will use beginPath. The code isn’t too complicated to understand let’s draw a circle:

ctx.beginPath();...
more →
Mac says: Nice article. P.S. Animated Div's at top are nicce :)

Integrating AJAX with PHP Part I

AJAX earned its share of stardom once industry giants like Google Maps, Zoho Writer and Y!Mail Beta started to actively implement AJAX into their services.

Though many webmasters out there are already using AJAX yet there is that section which is still unaware of its advantages.

This tutorial will help the latter part enjoy hands-on experience with AJAX and PHP. I won’t be using jargons yet I am assuming that you understand the basics of HTML, PHP and JavaScript.

What is AJAX?

Well, AJAX won’t be new for those who understand JavaScript. AJAX stands for Asynchronous JavaScript and XML. Using AJAX programmer can use JavaScript code to get content from server machine without re-loading the complete webpage. Now you know how Google Maps load on the fly without any page re-loads?

Server sends data to client in XML format and client uses JavaScript to parse XML in order to perform the designated task. AJAX can be seamlessly integrated with PHP, Python, ASP (.NET), JSP and almost every other server-side technology.

What is our goal?

We will create a small Availability Checker application for a restaurant. User will enter the number of customers and the application will return if a table is available for that much number of customers. Breaking down Availability Checker:

index.php will be responsible for displaying a field which consumes data from user and send the same to our business logic for processing. myAJAX.php will receive data from index.php and process the same. If the input number is within the availability range then we return “Table Available!” otherwise we return “We are full!” as output. Lastly, please be aware that we won’t be processing XML anywhere throughout our code. We will dissect the usage of XML in some other tutorial.

Starting with index.html (instead of index.php)

<html> <head> <title>First ever Ajax application with PHP</title> </head> <body> <form name="ajaxform" method="get" action="#"> Table for  <input type="text" name="number" id="number" value="" />?<br /><br /> <input type="submit" value=" Available? " /> </form> </body> </html>

Above code displays an empty text field with a submit button. Please note that I have left the action attribute blank for now.

Moving on to myAJAX.php

<?php session_start(); // for starting a session header("Content-type: text/plain"); // Setting HTTP header for plain text $numbers= array( // this will be our list '1', '2', '3', '4' ); if (in_array($_GET['number'], $numbers)) { // if condition satisfied echo '1'; // results in true } else { // otherwise echo '0'; // results in false } ?>

myAJAX.php compares the input against a given set of numbers.

If the input numeral matches with any hardcoded number then it returns 1. Otherwise, it returns 0.

The JavaScript!

<script language="JavaScript" type="text/javascript"> <!-- var ajaxVariable...
more →
Salman Siddiqui says: Ahh!! Let me complete the second part of this series and then I will surely work on this idea IF my thought provoking brain helps...