Topic PHP

advertisement
PHP
PHP
Definition
PHP, like JavaScript, is a scripting language for creating computer programs. PHP
is used extensively on the Web because it is easy to learn, integrates easily into
HTML pages, and is useful for most Internet file and database retrieval needs.
Introduction
We discuss PHP and JavaScript as examples of scripting languages and as
demonstrations that you can, and will on the job, need to introduce graphic and
data interaction to create or to improve your organization’s website. RSS feeds
and many other interactions are performed with php. In this topic, we do some
hands-on PHP mostly to introduce concepts associated with any web-based
information system.
Prerequisite
Read the topics about HTML, Client/Server, RDBMS, JavaScript
PHP is available to students in their home root directory, aka DOCUMENT_ROOT. If your Simmons
personal webspace is http://web.simmons.edu/~smith/index.html, then you can create PHP scripts,
store them in files with the .php extension, and upload them to your space. In this example, the php script
just sends to you user the Hello greeting. Use a text editor and enter the following lines exactly as you see
them. Play close attention to the spacing, apostrophe, and punctuation in the php line. Save the file as
“hello.php” and upload it to your space. The URL for your page will be http://web.simmons.edu/
~smith/hello.php
<html>
<head>
<title>My First PHP Script</title>
</head>
<body>
<?php echo '<p>Hello, world. </p>'; ?>
</body>
</html>
Try these versions at http://web.simmons.edu/~benoit/LIS488/hello.php and http://web.simmons.edu/~benoit/LIS488/hellojp.php
Because PHP is installed on the student server, a computer application (the actual php) on the server is
notified that a .php script is being used. The php program then responds within the webpage calling it. In
this example, notice the <? at the start of the php line. This is the same notation you see in XML (it's called
a processing instruction). This kind of syntax is read by the browser and web server one character at a
time. This is important: because web-based systems focus on each character, you must take special care to
use the characters correctly. For example, don't add extra spaces or use "curly quotes" or mixed capitaliza‐
tion in your html, xml, php, or JavaScripts. To the computer <?php is not the same as <?PHP. Because PHP
is a text file it's best not to use a word processing program.
<? is the processing instruction (lets the browser and server get ready for something that isn't
html)
php is the instruction (php, xml, future technologies)
echo is the php command to send whatever follows in single quotes back to the user's screen
' and ' are the String data that the echo command sends back
1
PHP
The line <p>Hello, world. </p> is not php; it is just plain html!
; ends the php command. All programming languages need a way to mark the end of the
command.
?> is the end of the processing instruction.
Note the indentation in the above web page. The indentation is created by using the tab key. This
generates a \t code. HTML, JavaScript, PHP, etc., all understand \r (carriage return), \n (new line), \t (tab),
the space, and a few other commands and usually ignore them.
PHP and all web-oriented scripts have access to a lot of data about the client and about the server. This
next command retrieves data about the server; the next returns data about the client. Save this next file as
"getPHPInfo.php"
<html>
<head>
<title>PHP Data from the Server</title>
</head>
<body>
<?php phpinfo(); ?>
</body>
</html>
After saving the file, upload it to your webspace and run the program. What kind of data do you see?
You'll recall from the Operating System topic that there are often built-in variables (usually expressed in
upper case) and we get the data from that variable by using the $. In PHP, $_SERVER is a variable that holds
all the data about the server. [This specific variable is called a superglobal variable.] We might consider
$_SERVER as an array (see Data Types topic). To get the specific data we want out of the array $_SERVER,
treat it like an array. One data we want is to know what kind of browser we're using. That info is stored in
the variable HTTP_USER_AGENT. To know all the variables, you'll have to check the PHP manual or looking
at the results of the phpinfo() command.
For the rest of the examples, we omit the HTML tags; reuse your page by changing the php line only.
So, to know what browser we're using, change the PHP line to this:
<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>
What do you see?
It's very common to check what browser the client is using so we can address any differences between
browsers in our website. [Some HTML tags are not supported by all browsers.] In this example, we find out
what kind of browser the client is using and pass that data to another function. This function happens to
be programmed to look for a String within another String. This is the same as searching for a file name on
your computer using the Find … command. The strpos() function means "String Position". It asks
whether or not the String you provide is found in the String being searched. Compare this to using the
Find file command and you enter part of the file name (e.g., you have a file called "myresume.doc" but
you've forgotten the full name. You can search for part of the name ("resume"). If the Find file program
finds a match, the program returns a value of true or false. True is considered by the computer as a number
1; false is 0.
2
PHP
<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
The function returned a true value. You must be using Internet Explorer
<?php
} else {
?>
The function returned false - so you're not using IE. Perhaps Safari or Firefox?
<?php
}
?>
Notice that this code snipped mingles HTML and PHP. Any text that is meant to be read by the PHP
program must be encapsulated in the proper php processing instruction. Everything else is by default
treated as HTML.
PHP and Web Forms
Anyone who has used the Internet has used a web form. A form is just a fill-in-the-blank web page.
The HTML tag <form> indicates the start of a form; the </form> ends the form. Data are sent most
commonly from the client to the server using one of two methods GET or POST. Whenever you go to
someone's homepage, for instance, you've actually issued the GET command. With web forms, we send
data to the server. If the data being sent is more than 256 characters we use another method, POST. The
webserver is informed what program to run on its side to process the data being sent based on the
action="xxx" attribute in the <form> tag. In this example, let's say you create a php script, call it
webform1.php. You want to send some data from the web form to the server … and have the server use
your webform1.php script to respond.
Web Page (webform1.html)
<html><head><title>Test 1</title></head>
<body>
This is a test of sending name and age to the server and having my script
respond.
<p>
<form action="webform1.php" method="post">
<p>What is your name? <input type="text" name="name" /> </p>
<p>And age? <input type="text" name="age" /></p>
p><input type="submit" name="Submitbtn" id="Submit_btn" value="Send"></p>
</form>
</body>
</html>
PHP Script (webform1.php)
<html><head><title>Response from the web form</title></head>
<body>
Hi. Thanks for testing the form. Here's the data you sent...
<hr>
Your name is <?php echo htmlspecialchars($_POST['name']); ?> and
you are <?php echo (int)$_POST['age']; ?> years old.
</body>
</html>
3
PHP
How did it go? What would you do to use GET instead? The name="name" means "create a variable (a
bucket) and call it name." Next when the user enters data, store those data in the variable (the bucket). The
variable has a name and contains a value, so together they're called a "name-value pair."
Finally, notice two special things: htmlspecialchars() and int. The htmlspecialchars() is a php
function that will try to remove characters that might be misinterpreted by PHP; it is useful, too, to prevent
people from inserting HTML tags or scripts that could be run on your server. The (int) means convert
whatever follows into an integer (number).
Using PHP to access relational databases and files via the Internet
To access any database or its tables, the user has to have permission, granted by the owner of the
database. For instance, a library could create a MySQL database and have a variety of tables, such as staff
names, patrons, circulation, digital library materials, payroll, fines, and so on. The owner of the database,
say the Tech Administrator, has "root" access, meaning she or he can perform all database functions - create
databases, delete them, create tables, insert (add) data, update, search, modify the table structure … and
control who else has access to the database and tables. Access to web-enabled databases can be limited to
entire databases or just a table within a database. Therefore, access requires permission, an authorized user
name and password. See the RDBMS topic to learn more. For now, tho, let's say you have permission and
you want to extract data from your database via the Internet. Using a web form you can insert your user
name and password in a variable and pass them using GET or POST to the web server, which in turn,
communicates with the database. The database will accept the user name and password or else it won't. If
the user name is rejected, we ought to let the user know! If it is accepted, we ought to execute the search
and return the results, no?
Example
In this example, we want only to check whether or not we have permission to connect to the
database. The username, password, and host name are all hard-coded. Hard-coding variables is fine for
testing, but in real life we want users to provide some data. Create this file yourself, replacing the XXXXX
with your own user name and password. Save the file as connectTest.php and upload it to your
Simmons web account.
<?php
$username = "XXXXX";
$password = "XXXXX";
$hostname = "gslis.simmons.edu:3306";
$dbh = mysql_connect($hostname, $username, $password) or
die("Unable to connect to MySQL");
print "Connected to MySQL<br>";
// you're going to do lots more here soon
mysql_close($dbh);
?>
The web form sends the data to the web server application. The application (such as Apache)
starts the program that is referred to in the <form action = xxx> tag (replace xxx with the name of the
program). That program is then given the variables from the web form (the name-value pairs).
In this example we create a form (webform2.html) that collects data about the user name, the
password, and the name of the host machine, nothing more, and passes them to the program that is called
by the <form action=..." statement (webform2.php). Notice that we extract the variables ("get the
parameters") and store them in new php variables. Now the php script can run properly.
studentCourses-1.html
4
PHP
Web Page (webform2.html)
p>
<html><head><title>Test 1</title></head>
<body>
This is a test of only connecting to a MySQL database.
<p>
<form action="webform2.php" method="get">
<p>Enter your user name? <input name="username" type="text" id="username" /> </
<p>And password <input name="password" type="password" id="username" /> </p>
<p>Which host? <input name="hostname" type="text" id="hostname" /> </p>
<p><input type="submit" name="Submit" value="Test my connection">
</form>
</body>
</html>
PHP Script (webform2.php)
<html><head><title>Response from the web form</title></head>
<body>
<?php
$theUserName=$_GET['username'];
$thePassword=$_GET['password'];
$theHost=$_GET['hostname'];
$dbh = mysql_connect($theHost, $theUserName, $thePassword) or
die("Unable to connect to MySQL, sorry.");
print "Connected to MySQL!";
mysql_close($dbh);
?>
</body>
</html>
The $theUserName, $thePassword, and $theHost are variables we created inside the php script. No other
script can access these variables. The $_GET is a supervariable - a variable containing a bunch of other ones
- and we extract the variables we want from the $_GET. $_GET kindly holds the name-value pairs from the
web form (username, password, and hostname). These value of the variables is extracted and stored in the
variables only our php script can see.
Next we create a new variable $dbh. At first $dbh has no value; but next we call the function
mysql_connect() and ask that function to complete the connection to the database. Since databases
require the user name, password, and the php script needs to know where (on the Internet) the database is
located, we pass three variables to the function: mysql_connect($theHost, $theUserName, $thePass‐
word). For example, let's say the username is "Tom", the password is "9938A", and the computer is the
Simmons web server ("gslis.simmons.edu"), using port 3306, the mysql_connect looks like
mysql_connect("Tom", "9938A", "gslis.simmons.edu:3306"). In fact, you could hard-code these in
your script and bypass the html page entirely and get the same results. Finally, note that you must
specifically close the connection between the webserver, your program, and the database
(mysql_close($dbh)).
Getting data from the database
To extract data from a database table, we need the name of the database, username, password, as
above, but also the name of the table that holds the data and the names of the fields in that (or those)
tables. In a php (or any) script, the programmer or person creating the script (you) must pass a correctlyformed SQL statement to the php command that interacts with the database. In other words, you need to
know the rudiments of how to communicate with a database using php and the basic command set of SQL
5
PHP
to communicate with data on the Internet. This example builds on the previous one by adding more
variables ($selected, $result, and while statement.
All the students in LIS488 can start their own online transcript and blog. We have a database called
userAccts. In that database is a table named "users". Here's the structure of that table:
mysql> desc users;
+--------+-------------+------+-----+---------+-------+
| Field | Type
| Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| idno
| varchar(8) | NO
| *
| NULL
|
|
| status | char(2)
| NO
|
| NULL
|
|
| lname | varchar(30) | NO
|
| NULL
|
|
| fname | varchar(15) | NO
|
| NULL
|
|
| email | varchar(60) | YES |
| NULL
|
|
+--------+-------------+------+-----+---------+-------+
5 rows in set (0.02 sec)
In this script, we're going to extract only your name based on your student ID number. The field to be used
is "idno". The first thing we need to do is to connect to the database server, then select the database we
want ("userAccts") and then issue a SELECT command to extract the data from the table ("users"). The
command is SELECT lname, fname, email FROM users WHERE idno='xxxx';
To create the command, we combine data from the web form with hard coded strings. First, we create a
variable that confirms that we can connect to the selected database, so let's call it $selected
$selected = mysql_select_db("userAccts", $dbh) or die "Cannot select db");
Now, we need a variable to hold the results of our search (if successful):
$result = mysql_query("SELECT lname, fname, email FROM users
WHERE idno='".$_GET['idno']."'");
Notice we're using a shortcut in extracting the idno from the form and including it in the SQL Select
statement.
If there are results, we want to see them all. There should be only one record for your student ID but if not,
this program will show us.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print "Name: " .$row{'fname'}." ".$row{'lname'}."<br>";
}
The full script looks like this:
<html><head><title>Checking my ID</title></head>
<body>
<?php
$theUserName=$_GET['idno'];
$thePassword=$_GET['password'];
$theHost="gslis.simmons.edu:3306";
$dbh = mysql_connect($theHost, $theUserName, $thePassword) or
die("Unable to connect to MySQL, sorry.");
$selected = mysql_select_db("userAccts", $dbh)
or die("Cannot select db");
$result = mysql_query("SELECT lname, fname, email FROM users
WHERE idno='".$_GET['idno']."'");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print "Name: " .$row{'fname'}." ".$row{'lname'}."<br>";
}
mysql_close($dbh);
?>
</body>
6
PHP
</html>
To connect to a database, remember, you need certain data and then pass those data to establish the
connection. If the connection cannot be made an error (aka exception) is returned to you. Once you have
the connection, you issue the command to get data from the database table and so need a variable (here,
$result) that captures the results of the search. Once you have an object that holds your results (aka result
set), you process each record one-by-one until there are no more. The "while ($row = …" statement should
be read "as long as there are records (or rows) that have data in them, get the data out of the variable and
do something with it." In this case, we're printing the data. When finished, be sure to close the connection
to the db.
What to know A few pages of PHP is not enough to teach you the subject. It is sufficient, however, to
emphasize a few repeating themes in client/server interaction and scripting in general.
• How to integrate HTML and script languages in the same page
• How to send data to the server using POST and GET and web forms
• How data can be converted: htmlspecialchars, (int)
• Processing directives (the <?php>
• Variables
• Name-value pair
• Parameter
• The steps to connect to a database
file:///Users/gbenoit/Documents/PHP%20and%20RSS%20Feeds/How%20To%20Build%20a%20Univer‐
sal%20Feed%20Reader.webarchive
7
Download