Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Saturday, 25 June 2011

Mobile - Web development


Introduction

About 20 years ago, mobile phones were devices used by business men, sales representatives and Chief Executive Officers; Owning a mobile phone and paying outstanding bills was expensive.  In those days, having a mobile phone was an excessive luxury that not everyone could afford. On the other hand, these devices were huge, and to carry the device was a burden.
Things change, and nowadays mobile phones are everywhere. Not only because bills are cheaper, I think the introduction of Multimedia and cool applications made mobile phones popular.
Internet is everything, news, friends on Facebook, emails and study materials. These goodies were only accessible from a personal computer a few years ago. Today everything is in the palm of our hands. Mobile phone can connect to the Internet, can view emails, has built in GPS and much much more. And yes you can still make phone calls.
In this week’s blog, I will design a mobile web page that can display your exact location using GeoLocations.

About GeoLocation

The GeoLocation API functions are used in web applications to find the geographic location of an object. In simple terms, using this API, a web application can request and find the exact position in terms of Longitude and Latitude of a client accessing the application.
Such technology, is used in a myriad of travelling  web sites; web pages can display nearby restaurants and interesting places to visit. On the other hand, organisations are using this technology to keep track of mobile phones, other devices and travelling employees.
In the old days, when you visit a foreign country for the first time you had to carry a map; surprise, maps are not updated. Today, the only tool that you need is a mobile phone. Locations are updated 24/7, suggested routes are one click of a button and if you’re lost you can always make a phone call and give your exact location to the recipient.
At first glance, this technology sounded complex but when I searched a bit on the Internet I found out that the Geolocations API has a lot of build in functions that can be easily implemented.

The environment

Before going into much detail on how to do this task, I downloaded the Opera Mini emulator.This emulator enables you to test mobile web pages on your personal computer. The emulator is easy to use and the pre-defined list of mobile brands enables you to test your web page on specific mobile devices.
You can choose one of the pre-defined brands and if your mobile is not in the list you can build a custom mobile. Although the emulator uses the host computer Internet connection you can still launch web pages located on your host. This enables you to test web pages that are not yet published on the Internet.

Interface

The web application is divided in the following sections:
  • A section that displays the user location
  • A link that opens the respective Google map
  • A section that displays stored locations
Using HTML markup I added some <div> and <span> tags and designed the following interface:
When the web page is launched, using a JavaScript timer, the user location will update every second. The Start and Stop buttons are used to start and stop the timer respectively. To store the current location, users must click the Record button, and once clicked, the location is added in the Recorded locations section.

Scripting

To check compatibility, I used the following JavaScript If statement:
If the GeoLocation is not installed or not supported, this syntax displays the following error message:
The navigator functions, enables you to construct a position object containing the user exact location. The following function, creates a new instance of the navigator object:
The navigator will call the following functions:
  • userLocated - This function is called when a location is obtained
  • locationError- This function is called when an error occurs
The userLocated function is used to get and display the user current position. In lines 28 to 20, the latitude, longitude and the time stamp are stored in three global variables.
Using the document.getElementById() and the innerHTML() functions, in lines 33 to 35 the values are displayed in the respective <span> tags.
In lines 38 and 39, the google map hyperlink is constructed using the latitude and the longitude retrieved.
When a location is updated, users can click the Record button to add their current location to the Recorded locations list. The following function is used:
When this function is called, the increment variable is incremented by one; this is used to display the location number. Using paragraph tags, the latitude, longitude, time stamp and google map link are added to the respective <div> tag.
I created a timer that will call the readLocation() function every one second as follows:
To start and stop the timer, I added the following <Input> buttons with the following syntax:

Implementation

Once my project was complete, I tested the web page using the opera mini emulator and some mobiles (Android and Windows). The following screenshots shows the result.
1- Load web page in Opera-mini emulator.
2- Load Google map from the provided link. 
 3- Record client location.
4- Load page using Google Chrome. 
5- View Google map from Google Chrome. 
6- Launch web page from iPhone online emulators. 

Conclusion

To test this application from mobile devices I registered with a free web hosting service and my web page can be accessed from http://omarz.comlu.com/projects/gpsloc/gpsloc.html.
Developing mobile web pages and mobile applications is an interesting and challenging task. I think one of the major difficulties is compatibility; various brands, various browsers. Developers can download emulators to test their mobile web pages.
While I was searching for emulators, I found the Android SDK. This SDK includes all the required libraries and an emulator to develop and test Android applications; I’m very tempted to try some stuff.
Happy coding...

Monday, 11 April 2011

Introduction to PHP

Introduction


When using server side scripting to generate and create dynamic web pages, all requests sent by a client machine are processed on the server. The server generates pages according to the user requests and sends these pages as a response. The internet browser on the client machine will interpret the response and display the output.  
One of the most commonly used scripting languages is PHP Hypertext Pre-Processor, also known as PHP. Un-like other scripting languages, PHP was designed and developed for web development; In-fact PHP scripting can be embedded within plain HTML markup.
Similar to other scripting languages, PHP has many built-in functions and can be used to perform most of the tasks required in web development. Amongst others, PHP can be used to process user inputs, interact with databases, and file handling on the server side and much more.
Un-like JavaScript, PHP is more secure because it resides on the server. This means that the scripting code cannot be viewed or modified by end users.
In this blog I will describe my experience and what I’ve learned while performing a task assigned by my tutor.

PHP syntax


PHP page

A PHP scripting page can be made up of both HTML markup and the PHP script. All PHP scripts are enclosed in <?php and  ?> tags and each file must have a .php extension. The following example shows some PHP scripting within an HTML <body> tag:

<body>
<?php
            //Display some text using echo()
            echo("Welcome to PHP scripting.". "<br>");
            echo("Today is ".date("l F d, Y"));
?>
</body>

Commenting

Like any other programming language, it is recommended to use inline and block commenting. PHP inline comments start with ‘//’ or ‘#’. The following example shows some inline comments:

//Display some text using echo()
echo("My name is Omar");  //Display name
echo("My surname is Zammit");  #Display surname

When a comment is made up of multiple lines, PHP enables you to add block comments. Block comments are enclosed between ‘/*’ and ‘*/’. The following is an example of a block comment:
/*
PHP is a scripting language that runs on the Server.
To write text to an HTML page use echo() or print().
Variables start with a dollar sign '$'.
*/

Always remember, a well documented block of code can be easily understood and maintained.

Variables

Similar to JavaScript, the PHP scripting syntax is case sensitive and variables are ‘loosely typed’; no need to declare and specify the data type.
Variables start with the dollar symbol ‘$’. The PHP parser allocates some memory when a variable is encountered for the first time. The memory size changes according to the data assigned to the variable. The following example shows different variables:

$name = "Omar";
$age = 31;
$male = true;
$today = date("Y/m/d");

Constants

Constants are fixed values that do not change during the execution of a program. In PHP such values are declared using the define(<Constant name>,<Constant value>). The following example shows an example:
In line 2, the currency rate is stored in a constant variable euro. Line 3 declares a new variable ($MalteseValue) and a value of 100. Line 4 is calculating and displaying the euro equivalent.

Decisions and iterations

Decisions in PHP can be achieved using the if-else and switch-case statements. Similar to other programming languages, if statements enable you to combine multiple conditions to add ranges, the syntax for an if-elseif-else statement is as follows:

if(<Condition 1>)
{
//If the Condition 1 returns true, execute code within this block.
}elseif (<Condition 2>) {
//If Condition 2 returns true, execute code within this block.
}else{
            //If all conditions return false, execute code within this block.
}

When comparing a single value with a pre-defined list, a faster approach is the switch-case. Switch enables you to compare with a list of numbers or strings, but un-like if, ranges are not supported.

Switch(<Variable>)
{
            case 1:
                                          //Do something if Variable is 1
                        break;
case 2:
                                          //Do something if Variable is 2
                        break;
case 3:
                                          //Do something if Variable is 3
                        break;
            default:
//Do something if Variable is not 1,2 or 3
}

The for-loop is used to iterate a block of code, when the number of repetitions is known. The for-loop is structured as follows:

for(<Initial value>; <Stop condition>; <Counter update>)
{
//Each iteration, execute the code in this block
}

When the number of iterations depends on a condition, the while-loop can be used. The syntax is as follows:

while(<Condition>)
{
//Repeat this block while the condition is true.
}

An alternative to the while-loop is the do-while. The main difference is that when using a do-while, the code block is always executed at least once.

do
{
//Repeat this block if the condition is true.
}while(<Condition>)

Arrays

An array is a list of elements contained in one variable; each element is made up of an index and a value. The following example shows how an array of strings can be declared:

$names = array();
$names[0] = "Omar";
$names[1] = "Christine";
$names[2] = "Eliza";

The index is enclosed within square brackets ‘[ ]’ and enables you to reference an array element. For example, to display the array elements:

echo($names[0]);
echo($names[1]);
echo($names[2]);

NOTE: Similar to other programming languages, in PHP, arrays start from zero.
You can loop through an array using one of the loop methods described previously, but the most efficient way is to use the foreach-loop. As the name implies, this loop iterates for each element in a collection. The following code shows a foreach looping through the $names array:

foreach($name as $single){
            echo($single);
}

NOTE: Each element is stored in a temporary variable ($single)
The following table shows some PHP built-in functions that can be used with arrays:
Syntax
Description
array_unshift(<Array name>,<element>,<…)
Add elements to the start of an array. Multiple elements can be added.
array_push(<Array name>,<element>,<…)
Add elements to the end of an array. Multiple elements can be added.
array_shift(<Array name>)
Remove an element from the start of an array.
array_pop(<Array name>)
Remove an element from the end of an array
sort(<Array name>)
Sort an array from lowest to highest.
shuffle(<Array name>)
Mix the elements in an array.
array_merge(<Array name>,<Array name>)
Merge two arrays in one array. This function returns a merged array.
array_slice(<Array name>,<start>,<end>)
Extract elements between the start and the end values.

Task Description


This blog describes my experience while performing a task assigned by my tutor. The task consists of the following stages:
     Verify that PHP is working on your web server.
     Create an associative array of user names and passwords and list the entire array in a table.
     Explain between the echo() and print() functions.

Task steps


Environment

To test and create PHP server side scripting, I will be using the environment described in my last blog. For more information, refer to XAMPP blog.

Test the PHP installation

To test if the PHP module in XAMPP is working on my server I performed the following steps:
1.    In my XAMPP installation htdocs folder, I created a PHP page (phptest.php) with the following script:

<body>
            <?php
                        echo("My PHP Module is working");
            ?>
</body>

2.    When accessing this page from the server (http://localhost/phptest.php) or from a remote client computer (http://<Server IP>/phptest.php), if PHP is working,  the following page should load:

Create tables dynamically

Example 1: Credentials from an array

The aim is to create an array with user accounts and display the accounts in an HTML table. To achieve this, I created a PHP page with the following code:
Line 3 is assigning a new array in variable $userarray. In lines 5 to 8, four items having different keys and values are being added to the array.
Lines 11 and 14 are using the echo(<String>) syntax to create the table HTML markup and the table headers respectively.
Line 17 is using the reset(<array>) function to move the array internal pointer to the first item in the array. The internal pointer enables you to iterate through an array using PHP build in functions.
The iteration is done in lines 19 to 21 using a while() loop and the each() function. The iteration, works as follows:
1.    The while(<condition>) will continue to iterate until the condition within the brackets is null.
2.    The each(<array>) returns the element indicated by the array internal pointer and moves the pointer to the next item. If there are no more items, the each(<array>) returns a null value and while(<condition>) will stop the iteration.
3.    The array item returned by the each(<array>) is stored in a variable $user. To be precise, this array item is another array of two items; the array key (Username) and the array value (Password).
4.    Line 20 displays the array key ($user[0]) and the array value($user[1]) into an HTML table row.
Line 24 is using the echo(<String>) to create the table HTML markup.
The following screenshot shows the output when launching the code described in this section. Please note that I added some CSS styles.

Example 2: Credentials from a text file

The aim is to collect a list of users from a text file and display the list into an HTML table. To achieve this, I created a PHP page with the following code:
Using the fopen(<File path>, <Mode>) the text file is loaded and stored in $file variable as read-only.
Lines 6 and 9 are using the echo(<String>) syntax to create the table HTML markup and the table headers respectively.
The iteration is done in lines 13 to 19 using a while() loop and the feof(). The iteration, works as follows:
1.    The while(<condition>) will continue to iterate until the end of file is reached.
2.    The feof() checks if the file pointer is located at the end of the text file. If yes, the feof() returns false and stops the while() iteration.
3.    In line 15, the fgets() gets the line indicated by the file pointer from the text file and moves the pointer to the next line. In addition, using the preg_split(<delimiter>, <String>) and the tab as a delimiter, the line is split in two and stored in an array ($SingleUser).
4.    Line 18 displays the user name ($SingleUser[0]) and the password ($SingleUser[1]) into an HTML table row.
In line 20, the text file is closed using the fclose().
Line 25 is using the echo(<String>) to create the table HTML markup.
The following screenshot shows the output when launching the code described in this section. Please note that I added some CSS styles.

Language constructs: print and echo

At first glance print() and echo() may seem the same, reason being that when used with some text they produce the same output.
Before analyzing the differences, one should be aware that both print() and echo() are Language constructs and not functions. The difference between a function and a Language construct is all in the interpretation process. In simple terms, when a function is parsed, the PHP parser first checks the syntax and then processes all the contents. Language constructs are more specific (base units) and the parser deals directly with such constructs without parsing.
NOTE: Other language constructs exist in the PHP scripting, amongst others; unset(), empty(), isset(), include(), require(),die().

Similarities

I created the following examples that shows how to use the print() and the echo() Language constructs and achieve the same results.

Example 1: Display text

print("Hello world!!");
echo("Hello world!!"); 

print "Hello world!!";
echo "Hello world!!";

Example 2: Using parameters with text

$name = "Omar";
$surname = "Zammit";
//The output is My name is Omar Zammit
print "My name is $name $surname";
echo "My name is $name $surname";

Example 3: Concatenating strings

print "My ". "name ". "is ". "Omar "."Zammit.";
print "My ". "name ". "is ". "Omar "."Zammit.";

Example 4: Using array values

$vars = array();
$vars[]="Hello";
$vars[]="World";
//The output is Hello World
print $vars[0]." ".$vars[1];
echo $vars[0]." ".$vars[1];

Differences

A difference I noticed while using these Language constructs is, echo() can display multiple parameters at once without using concatenation. When using the echo(), the following syntax is valid:

echo 'Please ', 'note ', 'that ', 'strings ', 'are ', 'parameters.';

Displaying syntax this way is much faster than the following concatenated equivalent:

echo 'Please '.'note '. 'that '. 'strings '. 'are '. 'parameters.';

NOTE: Passing multiple string parameters to a print() language construct is not supported.
Another difference between these Language constructs is, print() returns a value (always one) and can be used as a normal PHP function. When using print(), the following syntax is valid:
//This example prints Yes
((5+5) == 10) ? print 'Yes' : print 'NO'

NOTE: Using echo() in the same way is not supported.

Print or echo ?

To answer this question is a bit difficult, both are very similar and various sources state that it makes no difference which one is used. Some developers prefer echo() because it supports multiple parameters; faster than concatenation.

Conclusion


Having XAMPP installed helped me a lot to start quickly learning PHP. Following some tutorials from W3C schools and my coursework text book I managed to create some PHP pages. Comparing the time spend on other scripting languages I think that PHP it’s not difficult to learn.

Happy coding...