So far we’ve only looked at how to write PHP code. But just as important as your code can be the comments you write to explain what your code does.
PHP supports 3 different ways of writing comments. The first 2 are borrowed from C. There’s the double forward-slash format:
//this is a comment
and the multi-line comment:
/*
This is a comment that can include many lines
*/
And lastly there’s the shell-style comment with the # sign:
#this is another comment for just one line
The way the single line comment works is that everything following the start of your comment until the next new-line will be commented out and ignored by the interpreter, but with one rather important exception: PHP ending tags.
So, for instance, the following code will break:
// echo ‘<?xml ?>’;
And it doesn’t matter whether that’s a pair of forward slashes or a pound sign. Personally, I always use the forward slashes since there’s no functional difference between them, and it’s what I’m used to.
But anyway, what’ll happen is that the ?> will be seen by the interpreter as an end of the PHP block. Anything after that will just get printed directly to the page. Without the comment, PHP would have seen that as part of a quoted string, and known not to treat it like an ending tag. But once you have the comment there, it won’t recognize the quotes around it. It’ll just be treated like a closing PHP tag.
In this case, the only solution, if you really need that line commented out, would be to use the multi-line style comment. However, you have the freedom with that comment type to comment just a section of a single line.
Basically, the way multi-line comments work is they tell the interpeter to ignore anything between a /* and a */. Once the interpreter enters a comment block of that type, the only thing it looks for is an ending mark for that comment. And if it finds it on the same line or a thousand lines down the page, it makes no difference as far as the interpreter is concerned.
So, rewriting that comment:
/* echo ‘<?xml ?>’; */
And that comment will work just fine.
It’s worth noting that the multi-line comment ignores PHP ending tags as well. So, something like this:
<?php /* ?>
<p>Here is some HTML</p>
<?php */ ?>
would be a way of commenting out a section of HTML so that it didn’t get sent to the page. Just remove the beginning and ending tags for the comments and the HTML fragment will re-appear.
Now, the pit-fall with this type of comment usually happens when you try to nest them by mistake. Suppose you need to comment out a large block of code, but somewhere in that code there’s already a multi-line comment block, for instance like this:
/*
… lots of PHP code
/*
The following function does something wonderful
*/
function doSomething() {
//… do something wonderful
}
… more PHP code
*/
In this case, the PHP interpreter would see the first comment-ending tag, and treat everything after it as regular PHP. But then it would hit the intended comment-ending tag, and throw a fatal parsing error, since ‘*/’ isn’t a recognized PHP expression.
So, just be careful when blocking out large sections of code this way. If you use an editing environment like mine, it’ll alert you to this sort of mistake.
Now that we’ve looked at comments, a good programming tip is to use them to explain in plain English what your script is doing at each step of the way, before you actually write your code. This way, so long as your logic makes sense, you can just write your code to do what you intend to do and be fairly confident that your functionality will work as intended. If there’s a mistake to track down, then knowing exactly what the code ought to be doing can be a huge help, rather than trying to make an informed guess based on contextual clues.
Another use for comments is in removing a line or lines of PHP that you don’t want to execute. This can be especially important when you’re debugging, and we’ll look more at that in a later video.
March 09 2010 | Basics and PHP Programming Basics and PHP tutorial scripts | Comments Off on Commenting
We’ve already looked at using the GET superglobal array to get data from the user through the URL. Another way to get data from the user is through forms. Different form elements work differently.
Here’s a simple webpage with a form on it, I’ve mixed in one of each of the input element types that HTML provides, not counting ‘file’ since we’ll cover that in a later video:
{show output}
Behind the form, this is what it looks like:
{show source}
The first thing to look at is your form tag. The important attributes here are ‘action’ and ‘method’. If the form only contains a short amount of information – no textareas and text fields with maxchars set at numbers below 255, you can actually send up to 4000 or so characters’ worth of data through the URL when you submit the form. The way this will work is your browser will automatically encode the form data into a string, similar to how http_build_query works, and append it to whatever URL you specify in the action attribute. You do this by specifying GET as the method (that’s not case sensitive).
Personally though, I hate the way GET makes the URL look on any form with more than one or two elements, so I almost always use the other method, called POST. POST transmits the form data in a manner that’s invisible to the user, and it can handle as much data as you need.
To access your user’s submission, you have to specify the address of your php file within the action attribute. If you specify an empty pair of quotes, it’ll just submit the form data to the same URL the form is on.
Some programmers mistakenly assume that POST is somehow more secure than GET, just because the data is in plain sight in the address bar. And it’s true the if you want to prevent a hacker from sending someone to a completed form by using a link, then yes, POST might be better. But the truth is, in most respects, while GET is more visible, any hacker is going to have just as easy a time forging a POST request as they would with GET. There’s a whole chapter later in this tutorial that deals with security, but the first rule of security is never trust data that originates from the user. Doesn’t matter whether it’s GET, POST or any of the others I haven’t introduced yet. If it came from the user, check it and make sure it’s valid before you use it.
There are several types of input elements you can add to a form. You’ve probably encountered them all at some point just as a web surfer. However, we’re only going to look at a few. These are the text box, checkbox, radio button, hidden field, and the submit button.
All of the fields we’re going to look at are variations of the “input” HTML element. The input element has one required attribute – “type” and a few optional attributes. If you don’t specify a type, you’re violating the w3 standard for HTML, but in most browsers, rather than breaking the page, they’ll just treat it as text, since it’s the most common. So since it’s sort of the default, we’ll look at that first.
Here’s a simple text input element:
<input type=”text” name=”text1″>
In addition to a type, if you want to actually collect the data from your form in a meaningful way, another attribute your input elements should have is a name. Whatever type you use it for, the name will become the key your PHP script will use to reference the value submitted.
On the server, there are another couple superglobal arrays we haven’t looked at yet called POST and REQUEST. When I submit this form, the value of this input element, whatever it is, will be contained in the key ‘text1’ in both the POST and REQUEST superglobals. But they’re not redundant. POST will only have variables submitted through a form that uses the post method, whereas REQUEST will contain everything in both POST and GET, as well as another superglobal called COOKIE.
Here, I’ll prove it:
<?php
echo ‘POST[text1] = ‘ . $_POST[‘text1’] . ‘<br>’;
echo ‘REQUEST[text1] = ‘ . $_REQUEST[‘text1’];
{switch back to form, type “Hey Let’s Go!”}
And so you see that my data has been submitted to the server. My own recommendation is that you rely on POST when posting, and GET when passing through the URL.
By the way, if you try this out yourself, and you see forward slashes in front of your apostrophes, it means that your php installation has magic quotes turned on. If that’s the case, I recommend you read the PHP manual under security to learn what magic quotes are, and decide if you want to turn them off. It’ll give you instructions on how to do it. The feature is deprecated in PHP 5.3 and removed in PHP 6, so turning it off is the best option if you’re not already working on a site that relies on them.
Now, back to the name attribute here, you can actually use square brackets in the name itself to specify that the value is part of an array. I’ll prove that now:
{modify name attribute to be text1[key1][key2]}
echo ‘POST[text1][key1][key2] = ‘ . $_POST[‘text1’][‘key1’][‘key2’] . ‘<br>’;
And you can see that that works. I don’t have to use associative arrays either. If I wanted, I could have ten different elements all named like ‘var[]’ and they would automatically get set as a numerically-indexed array within POST called var.
Moving on, the hidden element has another attribute. Technically all of the input elements support it, but I ignored it with the text type. It’s the value attribute. The way hidden works is it sends a name/value pair to the server without any input needed from the user. Pretty simple right there.
The radio element is designed to work with other radio inputs that have the same name. Your script specifies a value, but that value only gets sent to the server if the radio button is checked. And with other buttons of the same name, the browser is responsible for ensuring that only one of the elements can be checked at a time.
{show radio button clearing another radio button}
Since each button has the same name, my script can tell which one was checked based on the value that gets passed with that key.
Checkboxes are similar. You don’t have them all named the same, although you can. But more than one can be submitted with the same name. The way all these inputs work is that if an element lower down on the page sends a value corresponding to the same key then only the latter element actually ends up in the POST array. Of course, that’s not counting ones with empty square brackets at the end – have as many of those as you want and they just keep getting appended to an array. And in fact, that’s not an uncommon thing to do with checkboxes. But if you have either radio buttons or checkboxes where none are checked, they don’t get submitted to the server, so a common use for hidden elements is to place them above your checkboxes in the code. That way, you can send a value to the server letting your form processor know that the box was left unchecked. But if the checkbox is checked, its value will be the one that shows up instead.
Anyway, my checkboxes are simple. They have names and all their values are 1’s. Above them all is a hidden field with the same name and a value of 0. So, my form processor knows whether they were checked or not. Because input elements lower down will override elements with the same name higher up on the form, the hidden element’s value will only get transmitted to the server if the corresponding checkbox is unchecked. But if the checkbox is checked, its value will be sent to the server instead.
if($_POST[‘cb1’] == 1) {
echo ‘cb1 was checked’;
} else {
echo ‘cb1 was not checked’;
}
The last input type is the submit button. I’ve been using it each time I’ve submitted the form, so let’s look at how it gets created:
<input type=”submit” name=”B1″ value=”Submit”>
The ‘value’ attribute is what shows up on the button when your user looks at the form. As for the ‘name’ attribute, it’s optional, but if I provide it, I can access the button’s value in the POST global through my PHP script. The ‘submit’ button isn’t the only way to create a button through HTML, but it has the special property that when your user clicks a submit button, it causes the form to be submitted. And if you have several different submit buttons on your form, you can check the POST array to find out which one was submitted. The submit button’s value only gets sent if the user clicks it. If it’s just on the page, but not clicked, then the POST array doesn’t get any information from it.
<input type=”submit” name=”B1″ value=”I am B1″>
<input type=”submit” name=”B2″ value=”I am B2″>
<input type=”submit” name=”B3″ value=”I am B3″>
<input type=”submit” name=”B4″ value=”I am B4″>
if(isset($_POST[‘B1’])) {
echo “You clicked B1”;
} elseif(isset($_POST[‘B2’])) {
echo “You clicked B2”;
}elseif(isset($_POST[‘B3’])) {
echo “You clicked B3”;
}elseif(isset($_POST[‘B4’])) {
echo “You clicked B4”;
}
{add the code shown above, click the form a couple times to prove it works}
So, that’s about it for forms. There’s more to them than what I’ve introduced, but this should be enough to get you started.
March 07 2010 | Schmategories | Comments Off on Getting Data from the user – part II