PHP Hypertext Processor

• PHP Hypertext Processor • Introduction • • • • • Server-side web scripting Dynamically write HTML based on user data (from HTML forms or queryst...
Author: Sydney Edwards
33 downloads 0 Views 82KB Size


PHP Hypertext Processor



Introduction • • • • •

Server-side web scripting Dynamically write HTML based on user data (from HTML forms or querystrings) Database interaction Large and fully-featured language http://www.php.net/manual/en/

PHP scripts are typically embedded within html documents The server processes the html document, executing the PHP segments and substituting the output within the html document

The server may be accessing files whose names should not be seen, or preprocessing data that it does not want the client to see The only reason the client even knows PHP is involved is due to the file extension (.php)

PHP is a large, fully featured language: an incredible amount of built-in features: • Form processing • Output / generate various types of data (not just text) • Database access • Allows for various DBs and DB formats • Object-oriented features • We will look at only the basics/essentials Simple PHP Example:

The Request-Response Cycle:

Web Server

Headers Cookies Requested URL Form Data

“Request” Client (Browser) • • • •

Request was for a .php file?

No: then send directly the HTML file requested as response

Headers Cookies HTML Page

Yes: then process the requested PHP script and send any HTML output as response

First PHP Example echo " \nMore PHP Output
\n";

Note there are a number of different ways of indicating blocks of PHP code (some may need to be turned on in your php.ini file): • Long form: • Shorter form: • Shortest form: This HTML is produced and sent to the client:

“Response”

If the .php file has embedded PHP code, the server first executes the PHP, replacing the PHP code with its output in the document (output uses the echo function) The modified document is then sent to the client Note that the client never sees the PHP code This is important – typically client should not see logic / code that server executes to process requests

First PHP Example OutputOutputOutput More PHP Output




What effect do the \n characters have? – answer: format the HTML visually, but no effect on what is displayed in the browser

Data types (variables are loosely typed): • Float • Integer • Boolean • String: • We have single-quoted and double-quoted string literals: o Double quoted allows for more escape sequences and allows variable values to be written into the string o i.e., rather than outputting the name of the variable, we output its contents, even within a quote.. (see example in a bit) Variables always begin with $ As well as programmer-defined variables, we have predefined variables: • $_SERVER is an array containing much information about the server • $_POST is an array containing variables passed to a script via HTTP POST • $_COOKIE is an array containing cookies • (Use square brackets to access arrays. Arrays can be indexed not only by a number but also by a String: see $_POST example below) Code syntax is very similar to C, Java, or JavaScript Processing HTML Forms: Here is a simple example of an HTML form and a corresponding php script that would allow the user to type his first and last names into a form and be acknowledged with a dynamically generated feedback page: Enter your first name:
Enter your last name:


and here is the corresponding php script that would process this form's entries

Note the use of braces (curly brackets) to insert values into the middle of a string If we prefer to separate a PHP code segment from the rest of our HTML, we can write it in another file as functions, and include it (good for making libraries of functions that you want to make use of on multiple pages on your website) Syntax for declaring functions: function name ( params ) { // statements; // optional return statement; }

Example: functions, includes and emailing In the file “contact.html”: Name Email Comment

In the file “PostForm.php”:

In the file “_email.php”:

• • •





State Control: Cookies and Sessions



• •

HTTP is a ‘stateless’ protocol It is simply defines how clients and servers communicate with each other over the Web • Yet with many Web applications, maintaining state is important o Example: When a customer logs into a site such as Amazon, he/she may go through multiple pages. Information gathered from one page may be needed on another page • We don't want to make him/her reenter information for each page • One way of maintaining state is via Cookies: o Small pieces of information (up to 4K) stored on the client machine o When client connects to a server, the server looks for “its” cookie on the client o Cookies can be read and written on both client and server, and are posted back-and-forth as part of each request and response Cookies in PHP are easy to use: • setcookie() function is called to create a cookie that will be sent to the client • Cookies must be sent prior to the http header: thus, you should determine and set any cookies in PHP mode prior to using any html • $_COOKIE array contains the cookies received from the client machine Thus, to maintain state a server can: • Send the client a cookie the first time the client connects to the server • Update / modify the cookie as client navigates the site • Or send additional cookies • Use the presence and / or value of cookies to discern information about the client • Ex: A repeat customer – time of last visit • Ex: A current customer – last request or last page visited Sessions:

• • •

Cookies are good for keeping track of return visitors For keeping state within a "current" visit, there are better ways that don’t require data to be sent back-and-forth with each request+response PHP allows session tracking which can simplify and streamline the process of maintaining state: When user first logs into (or simply visits) a site, a session is started and a unique, random ID is assigned to that user ID is stored in a cookie or on the URL, but state information (session variables) are stored on the server Any accesses by the same client with the same session ID are recognized and the session variables can be retrieved and used When session is finished (client logs out or browser is closed) the session variables are cleared and the session ID is disposed of Session tracking can be automatically turned on, but if not the programmer must explicitly start a session using session_start(); This should be done at the beginning of the script, prior to any regular html tags It must be done in any script in which the session variables are to be accessed Session variables are accessed through the $_SESSION array

Databases: • Although PHP allows reading/writing simple text files, databases are more efficient and flexible • Most common databases now are relational databases • We have data stored in tables and relate the data from one table to that of another • Access is faster than flat files • Queries to obtain specific sets of data can be done • User has random access to data • Concurrent access handling is built in • Access privileges are built-in Some definitions: • Database o The overall collection of data – may consist of many tables • Table o An individual "relation" in the relational database o Relates keys to values • Table Column o An attribute in the table • Table Row o An entity in the table o Typically has a value for each column • Key o An attribute that uniquely identifies an entity

• •

Foreign Key o Key used to relate data in one table with data in another table Schema o A set of table designs that determine a database o Does not yet include the data – simply shows how it will be structured in the database

Relationships -- how do data in different tables relate?: o One-to-one o An entity in a table corresponds to a single entity in another table o E.g. a “football teams” table and a “managers” table o The relationship is typically established using a foreign key for one or both entities o One-to-many o An entity in a table corresponds to 1 or more entities in another table o E.g. a “football teams” table and a “football players” table o Many-to-many o Multiple entities in one table correspond to multiple entities in another table o E.g. a “football cup competitions” table and a “football teams” table. o This relationship is often defined by a separate table, which in fact changes it into two one-to-many relationships o E.g. We might use a “football cup competitors” table, which has foreign keys to both “football cup competitions” and to “football teams” Accessing a MySQL database from PHP: 1. Establish a connection to the database by calling the following two functions in order (localhost is often used for the database host: this means the webserver and database server are actually on the same physical computer): o mysql_connect(host-name, user-account-name, password); o mysql_select_db(database-name);

4. Close the database connection by calling mysql_close(). This final step is actually optional in PHP, as it will automatically close any open connections once the page has been completely interpreted. For example, the following PHP code will establish a connection to a database called "testdb" on the local machine using a user account name of "testuser" with a password of "testpassword", and then retrieve all of the rows in the table "users" using a SELECT statement, printing out the value of the "name" column on separate lines in the HTML that is being prepared to send to the client: mysql_connect('localhost', 'testuser', 'testpassword'); mysql_select_db('testdb'); $result = mysql_query('SELECT * FROM users'); while ($row = mysql_fetch_array($result)) { echo $row['name'] . '
'; }

Another example: the following code establishes the same connection but this time deletes all rows in the "users" table for which the value of the "name" column is equal to "Sam". The number of rows affected is then displayed mysql_connect('localhost', 'testuser', 'testpassword'); mysql_select_db('testdb'); $result = mysql_query("DELETE FROM users WHERE name = 'sam'"); echo mysql_affected_rows() . '
';

Errors that can occur when connecting to a database include failing to connect, failing to select a database, the inability to execute a query, and no results from a query when some are expected. o The PHP function mysql_error() can be used to obtain details about errors that occur. o The die() function terminates the execution of a script and sends its parameter as a message to the Web browser. E.g: $dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());

2. Through this connection (PHP keeps a handle to the connection internally), execute a SQL statement using mysql_query('SQL-statement'); o (For SELECT statements, the return value of mysql_query() should be assigned to a variable, often called $result). 3. Fetch the results of the query, depending upon the type of SQL statement: o For a SELECT statement, iterate through each row of the returned result set ($result) by calling the mysql_fetch_query($result) function and assigning the return value (an associative array of column values in that row) to a variable (often called $row). The values in $row may then be referenced by the column name of the originating database table o For an INSERT, UPDATE, or DELETE statement, the mysql_affected_rows() function returns the number of rows affected.

It is wise to use the die function with any critical PHP function or operation on which the success of the rest of the script hinges. SQL ‘INSERT’ EXAMPLE – adding a new user to a table (data comes from a signup form) The following definition is assumed for the ‘users’ table: Field Name ID Name Login

Explanation Unique ID (Integer data; primary key; auto_increment) User’s publicly displayable name (Text data) User’s secret login name (Text data)

Password

User’s secret password (Text data)

In signup.html: Please sign up here:
Name:
Login:
Password:


$sql = "UPDATE users SET Password='{$_POST['newPassword']}' WHERE Login='{$_POST['login']}' AND Password='{$_POST['password']}';"; mysql_query($sql); ?>

In signup.php: Simple example displaying multiple rows into an HTML table: