330 likes | 358 Views
Making Database backed Websites. Session 3 Return of the Hypertext Putting it all together. HTML Refresher. <html> <head> <title>A Web Page!</title> </head> <body> <h1>A Web Page!</h1> Woo hoo. It works! </body> </html>. How Does PHP work?.
E N D
Making Database backed Websites Session 3 Return of the Hypertext Putting it all together
HTML Refresher • <html> • <head> • <title>A Web Page!</title> • </head> • <body> • <h1>A Web Page!</h1> • Woo hoo. It works! • </body> • </html>
How Does PHP work? • With HTML all the webserver does when it gets a request is send back the appropriate file. • A page written using PHP will be processed by the webserver before being sent. (Assuming PHP is installed on the server). • PHP stands for PHP: HyperText Preprocessor. • It’s a recursive acronym - typical hackish. • PHP is a programming language that is embedded inside the HTML.
A simple example • <html> • <body> • <?php echo "PHP did this"; ?> • </body> • </html> PHP
The <?php ?> tag • PHP is added to a page using a special tag. • It starts <?php • It ends ?> • Anything in-between is PHP. • Some servers will allow you to use <? and ?> but this can cause problems if you move your site to a server which doesn’t allow this. It’s safest to always use <?php ?>
Variables • Since PHP is a real programming language (unlike HTML which is a markup language) it allows you to define variables. • <?php • $foo = 1; • echo $foo; • ?> • Would output… • 1
Simple programming • You can also perform calculations… • <?php • $a=2; • $b=3; • echo $a+$b; • ?> • Would output… • 5
Simple Data Types • PHP, like SQL can work with a number of different data types. • Strings $foo = "hello"; • Numbers $foo = 4; • $foo = 3.141592653589793238; • Boolean$foo = True;//case insensitive • Resource$foo = mysql_connect • ("localhost","bar","wibble");
Manipulating Strings • $foo = "hello"; • $bar = " world"; • echo $foo.$bar; • Would output… • hello world • Alternatively, this would do the same. • $foo = "hello"; • $foo .= " world"; • echo $foo;
Manipulating Numbers • $foo = 14; • $foo = $foo + 12; • echo $foo; • Would output… • 26 • You can use + - * / % ++ -- = • Note $foo = $bar = 14;is allowed. The expression$bar=14evaluates to 14. So$fooends up as14.
if else elseif • What if you want to do different things depending on user input. • if ($foo == "yes") { • echo "Yes"; • } elseif ($foo == "no") { • echo "No"; • } else { • echo "Maybe"; • } • You can also use != < > <= >= <>
while • There are also constructs to allow you to do something repeatedly, until a certain condition is met. • $i=0; • while ($i < 10) { • print $i."<br>\n"; • $i++; • }
for • Since doing something a set number of times is so common there is a shorthand for it. • for ($i=0; $i < 10; $i++) { • print $i."<br>\n"; • } • This does the same as the previous example.
Functions • The real power of PHP is in the functions that are available. It's functions which will let you connect to the database, or do many other esoteric things. • A function is called like this… • $pos = stripos("hello world","WORLD"); Functionname Parameters
Functions • PHP contains up to 115 packages*, each of which contain numerous functions you can use. • * Depends which packages are installed on the webserver. • 8 packages just deal with databases. We'll use the MySQL package later this session. • You can also… • email, createimages, createPDFs, usecalendars, usemathematicalfunctions, spellcheckers, usestringfunctions, etc.
Arrays • You can also have arrays. An array is a data structure which can store many pieces of data. Each datum* is stored in a element of the array. • $array = Array(); • $array[0] = "foo"; • $array[1] = "bar"; • $arr = Array("foo", "bar"); • $foo = Array("foo" => "bar"); • echo $foo["foo"];
Getting data from a Form • PHP automatically creates a few arrays which contain various pieces of data. • For getting data from a form the two that matter are • $_GET • $_POST • Each element from a form will become an entry in one or other or these arrays.
Getting data from a Form • <form action="foo.php" method="get"> • <input type="text" name="text" value=""> • <input type="submit" value="Add Info"> • </form> • <?php $text = $_GET["text"]; ?> • <html> • <head> • </head> • <body> • You entered <b><?php echo $text?></b> • into the <i>text</i> field. • </body> • </html>
Connecting to the Database • The mysql_connect function takes three parameters. First the machine which the DMBS is on. Second the database username, and lastly the database users password. • @$dbms=mysql_connect("localhost","pete","jester"); • The mysql_select_db function just takes one parameter, the name of the database. • @mysql_select_db("movies") or • die("Failed to connect to database: ".mysql_error()); • mysql_error returns any errors from thedatabase
Performing a Query on the DB • Get the names and dates of birth of all the actors in the actor table. • The SQL for this is • select name, DATE_FORMAT(dob, \"%d %b %Y\") as dob from actors; • The DATE_FORMAT part gets the database to output the date as 17 Jul 1935 rather than it's native 1935-07-17.
Performing a Query on the DB • The PHP then looks like this… • $query = "select name, DATE_FORMAT(dob, \"%d %b %Y\") as dob from actors"; • $result = mysql_query($query); • The first line just sets up a variable which contains the query. The second line runs the query on the database. • Now all we need to do is read the result.
Performing a Query on the DB • For this we use the mysql_fetch_array function. It returns either an array containing the result, or FALSE if there are no more results. • while ($line = mysql_fetch_array($result)) { • $name=$line["name"]; • $dob=$line["dob"]; • print $name." - ".$dob."<br>\n"; • }
Inserting data into the DB • All SQL commands are known as queries, regardless of whether you're extracting data or not. So to insert data you just use a query. • $query = "insert into actors (name, dob) values (\"$name\", \"$year-$month-$date\")"; • $result = mysql_query($query); • With queries that don't return data, (ie aren't really queries) mysql_query returns True on success and False on failure.
Idempotent & Replay • What happens when you add data to a database, and then reload the page. • It gets added again! • This is known as a replay, or when done malevolently a replay attack. • The solution is to make your pages idempotent. • http://en.wikipedia.org/wiki/Idempotent (for the mathematically inclined) • Put simply something is idempotent if doing it repeatedly has the same effect as doing it once.
Idempotent & Replay • There are many strategies you could use to enforce idempotency. • A simple one would be to check to see if the name and date of birth was already in the database before attempting to add it. If it was, then just don't add it. • There are more general solutions but they are typically more complex. For example – using nonces.
Errors • You'll make mistakes unless you're super-human. • PHP will output errors into your webpage to tell you what's gone wrong. These vary in how meaningful they are. • To prevent errors from being reported put @ at the start of a line. This is useful for errors such as bad passwords in the database connect function. • A text editor which tells you line numbers is useful for finding what PHP is talking about.
Including other PHP files • One major time saver is making common PHP files which can then be referenced by all the pages on a site. • For example, all the navigation and design of a site can be in a couple of PHP files which you include in all pages. • Then if you want to change the site design you only have one or two files to edit, rather than every page on the site.
Including other PHP files • As you get more familiar with PHP you'll find yourself doing the same sorts of things over and over. • Often these functions can be put into scripts which you can include when needed rather than rewriting every time. Eventually you'll have a toolkit which makes building sites much faster. • include "foo.php"; • include_once "foo.php"; • require_once "bar.php";
Basic Security • Anyone can write a HTML page which sends data to your script. • If they have seen the code for your pages then they may be able to get your script to do things that may damage your data. • Work assuming that all the code of your pages can be seen by anyone. Most security breaches are committed by insiders or ex-insiders. • Security through obscurity is essentially no security at all.
Basic Security • PHP has a number of server configurations which can increase security. It's good to get in the habit of writing PHP on a locked down server. • By including PHP scripts from somewhere which is not in the publicly accessible webspace an attacker cannot see those scripts even if there is a breach in the PHP configuration.
Basic Security • Lastly, if you don't do any checking on your incoming variables it's sometimes possible for a user to input values which case unexpected behaviour. • For example, what happens if an actors name includes a " character? • There are String functions which can take care of these problems.
Questions? Presentation online at… http://people.surfaceeffect.com/pete/ tech/howitworks/dbwebsites/