Intro
This tutorial shows how to greet your visitors depending on what time of day it is. If it's morning, it greets your visitor with "Good Morning!" If it's afternoon, it greets them with "Good Afternoon!" Magic? Noooo! Just PHP!
Getting started
We will start by looking at the entire script and then dissecting it afterward.
<?php
//Here we define out main variables
$welcome_string="Welcome!";
$numeric_date=date("G");
//Start conditionals based on military time
if($numeric_date>=0&&$numeric_date<=11)
$welcome_string="Good Morning!";
else if($numeric_date>=12&&$numeric_date<=17)
$welcome_string="Good Afternoon!";
else if($numeric_date>=18&&$numeric_date<=23)
$welcome_string="Good Evening!";
//Display our greeting
echo "$welcome_string";
?>
Now, Im going to break it down to you like this:
In lines 4 and 5, we define the two main variables that we will be using throughout the rest of the script. We define $welcome_string as "Welcome!" just in case anything were to go wrong in the script. We define $numeric_date as date("G"). Why "G" you ask? G is the universal variable in the date() function for 24 hour time (You can find the other universal time/date variables in the time/date tutorial found here). We want the 24 hour time (military) so that we can tell what time of day it is so we can greet our viewers properly.
Now that we have grabbed our time and set it to the variable "$numeric_date", we need to set our conditions for displaying which greeting. In lines 8 and 9, we use PHP to say is the 24 hour time is greater than or equal to 0 and less than or equal to 11, modify $welcome_string to be equal to "Good Morning!." This is because any time between or during 11, it is still morning time.
Lines 10 and 11 are done the same as 8 and 9, except this time, we are aiming for times between 12 and 17, since this is the afternoon time. It also sets $welcome_string to "Good Afternoon!"
Lines 12 and 13 do the same as 8-11, except aim for times between 18 and 23 and sets $welcome_string to "Good Evening!"
Now that we have set up our conditions for displaying what greeting, we need to display our greeting. That's why we have line 12. We echo $welcome_string, which has been set by our conditions to whichever greeting is needed for the time of day.
Now that you understand what goes on in the script, put the script in its' entirety into a file of its' own named welcome_script.php. Now go to whatever place in your code that you want the greeting to be shown and include welcome_script.php. If you don't know anything about includes, check out my tutorial on includes here. If you don't want to learn about includes, or just plain don't want to include it (both of which I don't know why you wouldn't want to do), then you can just insert the script itself into the part of your website code where you want it to be displayed.
Enjoy!:o