PHP HelpPHP Help

Online Community that helps beginners learn PHP,
and webmasters solve PHP coding problems

since 1999

Introduction to PHP Programming

Dynamic Content

I'm sure you're interested in doing more with PHP than saying hello to the world. Otherwise, you probably would not be here reading about an HTML-embedded scripting language. You want a script that does something useful. Let's go deeper into PHP by writing a Tip of the Day script. It will introduce several new functions and concepts, but you do not have to understand them all at once. It also offers an introduction to working with the file system.

$tiplist file("");
$ntips sizeof($tiplist);
$rtip rand(0,$ntips-1);
$tip $tiplist[$rtip];

The first line of the script opens a file called (remember, Unix does not care about so-called "file extensions" found in Windows, so we don't need ".txt" at the end to identify it as a text file). There is no need to write anything to the file because we will just be reading and displaying a line of text from it. Using the file() function, each line of the file is read into the array $tiplist. We do not have to specify any file handles because the file() function takes a filename as an argument and returns an array as a result.. Each element of the array corresponds to a line of the file. The newline character is still attached to each string in the array. The tips file contains several tips, each on a line.

Next, we find the number of elements in the tips list array by using the sizeof() function. It returns the number of elements in an array. The following line generates a random number between zero and the number of tips read from the tips file. rand(n,m) returns a random number between n and m (we must specify a range between 0 and 3 if there are 3 tips because the range is inclusive). Because PHP arrays start a zero, we set our random number to between zero and the number of tips minus one. The randomly generated number is used as an index into the tips list. The script randomly selects a tip from the list using this index. The text of the selected tip is then output to the browser through the echo() function. Since we already have the string in a variable, we don't need any quotes around it.

This script nicely illustrates the PHP philosophy of working within the what is called "the HTML-context." If you notice, the script is inside the HTML code, and that the script is a web page that can be placed anywhere on the site. Because PHP scripts generate output after a "Content-type: text/html" MIME header is output to the browser, any output they generate will appear in the browser window. This also allows PHP code to be directly mixed with HTML code on the page. A special cgi-bin is unnecessary for PHP scripts.

Pages:  1   2   3   4Related Forum Topics   |   More Tutorials »

Copyright © 2018