530 likes | 1.03k Views
PHP & MySQL. Christos Efstratiou. Architecture. Web Browser. Request Page. Web Server. Page with PHP code. Read File. Send HTML page. Pass PHP page and server variables (GET attributes, Server settings, etc.). Generate HTML page. PHP Interpreter. MySQL. Interact with
E N D
PHP & MySQL Christos Efstratiou
Architecture Web Browser Request Page Web Server Page with PHP code Read File Send HTML page Pass PHP page and server variables (GET attributes, Server settings, etc.) Generate HTML page PHP Interpreter MySQL Interact with Database
PHP Syntax • In general PHP code is embedded into web pages • In most cases you will have pages that contain only PHP code • Pages with PHP code should have the extension: .php, .php3, .php4 • Examples: <? $name =“World”; ?> <html> <body> <h1>Hello, <? echo $name; ?> </h1> </body> </html> <? include(“header.html”); if (strpos($_SERVER[“HTTP_USER_AGENT”], “MSIE”) !== FALSE) { echo “You are using Internet explorer!”; } include(“footer.html”); ?>
PHP Syntax - Variables • PHP does not support explicit type definition. $foo ="0";// $foo is string (ASCII 48)$foo += 2;// $foo is now an integer (2)$foo = $foo + 1.3;// $foo is now a float (3.3) • You can enforce a variable type by using type casting. $foo =10;// $foo is an integer$bar=(boolean) $foo;// $bar is boolean (true) • Comparing values. $x= 0; $y=false; if ( $x==$y ) // this is true • Comparing values and types. $x= 0; $y=false; if ( $x===$y ) // this is not true, different types
PHP Syntax - Strings • There are two main ways of specifying strings • Using single quotes: text represented exactly as typed $str=‘This is an \n example’;// \n is not expanded to new line • Using double quotes: expands variables and supports special characters $val=5; $str=“The value is: $var \n”;// The string is: “The value is: 5” with a new line at the end • Concatenation with a “dot” $val=5; $str=‘The ’ . ‘value is: ’ .$var . “\n”; • Single characters in a string $str{2} =‘T’;// The third character of string
PHP Syntax - Arrays • PHP arrays are dynamic. Their size expands as needed. • PHP supports associative arrays: Array indices can be of any type not just integers. Key types can be mixed in the same array. $arr[1] = ‘Test’;// Using integers as keys $arr[‘first’] = ‘Test’; // Using strings as keys • Defining arrays $arr =array("foo"=>"bar",12=>true); $arr[5]=10;// The array is now: (“foo”=> “bar”, 12=>true, 5=>10) • Multidimensional arrays $arr =array( “first"=> array("bar",‘Test’), “second"=> array(1=>true,2=>false) );
PHP Syntax - Control Structures • All the control structures you would find in C • If (…) {…} elseif (…) {…} else {…} • while(…) {…} • for (…;…;…) {…} • do {…} while (…) • switch (...) { case …: …; case …: …; default: …; } • foreach : used for traversing associative arrays $foo = array(“Nigel”=>“nigel@comp.lancs.ac.uk” , “Chris”=>“efstrati@comp.lancs.ac.uk”, “Rob”=>“r.hooper@lancaster.ac.uk”, “Oliver”=>“stortz@comp.lancs.ac.uk”); foreach ($foo as $name=>$email) { echo“<p>Name: $name <br/>”; echo“Email: $email </p>”; }
PHP Syntax - Functions • Function definition <? function foo($arg_1, $arg_2, /* ..., */ $arg_n){ echo "Example function.\n"; return $retval;}?> • Global variables are only accessible if declared in a function <? $gval = 5;// Global variable function foo(){ global $gval ;// The function has now access to the global var (by reference) echo “Gval: $gval.\n";}?>
Pointers & pass by reference • All value assignments in PHP are “by copy”, even when working with arrays or objects. • There are no explicit pointer variables but you can assign variables by reference. $foo = 'Bob'; // Assign the value 'Bob' to $foo$bar = &$foo; // Reference $foo via $bar.$bar = "My name is $bar"; // Alter $bar...echo $foo; // $foo is altered too. • Passing function parameters by reference and returning references function &add_some_extra(&$string){ $string.= “some more"; return $string; }$foo=&add_some_extra($str);
Classes • Support for object orientation in PHP has improved with version 4 and is much more substantial in version 5. class Cart { var $items; // Items in our shopping cart // Add $num articles of $artnr to the cartfunction add_item($artnr, $num) {$this->items[$artnr] += $num; }} $myCart = new Cart; $myCart->myVar =“test"; // This object has a new attribute not defined by the class • Inheritance with the “extends” keyword class Named_Cart extends Cart { ……… }
Serialization • Serialization is supported through functions “serialize” and “unserialize” include("classa.inc");$a = new A;$s = serialize($a); // store $s somewhere$fp = fopen("store", "w");fwrite($fp, $s);fclose($fp); include("classa.inc");$s = implode("", file("store"));$a = unserialize($s);// now use the object. $a->show_one();
OO support in Version 5 • PHP v5 has an extended support for OO. • Supports variable and function scopes using “public”, “protected”, “private” keywords. • Supports static (class based) methods and variables. • Supports abstract classes, similar to virtual classes in C++. • Supports the definition of interfaces. • Includes a complete Reflection API • Includes an exception handling mechanism • From more info check the online manual:http://www.php.net/manual/en/
Programming techniquesSeparate code from GUI • The idea is to have separate HTML/CSS files to handle the user interface and php files to handle the application’s operation. • Use of templates (template support is provided by PhpLib). • Nested templates can be used to break the UI into blocks. E.g. one template for the main page, a nested template for a content block within the main page.
Programming techniquesTemplate example mainPage.html <html> <head><title>{PAGETITLE}</title></head> <body> <table> <tr><td colspan=“2”> <h1>{PAGETITLE}</h1></td></tr> <tr> <td>{OUT}</td> <td>Content</td> </tr> </table> </body> </html> index.php include(“template.inc”) $tpl = new Template(“mytemplates/”); // Create template object $tpl->set_file(“MainPage”, “mainPage.html”); // Load the template file $tpl->set_var(“PAGETITLE”, “My Page”); // Assign values to variables $tpl->set_var(“OUT”, “Test content”); $tpl->parse(“Output”, “MainPage”); // Parse page into variable Output $tpl->p(“Output”); // Print the Output var
Programming techniquesTemplate example mainPage.html <html> <head><title>My Page</title></head> <body> <table> <tr><td colspan=“2”> <h1>My Page</h1></td></tr> <tr> <td>Test content</td> <td>Content</td> </tr> </table> </body> </html> index.php include(“template.inc”) $tpl = new Template(“mytemplates/”); // Create template object $tpl->set_file(“MainPage”, “mainPage.html”); // Load the template file $tpl->set_var(“PAGETITLE”, “My Page”); // Assign values to variables $tpl->set_var(“OUT”, “Test content”); $tpl->parse(“Output”, “MainPage”); // Parse page into variable Output $tpl->p(“Output”); // Print the Output var
Programming techniquesTemplate example 2 <html> <head><title>{PAGETITLE}</title></head> <body> <table> <tr><td colspan=“2”> <h1>{PAGETITLE}</h1></td></tr> <tr> <td>{OUT}</td> <td>Content</td> </tr> </table> </body> </html> include("./template.inc"); $t = new Template("/page/to/webserver/template", "keep"); // define variables named page and box, referencing files $t->set_file(array( "page" => "page.ihtml", "box" => "box.ihtml")); // define variable TITLE and PAGETITLE $t->set_var(array("TITLE" => "Testpage", "PAGETITLE" => “test")); # extract the block "row" from "box", create a reference to {rows}". $t->set_block("box", "row", "rows"); # define NUM and BIGNUM, then append "row" to "rows"... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array("NUM" => $n, "BIGNUM" => $nn)); $t->parse("rows", "row", true); } # build out from box, then build output from page... $t->parse("OUT", "box“); $t->parse(“Output”, "page")); # finish out and print it. $t->p("OUT"); ?> <!– start box --> <table> <tr> <td colspan=“2”><b>{TITLE}</b></td> </tr> <!– BEGIN row --> <tr> <td>{NUM}</td> <td>{BIGNUM}</td> </tr> <!– END row --> </table> <!– end box -->
Programming techniquesTemplate example 2 <html> <head><title>test</title></head> <body> <table> <tr><td colspan=“2”> <h1>test</h1></td></tr> <tr> <td>{OUT}</td> <td>Content</td> </tr> </table> </body> </html> include("./template.inc"); $t = new Template("/page/to/webserver/template", "keep"); // define variables named page and box, referencing files $t->set_file(array( "page" => "page.ihtml", "box" => "box.ihtml")); // define variable TITLE and PAGETITLE $t->set_var(array("TITLE" => "Testpage", "PAGETITLE" => “test")); # extract the block "row" from "box", create a reference to {rows}". $t->set_block("box", "row", "rows"); # define NUM and BIGNUM, then append "row" to "rows"... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array("NUM" => $n, "BIGNUM" => $nn)); $t->parse("rows", "row", true); } # build out from box, then build output from page... $t->parse("OUT", "box“); $t->parse(“Output”, "page")); # finish out and print it. $t->p("OUT"); ?> <!– start box --> <table> <tr> <td colspan=“2”><b>Testpage</b></td> </tr> <!– BEGIN row --> <tr> <td>{NUM}</td> <td>{BIGNUM}</td> </tr> <!– END row --> </table> <!– end box -->
Programming techniquesTemplate example 2 <html> <head><title>test</title></head> <body> <table> <tr><td colspan=“2”> <h1>test</h1></td></tr> <tr> <td>{OUT}</td> <td>Content</td> </tr> </table> </body> </html> include("./template.inc"); $t = new Template("/page/to/webserver/template", "keep"); // define variables named page and box, referencing files $t->set_file(array( "page" => "page.ihtml", "box" => "box.ihtml")); // define variable TITLE and PAGETITLE $t->set_var(array("TITLE" => "Testpage", "PAGETITLE" => “test")); # extract the block "row" from "box", create a reference to {rows}". $t->set_block("box", "row", "rows"); # define NUM and BIGNUM, then append "row" to "rows"... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array("NUM" => $n, "BIGNUM" => $nn)); $t->parse("rows", "row", true); } # build out from box, then build output from page... $t->parse("OUT", "box“); $t->parse(“Output”, "page")); # finish out and print it. $t->p("OUT"); ?> <!– start box --> <table> <tr> <td colspan=“2”><b>Testpage</b></td> </tr> {rows} </table> <!– end box --> <!– Box row --> <tr> <td>{NUM}</td> <td>{BIGNUM}</td> </tr>
Programming techniquesTemplate example 2 <html> <head><title>test</title></head> <body> <table> <tr><td colspan=“2”> <h1>test</h1></td></tr> <tr> <td>{OUT}</td> <td>Content</td> </tr> </table> </body> </html> include("./template.inc"); $t = new Template("/page/to/webserver/template", "keep"); // define variables named page and box, referencing files $t->set_file(array( "page" => "page.ihtml", "box" => "box.ihtml")); // define variable TITLE and PAGETITLE $t->set_var(array("TITLE" => "Testpage", "PAGETITLE" => “test")); # extract the block "row" from "box", create a reference to {rows}". $t->set_block("box", "row", "rows"); # define NUM and BIGNUM, then append "row" to "rows"... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array("NUM" => $n, "BIGNUM" => $nn)); $t->parse("rows", "row", true); } # build out from box, then build output from page... $t->parse("OUT", "box“); $t->parse(“Output”, "page")); # finish out and print it. $t->p("OUT"); ?> <!– start box --> <table> <tr> <td colspan=“2”><b>Testpage</b></td> </tr> {rows} </table> <!– end box --> <tr> <td>1</td> <td>10</td> </tr>
Programming techniquesTemplate example 2 <html> <head><title>test</title></head> <body> <table> <tr><td colspan=“2”> <h1>test</h1></td></tr> <tr> <td>{OUT}</td> <td>Content</td> </tr> </table> </body> </html> include("./template.inc"); $t = new Template("/page/to/webserver/template", "keep"); // define variables named page and box, referencing files $t->set_file(array( "page" => "page.ihtml", "box" => "box.ihtml")); // define variable TITLE and PAGETITLE $t->set_var(array("TITLE" => "Testpage", "PAGETITLE" => “test")); # extract the block "row" from "box", create a reference to {rows}". $t->set_block("box", "row", "rows"); # define NUM and BIGNUM, then append "row" to "rows"... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array("NUM" => $n, "BIGNUM" => $nn)); $t->parse("rows", "row", true); } # build out from box, then build output from page... $t->parse("OUT", "box“); $t->parse(“Output”, "page")); # finish out and print it. $t->p("OUT"); ?> <!– start box --> <table> <tr> <td colspan=“2”><b>Testpage</b></td> </tr> {rows} </table> <!– end box --> <tr> <td>1</td> <td>10</td> </tr> <tr> <td>2</td> <td>20</td> </tr>
Programming techniquesTemplate example 2 <html> <head><title>test</title></head> <body> <table> <tr><td colspan=“2”> <h1>test</h1></td></tr> <tr> <td>{OUT}</td> <td>Content</td> </tr> </table> </body> </html> include("./template.inc"); $t = new Template("/page/to/webserver/template", "keep"); // define variables named page and box, referencing files $t->set_file(array( "page" => "page.ihtml", "box" => "box.ihtml")); // define variable TITLE and PAGETITLE $t->set_var(array("TITLE" => "Testpage", "PAGETITLE" => “test")); # extract the block "row" from "box", create a reference to {rows}". $t->set_block("box", "row", "rows"); # define NUM and BIGNUM, then append "row" to "rows"... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array("NUM" => $n, "BIGNUM" => $nn)); $t->parse("rows", "row", true); } # build out from box, then build output from page... $t->parse("OUT", "box“); $t->parse(“Output”, "page")); # finish out and print it. $t->p("Output"); ?> <!– start box --> <table> <tr> <td colspan=“2”><b>Testpage</b></td> </tr> <tr> <td>1</td> <td>10</td> </tr> <tr> <td>2</td> <td>20</td> </tr> </table> <!– end box -->
Programming techniquesTemplate example 2 <html> <head><title>test</title></head> <body> <table> <tr><td colspan=“2”> <h1>test</h1></td></tr> <tr> <td> <table> <tr> <td colspan=“2”><b>Testpage</b></td> </tr> <tr> <td>1</td> <td>10</td> </tr> <tr> <td>2</td> <td>20</td> </tr> </table> </td> <td>Content</td> </tr> </table> </body> </html> include("./template.inc"); $t = new Template("/page/to/webserver/template", "keep"); // define variables named page and box, referencing files $t->set_file(array( "page" => "page.ihtml", "box" => "box.ihtml")); // define variable TITLE and PAGETITLE $t->set_var(array("TITLE" => "Testpage", "PAGETITLE" => “test")); # extract the block "row" from "box", create a reference to {rows}". $t->set_block("box", "row", "rows"); # define NUM and BIGNUM, then append "row" to "rows"... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array("NUM" => $n, "BIGNUM" => $nn)); $t->parse("rows", "row", true); } # build out from box, then build output from page... $t->parse("OUT", "box“); $t->parse(“Output”, "page")); # finish out and print it. $t->p("OUT"); ?>
Programming techniquesTemplate example 2 <html> <head><title>test</title></head> <body> <table> <tr><td colspan=“2”> <h1>test</h1></td></tr> <tr> <td> <table> <tr> <td colspan=“2”><b>Testpage</b></td> </tr> <tr> <td>1</td> <td>10</td> </tr> <tr> <td>2</td> <td>20</td> </tr> </table> </td> <td>Content</td> </tr> </table> </body> </html>
Interacting with the user • Calling a web page (simple ) • URL parameters e.g.http://www.com/mypage.php?a=alpha&b=beta • Forms, either through GET or POST methods • A php script can gain access to parameters passed by user through two built in variables: • $_GET • $_POST • URL parameters example. The values are specified in the $_GET variable as: $_GET = array(“a”=>”alpha”, “b”=>”beta”);
Handling Forms <form method=“post” action=“index.php”> <input type=“hidden” name=“id” value=“100” /> <table> <tr> <td>User</td> <td><input type=“text” name=“user” /></td> </tr> <tr> <td>Password</td> <td><input type=“password” name=“passwd” /> </td> </tr> <tr> <td colspan=“2”> <input type=“submit” name=“Login” value=“Login” /> </td> </tr> </table> </form>
Handling Forms <form method=“post” action=“index.php”> <input type=“hidden” name=“id” value=“100” /> <table> <tr> <td>User</td> <td><input type=“text” name=“user” /></td> </tr> <tr> <td>Password</td> <td><input type=“password” name=“passwd” /> </td> </tr> <tr> <td colspan=“2”> <input type=“submit” name=“Login” value=“Login” /> </td> </tr> </table> </form> $ok = false; if (array_key_exists(“submit”, $_POST) && ($_POST[“submit”] == “Login”) ) { $ok = CheckLogin( $_POST[“id”], $_POST[“user”], $_POST[“passwd”]); } if ($ok) { include(“restrictedArea.html”); } else { include(“loginForm.html”); }
Handling Forms <form method=“get” action=“index.php”> <input type=“hidden” name=“id” value=“100” /> <table> <tr> <td>User</td> <td><input type=“text” name=“user” /></td> </tr> <tr> <td>Password</td> <td><input type=“password” name=“passwd” /> </td> </tr> <tr> <td colspan=“2”> <input type=“submit” name=“Login” value=“Login” /> </td> </tr> </table> </form> $ok = false; if (array_key_exists(“submit”, $_ GET) && ($_ GET[“submit”] == “Login”) ) { $ok = CheckLogin( $_GET[“id”], $_GET[“user”], $_GET[“passwd”]); } if ($ok) { include(“restrictedArea.html”); } else { include(“loginForm.html”); }
Handling Forms • Protection from user input. Data received by a form should not be trusted. • Functions that remove html code from source data • htmlspecials($str): convert HTML special characters to HTML entities (e.g. "). • html_entity_decode($str): reverse, convert entities to HTML characters. • striptags($str): remove HTML and PHP tags from a string. • Validate input using regular expressions • example: validate an e-mail address $ret = ereg(‘^([a-z0-9_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,4}$’, $string);
Sessions • HTTP communication is inherently stateless • The way to handle state information is through cookies. • PHP offers a built in mechanism for maintaining session information (hiding the cookie handling from the developer)
Sessions • session_start()creates a session or resumes the current one being passed via a cookie. • $_SESSIONthis array is used for assigning session variables or retrieving existing ones • session_destroy()ends an existing session (e.g. when you logout).
Sessions <? // Login page session_start(); // Process the login form …………………… // Login is completed $_SESSION[‘user’] = $_POST[‘user’]; $_SESSION[‘passwd’] = $_POST[‘passwd’]; // Redirect to the private page header("Location: ”. ”http://www.server.com/nextpage.php”);?> <? // next page session_start(); // Check login user if (!array_key_exists(“user”, $_SESSION)) { // No user logged in echo “You need to login first”; exit(); } echo “Hello “. $_SESSION[“user”] .”!<br/>”; ?>
Sessions • With sessions you can assign an arbitrary number of data to the $_SESSION variable. • The data is stored on the server side and only a session id is passed through cookies to the web client. • You can manage the timeout of sessions as you would with any cookie.
Authentication • It is simple to implement authentication through sessions. • The main advantage compared to HTTP authentication is that username and password are transmitted only once (login) and not in every request. • Permissions are handled by your code and do not rely on directories. • The general approach is to save the username and password in the session and check on every page that they are the correct ones. If not redirect to the login page.
MySQL • Limittations of MySQL • Does not support transactions. Cancelling groups of actions should be implemented by the developer. • Does not support referential integrity. Needs to be done programmatically • Does not support nested selections. There are ways to overcome this but they are not very efficient. • But in general it’s a reliable database.
MySQL management • The tool that you would mostly use is MySQLAdmin. A Web frond end for database management. • You would use it for setting up databases, creating database users. • During development, you would use it for testing queries before importing them into your code. • You would use it for debugging the results of your application (did the insert command work alright?)
MySQL Interaction • The interaction with MySQL server consists of the following steps: • Connect to MySQL server. This requires a username and a password. • Select the active database. • Perform SQL queries and retrieve results.
PHP Support for MySQL • Connection $link = mysql_connect(“localhost”, “dbuser”, “dbpass”); If ($link == false) die(“Could not connect: “. mysql_error()); • Database selection $link = mysql_select_db(“myDatabase”, $link); If ($link == false) die(“Could not select database: “. mysql_error()); • Perform a query $query = “INSERT INTO contacts (name, email) VALUES (‘Chris’, ‘efstrati@comp.lancs.ac.uk’)”; $res = mysql_query($query, $link); If ($res == false) echo “Could not perform insert: “. mysql_error(); else { $userID = mysql_insert_id($link); echo “New user id: $userID”; }
MySQL retrieving results $query = “SELECT * FROM contacts”; $res = mysql_query($query, $link); while ($record = mysql_fetch_assoc($res)) { echo “Name: “.$record[‘name’].”, email: “.$record[‘email’].”<br/>”; } mysql_free_results($res); • There are a number of ways for retrieving the results of a query. The most commonly used are • mysql_fetch_assoc(): returns an associative array where the keys are the record field names. • mysql_fetch_object(): returns a record as an object. There are object attributes for each record field.
MySQL & PHP: Things to remember • Usually you would get the data that you put in your database from the user. Make sure that the data will not break your SQL queries. • mysql_real_escape_string(): a useful function for escaping characters before using a string in an SQL query.
Suggested reading • Online Php Manualhttp://www.php.net/manual/en/index.php • Online MySQL Manualhttp://dev.mysql.com/doc/ • Web Application Development with PHPTobias Ratschiller, Till GerkenNew Riders Publishing