PHP shoutbox task

Bizarrely enough, I recently started teaching topic #1 on the OCR AS ICT F452 module. The specification clearly isn’t design to be taught from beginning to end, and in fact I’ve found I jumped all over the place trying to teach it. We started off by looking at interface design principles using HTML and CSS, given that we have so far only attempted command line Python interfaces, and I have yet to find an interface package for Python that would be suitable for a 17 year old to use – any ideas on this gratefully received? (I have tried Tkinter and wxpython with no joy.) I then thought back to a very old piece of programming my friend @natbat did at university – a shoutbox – and here was the perfect opportunity to teach writing to files too!

In case you are not familiar with PHP, it is a server side language which processes your code and produces a static HTML page as a result. This means you need to run it through a web server, and for development I don’t think you can beat XAMPP – a package with Apache web server, PHP and MySQL (should you want to teach databases) all bundled together in a convenient installer. (Small note: Apache uses port 80, and so does Skype, so if you do install it and it doesn’t work, check you aren’t running Skype before descending into a quivering wreck and asking the universe “why me”.) Please read the manual for better instructions, but the essentials of getting this working are 1) install, 2) start the server with xampp_control.exe, 3) put your files inside the htdocs folder 4) open a web browser and browse to the address http://localhost/yourdirectoryname/whateveryourfileiscalled.php

So we start off with a page containing a simple form, let’s call the page index.php

<form action="page2.php" method="post">
 <textarea name="shout"> </textarea>
 <input type="submit" value="Shout out"/>

The action attribute of the form specifies the page the data will be sent to when the button is clicked, and the method attribute specifies that the data will be sent via $_POST, i.e. secretly. There is a textarea for people to write things in, and a submit button. No need for PHP tags yet because although this page is saved with the extension .php we are writing only in HTML at the moment.

So on our unimaginatively named page2.php, at the most basic level we need to take the data from the form, which is conveniently provided to us in the array $_POST, and write it to a text file. Obviously you could also accomplish this task by storing the data in a database too, but the aim of this work was to teach writing to files.

So on page2.php we can add some PHP code as below

$fp = fopen("shouts.txt", "a");    // Open the file shouts.txt
fwrite($fp, $_POST['shout']."\n"); // Write the shout
fclose($fp);                       // Close the file

This code is extremely basic. It opens the file shouts.txt in append mode (the second argument “a”). This means we are setting the file pointer to the end of whatever contents are in the file already, and writing there. There are other access modes – in fact this would be a good opportunity to teach them and to start getting students to look up functions on for themselves. Line 2 writes the shout plus a newline character (\n) to the file, and then line 3 closes the file. Incidentally, the index in the array $_POST[‘shout’] is the same as the name of the textarea in your form. Essentially, whatever you names you give your form elements will be the index of their data in the $_POST array.

Clever students will hopefully realise that there is a lot they could do to improve this code. Improvements they could make could include:

  • A presence check to see whether text was actually entered into the form (at present this will write an empty line)
  • A length check if they do not want shouts to be over a certain length
  • An input sanitising check to remove things like HTML – functions like htmlspecialchars could help – get them to look it up
  • They could add the date/time of the shout – date function
  • You could add another input for the person’s name
  • They could pre-format the shout with HTML tags e.g. putting the person’s name bold
  • I’m sure there are other improvements I haven’t thought of…

Now, we go back to index.php which is where we want to display a list of the shouts, below our form. There are several ways of doing this, here is one:

$shouts = file('shouts.txt');
$shouts = array_reverse($shouts);
$shouts = array_slice ($shouts, 0, 50);
foreach ($shouts as $item)
    print $item."<br/>";

This code reads the file shouts.txt into an array. Each line of the file is a new element of the array, and since each shout is on a different line this should mean we have an array of shouts. I  then reverse the array to mean the most recent shouts are first, and then take a slice of the array so that only the top 50 most recent shouts are viewable. A foreach loop goes through this resulting array, printing the shouts (plus a line break) one by one. Again there are changes you could add to this code, for instance formatting the shouts in a prettier way. You could also have used the file_get_contents() function to read the entire file in as a string, and then explode() -ed the string on the newline character to get your array, although not sure why you’d want to from an efficiency point of view.

So, all in all a task which is excellent for teaching numerous things (writing to files, access modes, using a programming language manual, concatenation, array manipulation, interface design) and which is also very decent for differentiation – most people will be able to get a working shoutbox but more advanced students can make it very good indeed. Of course, you could upload finished products to a live webserver if you wished…but beware of inappropriate usage!

2 thoughts on “PHP shoutbox task

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: