Open your text editor, and type the following script;
<html>
<head>
<title>Time and Date </title>
</head>
<body>
<h1>
<?php
echo 'Today\'s time and date is: ';
echo date('H:i, jS F Y');
?>
</h1>
</body>
</html>
Save your file as today.php and publish it to your webserver. If you are using your machine to host locally, then you need to copy the file to the web server folder that contains web pages. If you are using IIS then copy the file today.php to the folder c/inetpub/wwwroot.
To view the file, open your web browser and type http://localhost/today.php.
To see the result click here
How Does the Script Work?
The first echo statement
echo 'Today\'s time and date is: ';
Will simply echo or write the words inside the single quote marks. That means this text will end up in the source code of our page. This means that wher we place our php script is very important. This script is contained inside the <h1> ...</h1> tags. It will end up as a large heading in the final page displayed by the browser.
Note the backslash in the word 'Today\s' This word contains a single quote mark used as an apostraphe. This could cause the echo statement to think it has reached the end of the words is supposed to write. The baclslash tells php that this is in fact a character we want to display, not a special control code. This is called escaping a character.
Using the Date() Function
The Date function used here adds dynamic data to the page. What date or time is displayed depends on when the page is accessed. The date function can present the time in a number of different formats, and the characters within the brackets are used to determine the format. H is the hour in a 24 hour format, I is the minutes, j is the day of the month, S is the suffix (the ‘th' in 26th), F is the month written in full, and Y is the year in 4 digit format (i.e. 2005) . For extra formatting a colon (:) has been added between the hours and minutes values, and a comma after the minutes values (H:i;). The other parts of the time and date are simply separated by spaces. There are other ways to display the date; check here for a full list.
When php runs the script the first echo statement will return
Today's time and date is:
And the second will return
16:42, 20th May 2005
So after the PHP code has been executed the page will now look like this;
< html >
< head >
< title >Time and Date </ title >
</ head >
< body >
< h1 > Today's time and date is: 16:59, 31st May 2005</ h1 >
</ body >
</ html >
All the PHP code has disappeared, and has been replaced by the output of the two echo statements. Because we put out php code in between two <h1> ...</h1> tags the result was formatted as heading 1.
