Problem: Write a php script to display welcome message
Solution: Here’s a simple PHP script that displays a welcome message
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <!DOCTYPE html> <html> <head> <title>Welcome Message</title> </head> <body> <?php echo "<h1>Welcome!</h1>"; ?> </body> </html> |
This script starts with a standard HTML document structure and uses PHP tags to embed a PHP script that outputs a welcome message in an h1
heading element. When run on a web server with PHP installed, this script will display the text “Welcome!” on the page.
Here’s an updated version of the script that includes a dynamic greeting based on the current time:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <!DOCTYPE html> <html> <head> <title>Welcome Message</title> </head> <body> <?php date_default_timezone_set("UTC"); $hour = date("G"); $greeting = ""; if ($hour >= 0 && $hour < 12) { $greeting = "Good morning"; } elseif ($hour >= 12 && $hour < 17) { $greeting = "Good afternoon"; } else { $greeting = "Good evening"; } echo "<h1>$greeting!</h1>"; echo "<h1>Welcome!</h1>"; ?> </body> </html> |
In this script, we use the date
function to get the current hour in a 24-hour format. We then use an if-else statement to determine the appropriate greeting based on the current hour and set the value of the $greeting
variable accordingly. Finally, we use two echo
statements to output the greeting and the welcome message on the page.
Here’s an extended version of the code that includes a personal message based on the user’s name:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <!DOCTYPE html> <html> <head> <title>Personalized Welcome Message</title> </head> <body> <?php date_default_timezone_set("UTC"); $hour = date("G"); $greeting = ""; if ($hour >= 0 && $hour < 12) { $greeting = "Good morning"; } elseif ($hour >= 12 && $hour < 17) { $greeting = "Good afternoon"; } else { $greeting = "Good evening"; } $name = ""; if (isset($_GET["name"])) { $name = $_GET["name"]; } echo "<h1>$greeting, $name!</h1>"; echo "<h2>Welcome to our website!</h2>"; ?> </body> </html> |
In this version of the code, we added a check to see if the name
parameter has been passed in the URL (e.g. http://example.com?name=John
). If it has, we retrieve the value of the name
parameter using the $_GET
superglobal array and store it in the $name
variable. Then, in the final two echo
statements, we use the $greeting
and $name
variables to personalize the welcome message for the user.