6_PHP_I_COMP3322B_s2019.pdf - COMP 3322B Modern Technologies on World Wide Web 2nd semester 2018-2019 PHP Part I(O2 Dr C Wu Department of Computer

6_PHP_I_COMP3322B_s2019.pdf - COMP 3322B Modern...

This preview shows page 1 out of 31 pages.

You've reached the end of your free preview.

Want to read all 31 pages?

Unformatted text preview: COMP 3322B Modern Technologies on World Wide Web 2nd semester 2018-2019 PHP - Part I (O2) Dr. C Wu Department of Computer Science The University of Hong Kong What we are going to learn next Technologies for creating dynamic, interactive web pages PHP [server side] JavaScript (AJAX, JSON, jQuery) [client side] HTML5 [client side] Node.js [server side and client side] AngularJS [client side] React [client side] PHP basics PHP stands for hypertext preprocessor PHP is a server-side scripting language, executed on the server PHP files can contain text, HTML, CSS, JavaScript, and PHP script PHP files are returned to the browser as HTML documents PHP files have a file extension of ".php" Widely used for making dynamic and interactive web pages PHP runs efficiently on different platforms (Windows, Linux, Unix, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP syntax A PHP script can be placed anywhere in the document A PHP script starts with <?php and ends with ?> On servers with shorthand support (set short_open_tag=on in php.info), a PHP script can start with <? and end with ?> echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!'; Each code line in PHP script must end with a semicolon example <html> <body> <?php echo "Hello World"; ?> </body> </html> two basic statements to output text and variables: echo and print. PHP variables Variables start with $, followed by the name of the variable The variable name must begin with a letter or _ A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case sensitive A variable is created the moment you first assign a value to it: $myCar="Volvo"; If you create/use a variable without assigning it a value, then it has the value of null. a variable does not need to be declared before assigning a value to it we do not have to tell PHP which data type the variable is PHP automatically converts the variable to the correct data type, depending on its value PHP variables (cont’d) Main PHP data types string (enclosed in single or double quotes), integer, float, boolean, null, array: <?php $cars = array("Volvo", "BMW", "Toyota"); echo $cars[0]; ?> <?php $colors = array("Peter"=>"red", "Joe"=>"blue", "Amy"=>"pink"); echo $colors['Peter']; ?> indexed array object: associative array <?php class Movie { func3on Movie() { $this->name = "Mission Impossible"; } } $mymovie = new Movie(); echo $mymovie->name; ?> key can be integer and string; value can be of any type PHP variables (cont’d) Some special predefined variables (superglobals) $_GET, an associative array containing variables and values sent from the client with the get method $_POST, an associative array containing variables and values sent from the client with the post method $_COOKIE, an associative array containing cookie variables and values $_SESSION, an associative array containing session variables and values PHP statements, operators and function PHP supports a number of statements (If/Else, Switch, While, For, etc.) and operators (+, - , * , /, etc.) check out for details not case sensitive PHP supports functions PHP provides more than 1000 built-in functions hUp://php.net/manual/en/indexes.func3ons.php <?php or we define our own functions: . is string concatena3on operator in PHP func3on concat($str, $num) { return $str.$num; } echo concat("I am No. ", 1); ?> Case sensitivity in PHP Case sensitive variables constants array keys class properties Case insensitive function names class contructors/methods keywords and constructs (e.g., if, else, echo, etc.) PHP server-side processing How to retrieve client-side input data? How to perform server-side computation? How to keep the state information of a client across different pages he/she accessed? How to store information permanently on the server? Two methods to send data to server HTTP'Request'message'format' Request'line' HTTP GET and POSTrequest Header' HTTP'R Blank'line' Data can be sent to the server through two methods HTTP request Request$line' HTTP'Request'message'format' Body' GET – pass data data along along in the URL. GET: pass in the URL Request'line' Request' HTTP'' as_sitesearch=hku.hk URL' Request line method' version' Header' Variable name : q space'Value : computer Variable name : hl as_sitesearch space' \r\n' Value : hku.hk en HTTP'' Blank'line' Request' URL' POST – pass data in the GET'''/~c0322/test/index.html'''HTTP/1.1' version' POST: method' pass data in the body of HTTP request y g p Try to change “computer” body of HTTP request. request space' space' \r\n' Example' to “apple”, or change “en” GET'''/~cwu/c0322/index.html'''HTTP/1.1' to “zh TW” to see Example' different pages generated q=computer&as_sitesearc h=hku.hk Body' GET Two typical cases where GET is used to send data to server Case 1. Submit an HTML <form>, with form attribute method ="get”; the data entered into the form will be appended to the end of the url (specified in the action attribute) in name/value pairs Example <form action=" ; method="get"> <fieldset> <legend>Search String</legend> <input type="text" name="q"> <input type="hidden" name="as_sitesearch" value="hku.hk"> </fieldset> <input type="submit" value=“Site Search”> </form> yoursearchstring URL in the GET request generated after clicking submit button: GET Case 2. Click a hyperlink on an HTML page, with variable and value appended at the end of the target URL Example <p>Click your favourite breakfast recipe below: </p> <ul> <li><a href="hUp:// toast</a></li> <li><a href=“hUp:// tart</a></li> <li><a href=“hUp:// prata</a></li> </ul> Screenshot Example 1 (login.html) A login <form> using the GET method <!DOCTYPE html> <html> <head> <3tle>Login page</3tle> </head> <body> <form ac3on="processLogin.php" method="get"> Login name <input type="text" name="loginName"><br> Password <input type="password" name="loginPassword"><br> <input type="submit"> </form> </body> </html> login.html Browser display of login.html Example 1 (processLogin.php) php) (processLogin.php) When the <form> isExample submitted, the 1 (processLogin cwu ***** browser sends an HTTP GET request to Login <form> using GET method. method retrieve the page specified in the action attribute (i.e., processLogin.php), When the <form>and is submitted appends the variable names and values at When the <form> with method = “get” is the end of the requested url submitted, the browser will send an HTTP request Browser display of Browser display of login.html login.html to retrieve the page specified in the <form> action (i.e., processLogin.php). The browser will append the variable names and values at the end of the requested page. 9 Example 1 (processLogin php) (processLogin.php) Login <form> using GET method. method When the <form> is submitted When the <form> with method = “get” is submitted, the browser will send an HTTP request to retrieve the page specified in the <form> action (i.e., processLogin.php). Browser display of login.html The browser will append the variable names and values at the end of the requested page. GET /~c0322/processLogin.php?loginName=cwu&loginPassword=12345 HTTP/1.1 Host : i.cs.hku.hk User-Agent : Mozilla/5.0 …… 9 Example 1 (processLogin.php) Example 1 (processLogin.php) Access the “GET” data on server side <!DOCTYPE html> <html> <head> <3tle>Process Login</3tle> </head> <body> <? print "<p>".$_GET['loginName']."</p>"; print "<p>".$_GET['loginPassword']."</p>"; ?> </body> </html> processLogin.php $_GET['variableName'] can access the variable passed by GET method HTML was designed to display data; XM transport and store data. Example 1 (client-server interaction) HTTP request GET /~c0322/processLogin.php?loginName=cwu&loginPassword=12345 … HTTP$request$(URL,$e.g.$h3p:// file.jsp?te Client$(web$browser)$ HTTP response Web$server$ HTTP/1.1 200 OK …. <!DOCTYPE html> <html> <head> <3tle>Process Login</3tle> </head> <body> <p>cwu</p> <p>12345</p> </body> </html> A Run PHP script and p output HTML c u P In Disadvantages of the GET method Limit on variable lengths: many servers put an upper limit on how many characters you can put in the URL Security issue: information that you fill in the <form>, including the masked password field, becomes visible in the URL when you submit the form POST The POST method sends your data to the server through the body part in an HTTP request The information in your <form> won't appear in the URL Usually a larger upper limit is put on the number of bytes that can be transmitted via the POST method Example 2 (login.html) A login <form> using the POST method <!DOCTYPE html> <html> <head> <3tle>Login page</3tle> </head> <body> <form ac3on="processLogin.php" method="post"> Login name <input type="text" name="loginName"><br> Password <input type="password" name="loginPassword"><br> <input type="submit"> </form> </body> </html> login.html Browser display of login.html Example 2 (processLogin.php) Example 1 cwu When the <form> is submitted, the (processLogin php) (processLogin.php) ***** browser sends an HTTP POST request to retrieve the page specified in the action Login <form> using GET method. method attribute (i.e., processLogin.php), and When the <form> is submitted the variable names and values are sent in When the <form> with method = “get” is the body part of the HTTP POST request Browser display of submitted, the browser will send an HTTP request message to retrieve the page specified in the <form> action login.html Browser display of login.html (i.e., processLogin.php). The browser will append the variable names and values at the end of the requested page. 9 Example 2 (processLogin.php) POST /~c0322/processLogin.php HTTP/1.1 Host : i.cs.hku.hk User-Agent : Mozilla/5.0 ..... Content-Type: applica3on/x-www-form-urlencoded Content-Length: 33 The browser will append the variable names and values at the end of the requested page. When the <form> with method = “get” is submitted, the browser will send an HTTP request to retrieve the page specified in the <form> action (i.e., processLogin.php). 9 loginName=cwu&loginPassword=56789 default content type when sending form data using post: encoding key/value pairs using URL encoding on nonalphanumeric characters ( html/html_urlencode.asp) Browser display of login.html When the <form> is submitted Login <form> using GET method. method Example 1 (processLogin php) (processLogin.php) Example 2 (processLogin.php) Access the “POST” data on server side <!DOCTYPE html> <html> <head> <3tle>Process Login</3tle> </head> <body> <? print "<p>".$_POST['loginName']."</p>"; print "<p>".$_POST['loginPassword']."</p>"; ?> </body> </html> processLogin.php $_POST['variableName'] can access the variable passed by POST method Server-side computation using PHP Client side does not know about the processing on the server side; only the generated html page will be sent to the client side Example 3 (processLogin.php) Example 3 (processLogin.php) (processLogin php) <!DOCTYPE HTML PUBLIC " //W3C//DTD HTML 4.01 Transitional//EN" <!DOCTYPE html> " ; p g <html> <head> String array variable <title>Process Login</title> </head> Note that h PHP variables bl are dynamically d dynamic typed, d typed <body> <? if we use 'single quote' or "double quote" $user_name[0]="Kit"; to indicate the value of a variable, the $user_password[0]='password'; variable is regarded as string automatically. automatically $user_account_balance[0]= 1000; $user_name[1]="Bobby"; $user_password[1]="password2"; $user_account_balance[1]= 2000; PHP array is very flexible! g or a string. g The keyy can either be an integer The value can be of any type. $user_name[2]="Harry"; $user_password[2]="password3"; $user_account_balance[2]= 3000; 17 Example 3 Example 3 (processLogin.php) (processLogin php) (processLogin.php) <!DOCTYPE HTML PUBLIC " //W3C//DTD HTML 4.01 Transitional//EN" <!DOCTYPE html> " ; p g <html> <head> Integer array variable <title>Process Login</title> </head> The h $user_account_balance $ b l variable bl is an <body> <? array variable. $user_name[0]="Kit"; $user_password[0]='password'; $user_account_balance[0] $user account balance[0] stores an integer $user_account_balance[0]= 1000; value $user_name[1]="Bobby"; $user_password[1]="password2"; $user_account_balance[1]= 2000; $user_name[2]="Harry"; $user_password[2]="password3"; $user_account_balance[2]= 3000; … 18 Example 4 (processLogin.php) (processLogin php) Example 3 (processLogin.php) … if (in (in_array($_POST[ array($ POST["loginName"] loginName ],$user_name)){ $user name)){ in_array() }else{ print "No such user!"; } in_array() – The in_array() function checks if a value exists in an array 24 Example 4 (processLogin.php) (processLogin php) Example 3 (processLogin.php) … if (in (in_array($_POST[ array($ POST["loginName"] loginName ],$user_name)){ $user name)){ $key = array_search($_POST["loginName"], $user_name); array_search() }else{ print "No such user!"; } array_search() array search() – The array_search() function searches the array for a given value and returns the corresponding key. key 25 Example 3 (processLogin.php) Example 4 (processLogin.php) (processLogin php) … Now we know how to if (in (in_array($_POST[ array($ POST["loginName"] loginName ],$user_name)){ $user name)){ perform f server side id $key = array_search($_POST["loginName"], $user_name); if ($user_password[$key] == $_POST["loginPassword"]){ processing, but every print "Login correct!<br>"; time we reload Browser display of print "Name Name :" : .$user_name[$key]. $user name[$key] "<br>"; <br> ; processLogin.php when print "Account balance:".$user_account_balance [$key].'<br>'; login.php we are [$key]."<br>"; login is successful asked to login again. }else print "Login Login fail!"; fail! ; Question: }else{ How to make the print "No such user!"; } server remember the 'login.html'>Back to login page</a>"; print "<br><a <br><a href href='login.php'>Back login.php >Back to login page</a>"; page</a> ; l i information login i f i off ?> </body> each client? </html> 26 References PHP tutorial: PHP project page: ...
View Full Document

  • Fall '13
  • Dr. C. Wu
  • Computer Science, Hypertext Transfer Protocol, Volvo, CWU

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture