PHP: Hot Pages: Basic Code
- What is PHP?
- PHP: Hot Pages
- Your Favorite Color
- Dates and Times
- PHP code starts looking like HTML code and ends looking nothing like it. If you’ve looked at HTML code, you’ve seen things that look like “<em>” or “<h2>”. Here’s a simple web page:
- Basic Code: Functions
- At its most basic, PHP uses functions to get things done. The functions we just used are the “echo” function and the “date” function. The ‘echo’ function is simple. Whatever you give it, it ‘echoes’ to the web page. In this case, we gave it the ‘date’ function. The ‘date’ function (http://php.net/manual/function.date.php) returns the current date and time in whatever format you want. The format code we used was “h:i A”. This means we want the…
- Basic Code: Variables
- Rather than immediately echoing the results of functions, you can store them in containers for later use. These containers are called “variables” by programmers. If, for example, you were going to mention the time more than once on your web page, you might want to store the time in a variable and simply echo that variable everywhere on your page. Change the body of your web page to:
- Custom functions
- PHP allows you to create your own functions as well as use built-in functions like the “date” function. Let’s give impatient people the seconds as well as the hours and minutes of the current time. If someone has visited our page within the last minute, we’ll change the format code to show seconds.
- Finding errors
- There are two common ways of finding errors when a PHP web page doesn’t do what you expect.
- Line endings
- PHP’s errors are only useful if it can successfully tell you which line the error occurred on. Unfortunately, different operating systems determine what makes a line in different ways. Make sure that you are using the same line endings on both your workstation and your server. If your server is Unix, tell your text editor to use Unix line endings. Otherwise, the line that PHP tells you the error is on probably won’t be the line you see.
- Avoiding errors
- At regular times while programming a web page, use http://validator.w3.org/ to verify that your PHP code is generating valid HTML. Validation can often catch a small error before it becomes a big error.
- The Final Code
- Here is the final code we used for this section: