TheTAZZone - Internet Chaos

Tutorial – PHP for Newbies 3

Tutorial – PHP for Newbies 3

In this segment, I’ll be covering a few methods of passing information from one web page to another via a URL, via a session, and via cookies.

Introduction

Before delving too deeply into any of the above, I’d like to take a moment to introduce you to the predefined methods used in PHP to retrieve stored information. Pay special attention to the first five.

$_GET[‘variablename’] corresponds with the HTML “get” method used in HTML forms (which will be covered in the next tutorial).
$_POST[‘variablename’] as you can imagine corresponds with the HTML “post” method used in HTML forms.
$_SESSION[‘variablename’] is used to create and retrieve information stored in PHP sessions.
$_COOKIE[‘variablename’] is used to create cookies and retrieve information stored within cookies.
$_REQUEST[‘variablename’] is used to retrieve variables that have been posted using any of the above methods.
$_SERVER[‘variablename’] is used to retrieve variables from the server.
$_FILES[‘variablename’] is used to retrieve variables from an uploaded file.
$_ENV[‘variablename’] is used to retrieve variables assigned from the operating environment.

I will only be utilizing the first five of the above during this and the next few tutorials.

Passing a Variable through a URL

Let’s take a look at a URL first.

Code:
Http://www.mydomain.com/sub/directory/thispage.php?id=12345&desc=AWESOME

The portion all the way through .php simply points to the file. The “?” onward is the part of interest. Notice the “something=value&somethingelse=anothervalue” format. You can assign values to the next page by adding them into the URL as demonstrated above and join multiple together with &. It’s worth noting that this is the URL the user sees in the browser, therefore this method of passing information from one page to another is completely insecure and fairly cumbersome for the user. That being said, it’s perfect for simple, short bits of code that you don’t mind the user seeing. To demonstrate how this works, you will need to create two files this time. Name them infourl1.php and infourl2.php. I’ll be using “desc” short for description (because that’s how my strange little mind works).

In infourl1.php input the following:

Code:
<html>
<head>
<title>My Title is Different.</title>
</head>
<body>
<?php
echo “<a href=’infourl2.php?desc=AWESOME’>”;
echo “Click here!”;
echo “</a>”;
?>
</body>
</html>

In infourl2.php input the following:

Code:
<html>
<head>
<title>My Title is <?php echo $REQUEST[‘desc’]; ?></title>
</head>
<body>
<?php
echo “This page is “;
echo $_REQUEST[‘desc’];
echo “!<br />”;
?>
</body>
</html>

Browse to http://localhost/variableurl1.php.

Click on the link and you should be brought to a page that displays the text: “This page is AWESOME!” Keep in mind that in the above example you have not created a variable “$desc”. In fact, you could add the line echo $desc; before the ?> closing tag and nothing would appear. You must refer to [‘desc’] with the $REQUEST method, or you can use a different method to define a variable on one page, pass it to another, then refer to that variable. As you can imagine, this is far more useful.

The tricky part about defining a variable and then passing it through the URL is that URLs are extremely particular about characters (like spaces for example), and variables tend to contain characters that do not play nicely with URLs. To address this problem, PHP uses the urlencode() function. Let’s try this out by editing the same files listed above.

In infourl1.php input the following:

Code:
<html>
<head>
<title>My Title is different.</title>
</head>
<body>
<?php
$desc = urlencode(“FREAKING RIDICULOUSLY AWESOME”);
echo “<a href=’infourl2.php?desc=$desc’>”;
echo “Click here!”;
echo “</a>”;
?>
</body>
</html>

For this example, infourl2.php will not change. It will still retrieve desc (not the variable) from the URL, which now contains the variable $desc. Navigate to http://localhost/inforurl1.php and follow the link to see what happens! As you can imagine, passing a variable from one page to another via the URL is much more useful, but it still adds the entire contents of the variable into the URL, taking up tons of space and is plain for all to see. Note that adding the line

Code:
echo $desc;

to infourl2.php before the ?> closing tag still does not have any effect. You must still use $REQUEST. It’s also worth noting that using this method may confuse a browser and risks old information coming up when a user presses “back” or visits a cached version of the page.

As you can see, passing a variable through a URL has some obvious drawbacks despite being fairly quick and easy to implement. Next I’ll show you a better alternative.

Passing a Variable using Sessions

Sessions are used to transmit information of a more sensitive nature (such as login information, phone number, address, full name, etc). A session creates a temporary set of variables that that by default disappear when the browser is closed. Sessions are assigned a unique ID. This is necessary for the sake of keeping track of the currently assigned values in the variable array. This ID can be passed through the URL or can be stored in a cookie (which will be discussed later). You begin a session using the function session_start(). To illustrate how sessions transmit information (like a username and password), we will ignore the fact that these are usually input and simply add them into the code ourselves strictly for the purpose of demonstrating the inner workings of a session. Create two files, sessionpractice1.php and sessionpractice2.php.

In sessionpractice1.php input the following:

Code:
<?php
session_start();
$_SESSION[‘username’] = “User”;
$_SESSION[‘authuser’] = 1;
?>
<html>
<body>
<?php
$genericvariable = urlencode(“generic text”);
echo “<a href=’sessionpractice2.php?variable=$genericvariable’>”;
echo “Click the link!” . “</a>”;
?>
</body>
</html>

In sessionpractice2.php input the following:

Code:
<?php
session_start();
//The following will check to see if the user is authenticated
if ($_SESSION[‘authuser’] != 1)
{
echo “Sorry, you are not authorized to see this page!”;
exit();
}
?>
<html>
<body>
<?php
echo “Welcome to the site, “;
echo $_SESSION[‘username’];
echo “! <br />”;
echo “Check out this neat “;
echo $_REQUEST[‘variable’];
echo “<br />”;
?>
</body>
</html>

Notice the PHP script before the <html> tag. This is critical! It is also critical that there are no spaces before this initial script begins. Also note that it is necessary to use the session_start() function on every page that references the session variables. The above will work every time, and you will never see the “Sorry, you are not authorized…” text because it’s rigged to always work. To experiment, change the value of authuser to 0 in the first script, save, and then again navigate to http://localhost/sessionpractice1.php. Finally, you may be wondering how to pass the session ID everything is tied to from one page to another. To answer that question, I should explain how cookies work.

C is for Cookie…

Cookies allow you to store information locally on the user’s computer for a specified length of time. The thing about cookies is they are quite helpful but impossible to rely on for a variety of reasons. Some people disable cookies, and most people clear them out routinely as a part of operating system maintenance. That being said, they are useful for storing information (such as the fields in a form) after the browser has been closed. (Remember that sessions expire when the browser is closed). Cookies are set using the PHP function setcookie(). When you set the cookie, you must specify a cookie name, value, and optionally the expiration timer, and whether or not a secure connection is required. The syntax looks like the following:

setcookie(‘cookiename’, ‘value’, ‘expiration timer’, ‘secure connection’);

There are other options available for cookies, but are beyond the scope of this tutorial. Let’s try an example. Create two files, the first named cisforcookie1.php and the second cisforcookie2.php.

Input the following into cisforcookie1.php:

Code:
<?php
setcookie(‘username’, ‘Sprocket’, time()+60);
?>
<html>
<body>
<?php
$genericvariable = urlencode(“generic text”);
echo “<a href=’cisforcookie2.php?variable=$genericvariable’>”;
echo “Click the link!”;
echo “</a>”;
?>
</body>
</html>

Input the following into cisforcookie2.php:

Code:
<?php
session_start();
?>
<html>
<body>
<?php
echo “Welcome to the site, “;
echo $_COOKIE[‘username’];
echo “! <br />”;
echo “Check out this neat “;
echo $_REQUEST[‘variable’];
echo “. <br />”;
?>
</body>
</html>

Now navigate to http://localhost/cisforcookie1.php and click on the link. On the next page, if your browser allows cookies you should see the output:

Welcome to the site, Sprocket!
Check out this neat generic text.

Summary

Now you should be able to pass information from one page to another using the URL, using a session, and by setting a cookie. In the next section I’ll review HTML forms and show how to use these to retrieve information from the user and how to use PHP to pass that information to another page.

ORIGINALLY POSTED BY KEEZEL FOR THETAZZONE/TAZFORUM HERE

Do not use, republish, in whole or in part, without the consent of the Author. TheTAZZone policy is that Authors retain the rights to the work they submit and/or post…we do not sell, publish, transmit, or have the right to give permission for such…TheTAZZone merely retains the right to use, retain, and publish submitted work within it’s Network


Leave a Reply

Your email address will not be published. Required fields are marked *

Advertise

If you'd like to advertise on The Mutt ( aka TheTAZZone.com ) feel free to contact us at: administration[at]thetazzone.com

TheTAZZone is a non-commercial entity. We do not sell any products or services ourselves. Our revenue comes from advertising and donations only.

We appreciate your support! Your advertising revenue ( or donations ) helps us to continue to upgrade, improve, and offset the costs of maintaining this site.

Donations can be made through the page ' Donate '.