meandeviation.com > learn php > try it yourself

try it yourself - make your own form and php

If you have familiarised yourself with writing forms using showform and mailform it is time to start making scripts that do things from your own forms.

This first exercise is to do basically the same as showform, that is simply produce a page listing the things you have entered into a form.

Here is an example form and php script to handle it:

DO NOT click the second link yet!! If you do you will probably get a very strange web page!!

Try going to the form and entering your name and email.

do it on your site

Download both files to your disk (use "download link to disk" in IE or similar save option in other browser).

The PHP file will come down under the name "try-yourself.phps" with ".phps" at the end instead of ".php". You will need to change this to ".php".

Now try uploading them both to your site using Dreamweaver or an FTP tool.

Now go the the copy of test-try-yourself.html on your site and try it out. Does it work? Congratulations - you have run your first PHP script!!!

If you have problems double check the files have unloaded to the same place etc. (and that PHP is enabled on your web server). Depending on your web server you may need to do some extra things before the scripts will run:

Aside: the reason that the file downloads as ".phps" is that it is actually a copy of the ".php" file with a different name. If you try to download a file called ".php" through a browser, the web server actually executes the PHP and what you get is the resulting page, not the PHP itself.

looking at the test form

Look at the HTML source of test-try-yourself.html

This should by now be familiar. A very simple form:

<form method="GET" action="try-yourself.php">
    <p>Name:
        <input type="text" name="yourname" size="50" maxlength="50">
    </p>
    <p>Email:
        <input type="text" name="email" size="50" maxlength="100">
    </p>
    <p>
        <input type="submit" name="Submit" value="Submit">
    </p>
</form>

Note however that the <form> tag's 'action' attribute is not a full URL starting "http://...", but instead is a relative URL: "try-yourself.php". This is so that when you download the file and upload it to your own server it is your copy of the php script that gets run, not the one on meandeviation. If you like you can write the full URL of the php script on your site into the action attribute.

You can also change the 'method' attribute to 'POST' and then you will not see the "&yourname=..." in the URL generated when you submit the form.

Otherwise, the only difference from the previous forms is that the <input> tags have an explicit 'size' and 'maxlength' attribute. The 'size' attribute says how big it will appear on screen (50 characters wide) and how many characters you are allowed to enter (100 in this case).

looking at the php

Now look at the PHP source of try-yourself.php

The first few lines look just like an ordinary HTML web page:

<html>
<head>
<title>php for you to edit</title> ....

In PHP anything not within <?php ... ?> is treated as normal HTML and sent to the browser as it stands.

A bit further down the source we find this:

<p>
You said your name is:
<?php
echo $_GET['yourname'];
?>

This starts of with some normal HTML "<p>" etc. and then we see "<?php echo $_GET['yourname']; ?>". The bit inside <?php ... ?> is PHP program code. In this case it just says "echo $_GET['yourname'];". the keyword 'echo' means put this on the page and the part that says "$_GET['yourname']" has come from the form you have just entered (or strictly from the "&yourname=..." part of the URL).

Try filling out the form (say with "Alan Dix" as the name) and then use "View > Source". You will see the HTML that has been generated by this bit of PHP. Instead of the <?php ... ?> tag you will see:

<p>
You said your name is:
Alan Dix

The <?php ... ?> has been replaced with the result of running the code ... that is the contents of $yourname which is "Alan Dix" (or whatever you entered for the name).

Next in the PHP source we see the email displayed:

<p>
and your email is:
<?php
echo "<a href=\"mailto:" . $_GET['email'] . "\">" . $_GET['email'] . "</a>";
?>

This looks a bit more complicated. Perhaps it is best to look at the generated page again and see what this produces (assuming you have entered "alan@hcibook.com" for the email):

 

<p>
and your email is:
<a href="mailto:alan@hcibook.com">alan@hcibook.com</a>

Notice first that "alan@hcibook.com" appears twice. Corresponding to the two uses of $_GET['email'] in the PHP echo command. The 'echo' is more complicated because it is constructing the <a href="..."> link.

The 'echo' includes some 'literal' text in quotes (such as "</a>") this is simply sent to the browser as it is (that is the last "</a>" in the HTML page).

One of these bits of literal text itself wants to include a quote. You cannot simply write "<a href="" as PHP wouldn't know that the second quite was supposed to be sent to the web page or end the literal string. In order to tell PHP that we actually want a " on the page it is 'escaped' with a backslash (\), so we have the literal "<a href=\"".

Now you may be thinking "what if I wanted a backslash on the page" ... well in this case you 'escape' the backslash and so \\ inside literal text means \ (OK computers are stupid, but try writing a story with quotes inside quotes and see how confused you get!).

Finally the dot in PHP means "join these bits of text together". So the bits of the echo convert into bits of page as follows:

"<a href=\"mailto:"   ->  <a href="mailto:
$_GET['email']        ->  alan@hcibook.com
"\">"                 ->  ">
$_GET['email']        ->  alan@hcibook.com
"</a>"                ->  </a>

All joined together we get: <a href="mailto:alan@hcibook.com">alan@hcibook.com</a>

One last thing. You may not recognise the "mailto:" bit inside the link. This means that when you click the link the browser will start an email to that address (if it is configured properly). You will probably have seen links like this, for example, in the staff pages at: http://info.comp.lancs.ac.uk/computing/staff/

now it is your turn

OK try and make a form and PHP script of your own. Either copy and edit the files above or start from scratch (perhaps use Dreamweaver). See how to design generated pages for details on good ways to move from hand layout to generated pages.

Try to add a pull down menu (e.g. for Mr/Ms title like in the showform test form), some radio buttons (like the male/female) and a field to enter a URL for a home page.

N.B. do not have spaces in the names of your fields, so call the name of the field "homepage" or "url" not "home page". It is fine to have spaces though in the html that labels the field. For example:

<p>Home Page:
    <input type="text" name="homepage" size="70" maxlength="100">
</p>

If you include the home page you may like to either make this a 'live' link, rather like the email ... or perhaps make the name itself live.

You can test your form by using the "showform" URl as the 'action' of your form and then change it to point to your own PHP.

N.B. don't forget to change the 'action' attribute of the <form> tag otherwise it will point to the original "try-yourself.php" script.

some extra things ...

dealing with data from checkboxes

I carefully didn't mention checkboxes as in the "interest1", "interest2" fields in the showform test form.

Recall the form had:

<p>Home Page:
    <p>Interests: 
<input type="checkbox" name="interest1" value="web" checked>
web development
<input type="checkbox" name="interest2" value="user"> user interfaces
<input type="checkbox" name="interest3" value="music"> music
</p>

You could put something like this into your PHP 'action' script:

<p>
Your interests: <?php
echo $_GET['interest1'];
?> <?php
echo $_GET['interest2'];
?>
<?php
echo $interest3;
?>

But this would generate the following HTML (assuming "web development" and "music" were selected):

<p>
Your interests: web music

This would format on the page as:

Your interests: web music

This has two problems.

First you may want to say something more descriptive like "web development" rather than the value returned by the form.

To do this you need a bit of extra PHP - the "if" command:

<p>
Your interests: <?php
if ( $_GET['interest1'] ) echo "web development";
?> <?php
if ( $_GET['interest2'] ) echo "user interfaces";
?> <?php
if ( $_GET['interest3'] ) echo "music";
?>

This should be read as:

if the field 'interest1' is not empty then put "web development" into the generated HTML page
... etc.

The second problem is that this will still produce something like:

Your interests: web development music

On the web page. You would really like commas between them.

The obvious thing is to add these to the echo-s:

<p>
Your interests: <?php
if ( $_GET[interest1'] ) echo "web development, ";
if ( $_GET[interest2'] ) echo "user interfaces, ";
if ( $_GET[interest3'] ) echo "music";
?>

(Note: all the php has been put into a single <?php .. ?> block. All the PHP commands within the tags are executed.)

This will be fine and produce:

Your interests: web development, music

just what you want ... but ...

... if instead web development and user interfaces have been selected you would get:

Your interests: web development, user interfaces,

Notice the 'spare' comma at the end.

Separators are always very messy.

One solution is:

<p>
Your interests: <?php
if ( $_GET[interest1'] ) echo "web development";
if ( $_GET[interest1'] && $_GET[interest2'] ) echo ", ";
if ( $_GET[interest2'] ) echo "user interfaces, ";
if ( ( $_GET[interest1'] || $_GET[interest2'] ) && $_GET[interest3'] ) echo ", ";
if ( $_GET[interest3'] ) echo "music";
?>

Read "&&" as "and" (in the logical sense) and "||" as "or". So this means:

if the field 'interest1' is not empty then put "web development" into the generated HTML page
if the field 'interest1' is not empty and the field 'interest2' is also not empty then put ", "
if 'interest2' is not empty then put "user interfaces"
if 'interest1' is not empty or 'interest2' is not empty and is 'interest3' not empty then put ", "
if 'interest3' is not empty then put "music" into the generated HTML page

Check it out for yourself to see whether it makes sense!!!

making your own variables

The PHP code above is made hard because all the names are preceded by "$_GET".

ASIDE: Technically $_GET is a 'predefined array': predefined in that PHP defines it for you and an array as it has lots of parts: the named bits inside [].

You can make this simpler ... and learn about something new, by defining your own variables. You do this my simply writing "$yourvariablename = " inside the PHP code, followed by what you want it to be.

<p>
Your interests: <?php
$web_interest = $_GET[interest1'];
$ui_interest = $_GET[interest2'];
$music_interest = $_GET[interest3'];

if ( $web_interest ) echo "web development";
if ( $web_interest && $ui_interest ) echo ", ";
if ( $ui_interest ) echo "user interfaces, ";
if ( ( $web_interest || $ui_interest ) && $music_interest ) echo ", ";
if ( $music_interest ) echo "music";
?>

Isn't that easier to read now?

different ways to do the same thing

Recall the email link was constructed using quoted strings, variables and dots:

<p>
and your email is:
<?php
echo "<a href=\"mailto:" . $_GET['email'] . "\">" . $_GET['email'] . "</a>";
?>

We could also change this to use a variable:

<p>
and your email is:
<?php $myemail = $_GET['email'];
echo "<a href=\"mailto:" . $myemail . "\">" . $myemail . "</a>";
?>

 

There are a couple of other ways of doing this that show you different ways to use PHP.

First it is possible to include variables inside literal quoted strings:

<p>
and your email is:
<?php $myemail = $_GET['email'];
echo "<a href=\"mailto:$myemail\">$myemail</a>";
?>

PHP recognises the '$' and so includes the value of the variable so that:

"<a href=\"mailto:$email\">$email</a>"

becomes on the web page:

<a href="mailto:alan@hcibook.com">alan@hcibook.com</a>

Sometimes this is clearer than using the dot to join text strings together, but can be confusing or not possible for some special kinds of variable.

The other way is to have 'smaller' <?php .. ?> tags and use the fact that things outside the tag just appear on the page:

<?php
   $myemail = $_GET['email'];
?>
<p>
and your email is:
<a href="mailto:<?php echo $myemail; ?>"><?php echo $myemail; ?></a>

Because PHP interprets the <?php ... ?> tag before HTML sees the page, the <?php ... ?> tags inside the href="..." expand properly to give the same result as before. Note too that the quotes in href="..." do not need to be escaped as they are part of the page outside the <?php ... ?> tag.

This is just a more complicated use of the same kind of expansion as the simple one for $yourname, but I always find the <?php .. ?> tag inside the <a href="...">, just a little confusing!

Also do note the fact that these <?php .. ?> tags have been put with no space between them and the rest of the HTML. In the previous examples I always started these on separate lines, but this would have introduced extra spaces into the HTML. In the case of the link this would mean that it would have become:

<a href="mailto: alan@hcibook.com "> alan@hcibook.com </a>

In the web page would look like:

and your email is: alan@hcibook.com

This looks OK, but the spaces in the href="..." may mean the email would not work on some systems. Certainly this will make many ordinary URL links fail. Also HTML had been included within some surrounding text, perhaps angle brackets as is common for emails, then the spaces within the link would appear as underlined space: < alan@hcibook.com >

In HTML it is usually all right to have multiple spaces instead of one (with exception of preformatted text), but extra spaces where none are expected can cause problems with layout ....

... and not just in generated pages - before Dreamweaver sometimes puts spaces in tables that cause bad layout and have to be removed.

Finally you may have noticed the the variable declaration "$myemail = ..." was put inside a different PHP tag to the use of it. This is fine; when variables are defined or set they can be used in any further PHP tags further down the same page.


http://www.meandeviation.com/tutorials/learnphp/about-try-yourself.html Alan Dix © 2002