LIS651 lecture 3 taming PHP Thomas Krichel 2005-11-12.

Slides:



Advertisements
Similar presentations
PHP: Date() Function The PHP date() function formats a timestamp to a more readable date and time.
Advertisements

Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizards Guide to PHP by David Lash.
LIS651 lecture 3 taming PHP Thomas Krichel
LIS651 lecture 1 PHP basics, database introduction Thomas Krichel
LIS651 lecture 3 functions and arrays Thomas Krichel
LIS651 lecture 2 mySQL and PHP mySQL function Thomas Krichel
LIS651 lecture 1 arrays functions & sessions Thomas Krichel
LIS651 lecture 3 functions & sessions Thomas Krichel
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
PHP SQL. Connection code:- mysql_connect("server", "username", "password"); Connect to the Database Server with the authorised user and password. Eg $connect.
Widhy Hayuhardhika NP, S.Kom. Overview of database structure Connecting to MySQL database Selecting the database to use Using the require_once statement.
Presenter: James Huang Date: Sept. 29,  HTTP and WWW  Bottle Web Framework  Request Routing  Sending Static Files  Handling HTML  HTTP Errors.
PHP Hypertext Preprocessor Information Systems 337 Prof. Harry Plantinga.
Lecture 6/2/12. Forms and PHP The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input When dealing with HTML forms.
Web Database Programming Connecting Database to Web.
Manipulating MySQL Databases with PHP. PHP and mySQL2 Objectives Connect to MySQL from PHP Learn how to handle MySQL errors Execute SQL statements with.
Intermediate PHP & MySQL
PHP and MySQL Web Development tMyn1 PHP and MySQL Web Development When you install PHP, you can select from a number of extensions. The MySQL support in.
15. User Authentication, Form Validation, Paging. M. Udin Harun Al Rasyid, S.Kom, Ph.D
SJSU CS157B Dr. Lee1  2004 Jenny Mitchell Two Useful Tools You Can’t Live Without by Jenny Mitchell SJSU CS157B Section PHP and MySQL.
Introduction to PHP and Server Side Technology. Slide 2 PHP History Created in 1995 PHP 5.0 is the current version It’s been around since 2004.
(c) Manzur Ashraf, Short course, KFUPM PHP & MySQL 1 Basic PHP Class 2.
INTERNET APPLICATION DEVELOPMENT For More visit:
Lecture 6 – Form processing (Part 1) SFDV3011 – Advanced Web Development 1.
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
LIS651 lecture 7 PHP mySQL Thomas Krichel
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
Class 8Intro to Databases Authentication and Security Note: What we discuss in class today covers moderate to low security. Before you involve yourself.
INTERNET APPLICATION DEVELOPMENT For More visit:
Validated.php
MySQL + PHP.  Introduction Before you actually start building your database scripts, you must have a database to place information into and read it from.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
© 2003 By Default! A Free sample background from Slide 1 Week 2  Free PHP Hosting Setup  PHP Backend  Backend Security 
SHOPPING CARTS CHAPTER 19. E-COMMERCE Typically, an e-commerce site will have public pages and admin pages.
PHP meets MySQL.
Accessing MySQL with PHP IDIA 618 Fall 2014 Bridget M. Blodgett.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to MySQL Lab no. 10 Advance Database Management System.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL.
1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices.
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
1. Visit 2. Click on
CHAPTER 9 PHP AND MYSQL. A POSSIBLE SITE CONFIGURATION Application Folder index.php includes (folder)header.phpfooter.phpstyle.cssmodel (folder)mysqli_connect.php.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
Controlling Web Site Access Using Logins CS 320. Basic Approach HTML form a php page that collects the username and password  Sends them to second PHP.
PHP getting data from a MySQL database. Replacing XML as data source with MySQL Previously we obtained the data about the training session from an XML.
>> PHP: Insert Query & Form Processing. Insert Query Step 1: Define Form Variables Step 2: Make DB Connection Step 3: Error Handling Step 4: Define the.
NMD202 Web Scripting Week5. What we will cover today PHP & MySQL Displaying Dynamic Pages Exercises Modifying Data PHP Exercises Assignment 1.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
PHP and SQL Server: Connection IST2101. Typical web application interaction (php, jsp…) database drivers 2IST210.
Class 3Intro to Databases Class 4 Simple Example of a Database We’re going to build a simple example of a database, which will allow us to register users.
CSC 2720 Building Web Applications Accessing MySQL from PHP.
MySQL MySQL and PHP – interacting with a database.
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
Radoslav Georgiev Telerik Corporation
Web Database Programming Using PHP
ASP.NET Programming with C# and SQL Server First Edition
LIS651 lecture 3 functions & sessions
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
Web Database Programming Using PHP
Web Design and Development
Web Design and Development
PHP: Security issues FdSc Module 109 Server side scripting and
MySQL Web Application Connecting to a MySQL database
MySQL Web Application Connecting to a MySQL database
Presentation transcript:

LIS651 lecture 3 taming PHP Thomas Krichel

functions The PHP function reference is available on its web site It shows the impressive array of functions within PHP. But one of the strengths of PHP is that you can create your own functions as you please. If you recreate one of the built-in functions, your own function will have no effect.

example Stephanie Rubino was an English teacher and objects to sentences like You have ordered 1 bottles of Grosswald Pils. Let us define a function rubino_print(). It will take three arguments –a number to check for plural or singular –a word for the singular –a word for the plural

function and parameters use the keyword "function" and declare your parameters, as in: function rubino_print ($number, $singular,$plural) { if($number == 1) { print "one $singular"; } else { print "$number $plural"; }

default arguments Sometimes you want to allow a function to be called without giving all its arguments. You can do this by declaring a default value. For the previous example function thomas_need($thing='beer') { print "I need $thing\n"; } thomas_need(); // prints: I need beer thomas_need('sex'); // prints: I need sex

rubino_print using common plurals function rubino_print ($num, $sing,$plur=1) { if($num == 1) { print "one $sing"; } elseif($plur ==1) { print "$num $sing"."s"; } else { print "$num $plur"; }

return value Up until now we have just looked at the effect of a function. return is a special command that return a value. When return is used, the function is left.

rubino_print with return function rubino_print ($number, $singular,$plural) { if($number == 1) { return "one $singular"; } return "$number $plural"; } $order=rubino_print(2,"beer","beers"); print "you ordered $order\n"; // prints: you ordered 2 beers.

utility function from php.net function mysql_fetch_all($query) { if($err=mysql_error()) { return $err;} if(mysql_num_rows($r)) { while($row=mysql_fetch_array($r)) {$result[]=$row; } return $result;}} if(is_array($rows=mysql_fetch_all($query)) { // do something } else { if (! is_null($rows)) { die("Query failed!");} }

visibility of variables variables used inside a function are not visible from the outside. Example $beer="Karlsberg"; function yankeefy ($name='Sam Adams') { $beer=$name; } yankeefy(); print $beer;// prints: Karlsberg the variable inside the function is something different than the variables outside.

accessing global variables. There are two ways to change a global variable, i.e. one that is defined in the main script. One is just to call it as $GLOBAL['name'] where name is the name of the global variable. function yankeefy ($name="Sam Adams") { $GLOBAL['beer']="name"; }

brewer_quiz.php: introduction <?php $brewers=array('Großwald Brauerei','Homburger Brauhaus', 'Karlsberg Brauerei','Ponter Hausbrauerei', 'Saarfürst Merziger Brauhaus','Mettlacher Abtei-Bräu','Körpricher Landbräu','Brauerei G.A. Bruch','Neufang Brauerei','Zum Stiefel'); $form_top=" \n"; $form_submit=' '."\n"; $form_end=' ';

brewer_quiz.php: form building function build_form($answer,$comment) { print " Take the Saarland brewery challenge \n"; print $GLOBALS['form_top']; print " "; print $GLOBALS['form_submit']; print $GLOBALS['submit_check']; print $GLOBALS['form_end']; print $comment; }

brewer_quiz.php: form processing function process_form($answer,$brewers) { $r[]=$answer; foreach($brewers as $brew) { if($answer == "$brew") { $r[]=' Congradulation! This is correct! '; return $r; } $r[]=' This is a bad answer, try again! '; return $r; }

brewer_quiz.php main part if($_GET['submitted']) { $from_form=process_form($_GET['guess'],$brewers); } build_form($from_form[0],$from_form[1]) ; ?>

working with many source files Many times it is useful to split a PHP script into several files. PHP has two mechanisms. require(file) requires the to be included. If the file is not there, PHP exits with an error. include(file) includes the file.

require() and include() Both assume that you leave PHP. Thus within your included file you can write simple HTML. If you want to include PHP in your included file, you have to surround it by, just like in a PHP script. Here is an example to use include to build the basic web page.

top.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " $title

bottom.html <img style="border: 0pt" src=" alt="Valid XHTML 1.0!" height="31" width="88" />

validated.php <?php $title="my basic page\n"; include("top.html"); print " hello, world "; include("bottom.html"); ?>

trouble $title in the top.html is not understood as the title. It reads as $title, which means "idiot" for your web user. Even if you replace $title with $title is empty. The definition from the outer file is not seen in the included file. So you have to split into three files, and print the title in the main file. I leave that to you to figure out.

login.php & create_account.php Both require a database that has three fields –id which is an auto_increment int acting as a handle –username is the username of the account. it must be unique and this is enforced by mySQL –password is a varchar(41) because the sha1 of the password is stored. This is 40 chars long.

login.php function show_form($message) { print " $message Login Username <input type=\"text\" name=\"username\" maxlength=\"15\" value=\"$_POST[username]\" /> Password Not yet a member? Create an account ! "; }

function process_form() { $username=trim($_POST['username']); $pass=trim($_POST['pass']); $sha_pass=sha1($pass); $db=mysql_connect('localhost','krichel','laempel'); $query="SELECT * FROM beer_shop.users WHERE username='$username' AND password = '$sha_pass'"; $result=mysql_query($query); $error=mysql_error(); if($error) { return "Sorry: $query gives an error $error"; } $affected=mysql_affected_rows(); if(! ($affected)) {return "Invalid username or password";} }

login.php (end) if($_POST['submitted']) { $error=process_form(); if($error) { show_form($error); } else { $user=$_POST['username']; print " Welcome to $user "; } else { show_form(''); }

create_account.php function show_form($message) { print " $message Create Account Please complete the form below to create your account. <form action=\"$_SERVER[PHP_SELF] \" method=\"post\"> <input type=\"hidden\" name=\"submitted\" value=\"1\" /> It must be more than 5 characters and cannot be your username. ";

create_account.php Password Password <input type=\"password\" name=\"pass1\" value=\"$_POST[pass1]\"/>Confirm Password <input type=\"password\" name=\"pass2\" value=\"$_POST[pass2]\"/> The password you enter will be used to access your account. It must be more than 5 characters and cannot be your username. <input type=\"submit\" value=\"Create Account\" /> "; }

create_account.php function process_form() { $username=trim($_POST['username']); $pass1=trim($_POST['pass1']); $pass2=trim($_POST['pass2']); if(strlen($username)<6) { return "Username is too short."; } if(! ($pass1 == $pass2)) {return "Passwords do not match.";} $pass=$pass1; if($pass == $username) { return "Your username can not be your password.";

create_account.php if(strlen($pass)<6) {return "Password is too short.";} $sha_pass=sha1($pass); $db=mysql_connect('localhost','krichel','laempel'); $query="INSERT INTO beer_shop.users VALUES ('','$username','$sha_pass')"; $result=mysql_query($query); $error=mysql_error(); if($error == "Duplicate entry '$username' for key 2") { return "Sorry: Username $username is already taken, choose another."; } else {print " Thank you for registering with us! ";} } 1

create_account.php (end) if($_POST['submitted']) { $error=process_form(); if($error) { show_form($error); } else { show_form(''); }

sessions You will recall that HTTP is a stateless protocol. Each request/response is self-contained. Statefulness is crucial in Web applications. Otherwise users have to authenticate every time they access a new page. Traditionally, one way to create statefullness is to use cookies. PHP uses cookies to create a concept of its own, sessions, that makes it all very easy.

cookies A cookie is a piece of attribute/value data. A server can send cookies as value of a HTTP header Set-Cookie:. Multiple headers may be sent. When the client visits the web site again, it will send the cookie back to the server with a HTTP header Cookie:

Set-Cookie Set-Cookie: name=value; [expires= date;] [path=path;] [domain= domain] [secure] where –name= is the variable name set in the cookie –value= is the variable's value –date= is a date when the cookie expires –path= restricts the cookie to be sent only when requests to a path starting with path are made –domain= restricts the sending of the cookie to a certain domain –secure restricts transmission to https

Cookies: The browser compares the request it wants to make with the URL and the domain that sent the cookie. If the path is not set the cookie will only be sent to a request with the originating URL. If the cookie matches the request a request header of the form Cookie: name1=value1 ; name2=value2 is sent.

sessions Sessions are a feature of PHP. PHP remembers a session through a special cookie PHPSESSID. To activate the sessions, include session_start(); at the beginning of your script, before any printing has been done. One a session is active, you have a special super-global variable $_SESSION. Session data is stored in special files on wotan.

$_SESSION This is an array where you can read and set variables that you want to keep during the session. if($_SESSION[user_name]) { print "welcome $_SESSION[user_name]"; } else { // show users login form print login_form(); }

ending sessions At 9 and 39 past each hour, wotan deletes all session files that have not been changed for 24 minutes or more. If you want to remove a session yourself, you can call session_destroy() in your script.

visit.php <?php $top='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> '; $bottom=' <img style="border: 0pt" src="/valid-xhtml10.png" alt="Valid XHTML 1.0!" height="31" width="88" /> ';

visit.php session_start(); $current=mktime(); // look at the current time if($_SESSION[last_click]) { $passed=$current-$_SESSION[last_click]; $to_print.="$passed seconds have passed since your last visit.\n"; $_SESSION[last_click]=$current; } else { $to_print="This is your first visit.\n"; $_SESSION[last_click]=$current; } print "$top\n$to_print\n$bottom"; ?>

Thank you for your attention! Please switch off machines b4 leaving!