What makes a website different from a picture? It usually has interactivity (buttons, links, videos, etc.), but it also has something else: customizability. If it has an account system, for instance, you can enter your username and password, and it will check its database for your credentials.
Once signed in, you will receive a more personalized web page, perhaps with information such as Facebook notifications, new Youtube channel subscribers, or the amount of money you have in your Paypal account. How does this work when you're using HTML and PHP? That's what this tutorial is going to help with.
Please note that this is not an exhaustive tutorial demonstrating all of the different ways that websites can achieve this - it is merely showing one common way this is done. When you are using PHP, there are 2 simple ways (there are also more complex ways using sockets, for instance, but they are very complicated) that a user can send new data to a website: HTTP POST and HTTP GET.
POST is basically only ever used for web forms. POST data is not visible to the user in any way without them using a special plugin or program to monitor it.
In this tutorial, we're going to be focusing on the GET method. GET transmits data to a web server script (from the user's browser) through the URL. Whenever you see incredibly long URL's that look like this: "www.google.com/somepage.php?variable1=value1&variable2=value2", GET is being used.
Real quick, before we begin looking at code, I have 2 links to show you:
- php.net - Go here to read more about PHP code and functions.
- thecodingwebsite.com/tutorials/demos/httpget.zip - Go here to download a zip folder containing the 4 examples used in this tutorial. It might make it easier for you to read the code (especially in example 4, where I post the entire example's code but go through it practically line by line).
So, how does GET work? Firstly, the server has to have some PHP code "listening" for the data. If you have a simple plain HTML page and someone tries to pass it GET data, the server will have no way of retrieving it without some server script (like PHP code) running.
Let's look at a very simple example of this working:
http://thecodingwebsite.com/tutorials/demos/httpget/example1.php?myVariable=Hello%20there,%20how%20are%20you?%20%3Cb%3ENotice%20that%20special%20tags%20can%20be%20included%20in%20here%20by%20the%20user.%3C/b%3E%20This%20can%20be%20prevented,%20though.%20:%29
When you visit the page, notice what it says in the URL box at the top. Now take a look at the "example1.php" code:
<html> <head> </head> <body> <?php echo $_GET["myVariable"]; ?> </body> </html>
When you actually visit the page, however, none of the code inside the PHP tags is visible. This is because the server is actually executing that code. (Note: some servers and some Content Management Systems (like Wordpress (I use the Exec PHP plugin or some variation, in that case)) need to be specially configured to run PHP code.)
"$_GET" is used to access the array (list) of variables that have been sent to the server during a single page visit. The "[ ]" brackets are used to access elements of that array. "myVariable" is placed in quotes inside those brackets to tell the server that we want to retrieve the value of "myVariable" as passed to the server using GET. I'll shorten and simplify the URL so you can see this in action:
http://thecodingwebsite.com/tutorials/demos/httpget/example1.php?myVariable=somevalue
Before we move on, I would like to point out that using GET (and even POST) can be very dangerous if used improperly. There's a hack called cross site scripting (often called XSS) which can use a technique like the "<b></b>" (bold) tags and other HTML tags to change the page content (against the programmer's intentions) and have it e.g. submit the data to another website. Fortunately, PHP provides a very simple fix to this problem: the "htmlspecialchars" function. Take a look at this modified code that I'm now demonstrating in "example2.php":
<html> <head> </head> <body> <?php echo htmlspecialchars($_GET["myVariable"]); ?> </body> </html>
Now when you try to submit GET data through the URL that contains HTML characters, PHP will replace them with the "HTML equivalent". For example, the HTML version of the "<" character is "<", and the HTML version of the ">" character is ">". When the browser sees these characters, it displays the "<" or ">" characters. You may be wondering how you can see "<" then - the answer is that the "&" in "<" has its own HTML equivalent: "&", etc.
Try it out:
http://thecodingwebsite.com/tutorials/demos/httpget/example2.php?myVariable=somevalue%3Cb%3Ehey%3C/b%3E
There are other kinds of hacks against the server that can happen with GET and POST (it has to do with escape characters and single/double quotes), but you don't really have to worry about these hacks anymore because any decently updated version of PHP automatically takes preventive measures against them.
Now here's where it all gets interesting: HTML and PHP code can actually be intertwined. This allows you to make your website display content (including text, links, pictures, etc.) OR NOT display content depending on the data given to it. The server will run through the entire page, look for any PHP code (inside the PHP tags), and execute it, and then once that's all finished the resulting page will be sent to the user. You'll see that this allows for a lot of customization and such.
Take a look at "example3.php":
<html> <head> </head> <body> <?php $name = htmlspecialchars($_GET["myName"]); if ($name == "bill") { echo "Hello, Bill! This is a personalized message for you."; } else if ($name == "joe") { echo "Hi Joe."; } echo "<br/>"; $age = htmlspecialchars($_GET["myAge"]); switch($age) { case 7: echo "7 is a good number."; break; default: echo "You're not 7?! Boring."; break; } ?> </body> </html>
Try out these links, and maybe try out a few of your own variations to see it in effect:
http://thecodingwebsite.com/tutorials/demos/httpget/example3.php?myName=bill&myAge=7
http://thecodingwebsite.com/tutorials/demos/httpget/example3.php?myName=jim&myAge=13
http://thecodingwebsite.com/tutorials/demos/httpget/example3.php?myName=joe&myAge=42
You'll notice that it expects two variables to be passed in: "myName" and "myAge". You can name these whatever you like - they will affect the variable names used to transmit data to the page through the URL. I stored "myName" into the "$name" variable and "myAge" into the "$age" variable (after applying htmlspecialchars to it, of course).
Then I showed an "if, else if" statement (you can branch infinite "else if"'s onto the end for more checks) to see if the name passed in is "bill" or "joe". If the name passed in is neither of these (or it wasn't passed in at all), then the code will skip right on to the "echo "<br/>";" line. If the name is one of those, it will echo the personalized message associated with the name logically. If you then branch an "else" statement (without any "if" or condition) onto the end of that, then that will be the default code run if none of the above "if" or "else if" conditions were true.
I also demonstrated the use of a "switch" statement. Switch statements have cases (you can make many different cases for many different kinds and numbers of values, such as "case 'bill':", "case 'joe':", etc.), and then at the end of each case you place a "break;" so that the script does not leak into the next case. There's also an optional "default:" that you can use that will be called if no cases listed have occurred.
Okay, now it's time for the final example. It will demonstrate several things:
- How to make the page not display any content if none of the values passed in are acceptable.
- How to make link content vary directly based off of a passed in value (after checking the value to make sure it's one of the expected ones).
- How to make large sections of HTML code display or not display depending on the values passed in.
http://thecodingwebsite.com/tutorials/demos/httpget/example4.php
http://thecodingwebsite.com/tutorials/demos/httpget/example4.php?referrer=bob
http://thecodingwebsite.com/tutorials/demos/httpget/example4.php?referrer=jim
http://thecodingwebsite.com/tutorials/demos/httpget/example4.php?referrer=joseph
Here's the source code for "example4.php":
<?php $name = htmlspecialchars($_GET["referrer"]); ?> <html> <head> </head> <body> <?php $showContent = true; $linkName = ""; $linkAge = ""; switch($name) { case "bob": $linkName = $name; $linkAge = 7; break; case "jim": $linkName = $name; $linkAge = 50; break; case "joseph": $linkName = "joe"; $linkAge = 100; break; default: $showContent = false; break; } if ($showContent) { //Note how you can unquote and concatenate strings using a period, or you can just //use the variable name with its $ in front inside the quotes. Both methods will work. //If you want to apply string operations (like lower case), however, you must use //the first method. $linkURL = "example3.php?myName=" . $linkName . "&myAge=$linkAge"; //Note: if you set up the link in HTML instead of PHP, you would use this code (without the surrounding /**/): /*example3.php?myName=<?php echo $linkName; ?>&myAge=<?php echo $linkAge; ?>*/ ?> <b>Congratulations on being referred by <?php echo $name; ?>! It is currently <?php echo date("F j, Y, g:i a"); ?>.</b> <p>Please click this link: <a href="<?php echo $linkURL; ?>"><?php echo $linkURL; ?></a></p> <?php } else { ?> <p>You aren't allowed to see anything here! Please get your referral's link. Thanks.</p> <?php } ?> </body> </html>
It starts off by getting the "referrer" value and storing it into "$name". Then it switches over to HTML code for a bit, until it reaches the "<body>" tag, where it goes back to PHP code. It sets "$showContent" to true (its default value), but then if the referrer value passed in does not equal "bob", "jim", or "joseph", "$showContent" gets set to false so that the page's contents cannot be seen.
"$linkName" and "$linkAge" are simply there to store the values that will be used in the link below if the page content is visible. Not much new is added to this switch statement, so I'll move on.
I have a conditional statement that checks to see if "$showContent" is true (when there are no "==" or anything, the default operation is to check to see if the variable is equal to true). If it is, it sets up the "$linkURL" variable so that the link URL itself and the link's content can be easily displayed later on. Read the comments in this section, they explain a lot.
Then it jumps straight into HTML again. Now it's using a lot of HTML code with a few PHP code switchovers here and there. Every time it switches to PHP code, it simply echoes a value and then jumps back into HTML code.
First it echoes the name, then the date (there's a specific formula you can use to set it up this way - there are a lot more details about how this works here). Finally, it echoes the "$linkURL" value twice - once for the link URL, then again for the link contents (you can name the link contents whatever you like, of course - in this case, I just decided to show the URL in the link's text).
Then it returns back to PHP to close the conditional statement (with a "}") and add an "else" statement onto the end with another "{". Note: I can use "else" here instead of "else if" because I only have one simple condition: no other conditions have been met so far.
Finally it displays some text when none of the expected values have been passed in, it closes up the "else" statement with a final "}", and then finishes the page with the closing "</body>" and "</html>" tags.
Hopefully you understand how this process works now. It can take a little bit of time to get used to (and to work out all of the kinks), but it's really not that bad. Some other ways you could improve on these examples would include:
- Adding some string (a string is a variable/value of text) manipulation techniques, like substrings (pieces of strings), lower and upper case, number conversions so math can be applied (e.g. if you want to make a crummy calculator using just HTML and PHP - there are more practical uses for this, of course :), etc.
- Loading in parameters (like expected values and what to do when they're reached) from a text file or database.
- Storing passed in parameters in a text file or database.
that is nice
ReplyDeleteThank you!
Delete- Andrew