More PHP. PHP Version Differences PHP 5.0 requires use of the _REQUEST or _GET or _POST variables to access variables passed in by forms _REQUEST is an.

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

PHP I.
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.
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
PHP Hypertext Preprocessor Information Systems 337 Prof. Harry Plantinga.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Web Database Programming Using PHP.
PHP (2) – Functions, Arrays, Databases, and sessions.
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
Server side basics.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
15. User Authentication, Form Validation, Paging. M. Udin Harun Al Rasyid, S.Kom, Ph.D
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide
August Chapter 1 - Essential PHP spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
More PHP. PHP Version Differences PHP 5.0 requires use of the _REQUEST or _GET or _POST variables to access variables passed in by forms _REQUEST is an.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Advance web Programming Chapter 3: MySQL Date: 28 April 2014 Advance web Programming Chapter 3: MySQL Date: 28 April 2014 Dr. Mogeeb A. A. Mosleh .
Application Development Description and exemplification of server-side scripting language for server connection, database selection, execution of SQL queries.
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.
PHP : Hypertext Preprocessor
(c) Manzur Ashraf, Short course, KFUPM PHP & MySQL 1 Basic PHP Class 2.
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
Chap 3: Web Programming (CCSB144) - PHP 42 Chapter 4 - PHP Outline Introduction PHP String Processing and Regular Expressions Viewing Client/Server Environment.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
NMED 3850 A Advanced Online Design January 26, 2010 V. Mahadevan.
School of Computing and Information Systems CS 371 Web Application Programming PHP - Basics Serving up web pages.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
School of Computing and Information Systems CS 371 Web Application Programming PHP – Forms, Cookies, Sessions and Database.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
PHP - Part 2. More operators... Arithmetic and Assignment Operators e.g., using + and =  $IntA=5; $intB=8; $intC=$intA+$intB; //intC is 13  // Same.
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
Introduction to PHP A user navigates in her browser to a page that ends with a.php extension The request is sent to a web server, which directs the request.
Website Development with PHP and MySQL Saving Data.
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
Creating PHPs to Insert, Update, and Delete Data CS 320.
1 Introduction to PHP Part #2. 2 Simple PHP Script Consider the following HTML file, example.html: My Page Hello world!
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports.
Creating Databases Local storage. join & split Classwork: show 1 table application. Share designs for oscars application. Adaptive select. Homework: [Catch.
1 Chapter 7 – Object-Oriented Programming and File Handling spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
Storing and Retrieving Data
Server-Side Scripting with PHP ISYS 475. PHP Manual Website
PHP 4 Files, Functions. Opening a File The fopen() function is used to open files in PHP. The first parameter of this function contains the name of the.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
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.
Creating Databases for Web applications Server side vs client side PHP basics Homework: Get your own versions of sending working: both html and Flash!
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
8 th Semester, Batch 2009 Department Of Computer Science SSUET.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Web Database Programming Using PHP.
Files A collection of related data treated as a unit. Two types Text
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
Radoslav Georgiev Telerik Corporation
PHP using MySQL Database for Web Development (part II)
Web Database Programming Using PHP
CS 371 Web Application Programming
Web Database Programming Using PHP
PHP –MySQL Interview Question And Answer.
PHP / MySQL Introduction
Intro to PHP & Variables
CSE1320 Files in C Dr. Sajib Datta
PHP: Security issues FdSc Module 109 Server side scripting and
<?php require("header.htm"); ?>
PHP.
Web DB Programming: PHP
Presentation transcript:

More PHP

PHP Version Differences PHP 5.0 requires use of the _REQUEST or _GET or _POST variables to access variables passed in by forms _REQUEST is an array that contains variables passed in from the form This works on both PHP 4 and PHP 5 PHP 4 allows you to access form variables directly by name, but this doesn’t work in PHP 5

PHP 4 Only <? header("Content-Type: text/html"); print(" My Page "); print(" "); print(" "); if ($_SERVER['REQUEST_METHOD'] == ‘POST') { print("foo = $foo, bar = $bar "); } print(" "); ?>

PHP 4 or PHP 5 <? header("Content-Type: text/html"); print(" My Page "); print(" "); print(" "); if ($_SERVER['REQUEST_METHOD'] == 'POST') { print("foo = ". $_REQUEST["foo"]. ", bar = ". $_REQUEST["bar"]. " "); } print(" "); ?>

More PHP Here we will focus on additional functions that will be helpful for you to complete the homework assignment –Random number generation, sort, arrays (previously covered) –Type Checking is_array, is_string, is_long, is_double –Useful string functions strlen, implode, explode, substr, strstr, trim, char access –File I/O fopen, fread, feof, fclose, fwrite –Some examples

Type Checking PHP includes several functions to determine the type of a variable since it may not be obvious what the type is due to conversions is_int($x)// returns true if $x is an integer is_double($x)// returns true if $x is a double is_array($x)// returns true if $x is an array is_string($x)// returns true if $x is a string is_null($x)// returns true if $x is a null

String Functions We can access a string as an array to retrieve individual characters: $s=“hithere”; $z = $s[0]. $s[2]. $s[4]; print($z);// hte We can also assign characters to the string: $s[2] = “F”; print($s);// hiFhere

Strings String length: strlen($s) returns the length of the string $s="eat big macs"; for ($i=0; $i<(strlen($s)-1)/2; $i++) { $temp = $s[$i]; $s[$i] = $s[strlen($s)-$i-1]; $s[strlen($s)-$i-1] = $temp; } print($s);// Output : scam gib tae

Strings Substring: Searches a string for a substring Prototype: string strstr (string haystack, string needle) Returns all of haystack from the first occurrence of needle to the end. If needle is not found, returns FALSE. $ = $domain = strstr ($ , print ($domain); //

Strings strtolower($s) : returns $s in lowercase $s=“AbC”; $s = strtolower($s);// $s = “abc” strtoupper($s) : returns $s in uppercase $s = “AbC”; $s = strtoupper($s);// $s = “ABC” trim($s): returns $s with leading, trailing whitespace removed $s = “ \n ABC \r\n”; $s = trim($s);// $s = “ABC” Trim is useful to remove CR’s and Newlines when reading lines of data from text files or as input from a form (e.g. textbox, textarea)

Strings Substring: Format: string substr (string string, int start [, int length]) –Substr returns the portion of string specified by the start and length parameters. –If start is positive, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth. Examples: $rest = substr ("abcdef", 1); // returns "bcdef" $rest = substr ("abcdef", 1, 3); // returns "bcd"

Implode Implode is used to concatenate elements of an array into a single string string implode (string glue, array pieces) Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element. Examples $arr[]="A"; $arr[]="B"; $arr[]="C"; $s = implode(",",$arr);// $s = “A,B,C” $s = implode("",$arr);// $s = “ABC”

Explode Explode is used to create an array out of a string with some delimiter array explode (string separator, string string) Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator. Example $s="eat:large:fries"; $arr = explode(":",$s); print_r($arr); print(" "); Output: Array ( [0] => eat [1] => large [2] => fries )

File I/O Opening a file: fopen Format: int fopen (string filename, string mode) –Filename is the complete path to the file to open; must have proper permissions –Mode is one of the following 'r' - Open for reading only; place the file pointer at the beginning of the file. 'r+' - Open for reading and writing; place the file pointer at the beginning of the file. 'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. 'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. –Returns: a file pointer used to reference the open file

File I/O Reading from a text file: string fgets (int filepointer, int length) –Returns a string of up to length - 1 bytes read from the file pointed to by fp. –Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first). –We can use this function on files we have opened for reading

File I/O Writing to a text file: int fwrite (int fp, string string) –fwrite() writes the contents of string to the file stream pointed to by fp. –The file must be opened for writing Checking for end of file feof(int fp) Returns true if we have reached the end, false otherwise Closing a file fclose(int fp) Use when done with the file and close the file pointer

File I/O example $fd = fopen ("/proc/cpuinfo", "r"); while (!feof ($fd)) { $oneline = fgets($fd, 4096); print("$oneline "); } fclose ($fd);

fgets IMPORTANT – Remember that fgets returns the string WITH the newline This is critical if you are going to perform comparisons –You’ll get a false match if the newline is not accounted for –Easiest technique: trim out the newlines $oneline = trim(fgets($fp, 1024));

Example Create a single PHP script that generates a form with a textarea –Allow the user to enter numbers in the textarea –Submit the form to the same script –Compute the sum of the numbers in the textarea and print it out

Example.php <?php header("Content-Type: text/html"); print(" My Page "); print(" "); if($_SERVER['REQUEST_METHOD'] != "POST") { // We are loading for the first time, // not receiving a form. So generate // a form allowing the user to enter // data in a text area and have it submitted // to this same script print(" "); print("Enter numbers below. "); print(" "); }

Example.php else { // We are receiving data from our form // Put the text data into an array. Each // is separated by a newline, so use explode // to parse $a = explode("\n",$_REQUEST['myData']); // Here we loop through and add up the numbers $total = 0; foreach ($a as $key=>$value) { // Each element in the array is a string, // but note that each will contain a \r // whitespace at the end, so you may wish // to trim these out. It is not really // necessary in this example but you will // normally want to trim just to be safe $num = (int) trim($value); $total += $num; } print("The sum of your numbers is $total "); } print(" "); ?>

Accessing a MySql Database Here is the minimum for executing a mysql query from PHP. Given the following database:

// Database parameters $db_location = "localhost"; $db_user_name = "test"; $db_password = "test"; $database_name = "test"; // Connect to the DB $dbcnx = mysql_connect($db_location, $db_user_name, $db_password); mysql_select_db($database_name); // Display everything from the data table $result = mysql_query("SELECT * FROM data;"); print(" "); while ($row = mysql_fetch_assoc($result)) { $username = $row['username']; $val = $row['val']; $pw = $row['password']; print(" "); print(" $username $val $pw "); print(" "); } print(" "); ?> Reading from the DB

<?php // Database parameters $db_location = "localhost"; $db_user_name = "test"; $db_password = "test"; $database_name = "test"; // Connect to the DB $dbcnx = mysql_connect($db_location, $db_user_name, $db_password); mysql_select_db($database_name); // Insert a new record $result = mysql_query("INSERT INTO data (username, val, password) VALUES ('martin',55,'complexity');"); print("Result of insert: $result"); // True if successful ?> Writing to the DB

SQL Injection Example PHP code $id = $_REQUEST[“id”]; $pass = $_REQUEST[“password”]; $qry = “SELECT ccnum FROM cust WHERE id = $id AND pass=$pass”;

SQL Injection Example PHP code $id = $_REQUEST[“id”]; $pass = $_REQUEST[“password”]; $qry = “SELECT ccnum FROM cust WHERE id = ‘$id’ AND pass=‘$pass’”; User inputs id of user to attack For password, enters: ' OR 1=1 – -- is the comment operator, to ignore whatever comes afterwards Another: Password: 'OR ''='

Update Counter What’s wrong with this? <?php $h = fopen("counter.txt","r"); $count = fread($h, 100); fclose($h); $h = fopen("counter.txt","w"); fwrite($h, $count + 1); fclose($h); ?>

Update Counter Better <?php $h = fopen("counter.txt","r+"); if (flock($h, LOCK_EX)) { $count = fread($h, 100); rewind($h); fwrite($h, $count + 1); fclose($h); flock($h, LOCK_UN); ?>

Session Variables Variables that keep their state from one PHP script to another –Generally stored as a cookie for the browsing session <?php session_start(); // Must send before HTML $_SESSION['varname'] = value; // Use isset to see if set

Summary PHP is an imperative language for the web Similarities to C, Java, and even interpreted languages such as Scheme Competition to ASP,.NET Can’t do everything since server side only – often coupled with client-side languages such as JavaScript PHP version 5 not quite backward compatible with PHP 4 –More OOP, references allow for more efficiencies –Highlights design choice of evolving language Easy to write sloppy code so one must be more disciplined in design of classes, functions, variables, HTML, documentation

Lots More to PHP We have only scratched the surface, but there is much more that PHP can do –Generate graphics (gd library) –Networking, Sockets, IRC, –LDAP –Regular Expressions –PDF –Java –XML –AJAX –Design methodologies (e.g. FuseBox, Smarty Templates, include files) –Many more See the excellent resources online – – –