PageRenderTime 39ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/lab11/worksheet.md

https://gitlab.com/NgocVo/Second_NgocVo
Markdown | 247 lines | 184 code | 63 blank | 0 comment | 0 complexity | 0687a9aecd7f47152447ee9719f3f759 MD5 | raw file
  1. # Introduction to PHP
  2. ## What is PHP?
  3. In this worksheet is an introduction to the PHP programming language.
  4. When implementing a Web-based application some processing is usually done on a client-side (web browser) and/or on a server-side (web server). The server creates a response programmatically since static content is not usually enough.
  5. This can be done in various ways: using PHP, Java Server Pages (JSP), Ruby, Python etc. PHP programming language is widely used and fairly easy to learn, so we are using PHP in this course.
  6. PHP is a scripting language meaning it is interpreted; it is translated to machine instructions and executed on the fly, rather than compiled to machine code before actually running a program.
  7. Traditionally a PHP program creates a dynamic content in the HTML page, for example client information read from the database which is stored in the server. Nowadays there is a trend towards to an API based processing: a PHP programming module is triggered by a REST API call and returns a JSON object as a response.
  8. Further reading: [PHP documentation home page][PHP]
  9. [PHP]: http://php.net/manual/en/
  10. ## Task List
  11. In this lab you
  12. - write small PHP code examples
  13. - learn how Javascript and PHP work together
  14. ## 1. PHP in C9
  15. Newly created Cloud9 workspaces run PHP 5.5 (5.5.9, 64-bit) by default. If you want to run a different version, you can use a tool like php-build to install it manually.
  16. You can run your PHP application on Cloud9 and use the built-in debugger to inspect your code in real-time. Read the documentation on Running and Debugging Your Code for a more detailed introduction.
  17. There are a few different ways to launch the debugger, depending on the kind of PHP script youre going to debug:
  18. ### 1.1 PHP Web Applications
  19. In this mode, Cloud9 launches the built-in PHP web server, activates the debugger, then opens a preview window.
  20. - Open the script you want to debug, for example index.php
  21. - Set at least one breakpoint (optional)
  22. - Choose Run > Run With > PHP (built-in web server)
  23. ### 1.2 PHP Console Commands
  24. If you have a command line script that you want to debug, you can run it directly using the console runner. In this mode, Cloud9 opens a terminal window, then launches a PHP process with the path to your script.
  25. - Open the CLI script you want to debug, for example hello-cli.php
  26. - Set at least one breakpoint (optional)
  27. - Choose Run > Run With > PHP (cli)
  28. ## 2. Basic PHP-program
  29. Take a look at the basic PHP-program below:
  30. ```php
  31. <?php // php-mode
  32. for ($i=1; $i<=20; $i++){
  33. echo $i;
  34. }
  35. ?>
  36. ```
  37. This file should be named using PHP-extension (not HTML-extension) for example Minimal.php, so that the server understands to execute the PHP-code.
  38. Note that the page is shown in the browser but it isn't valid HTML page. It doesn't have DOCTYPE or html element and so on. We could add additional print statements to output these tags, or we could use embedded PHP to produce valid page. But since we will be using PHP to give answers to the requests we send from Javascript, we don't care about this.
  39. ## 3 Some PHP-spesific features
  40. ### 3.1 Defining a variable
  41. A variable name in PHP is always preceded by a $ sign. The variable is defined by assigning it a value. The type information is not needed.
  42. The type of a variable is based on the type of an assigned value. The syntax template for variable definition is below:
  43. ```
  44. $name = expression
  45. ```
  46. Examples:
  47. ```php
  48. $user_name = "james";
  49. $age = 20;
  50. $under_age = $age - 5;
  51. ```
  52. Under_scores are forbidden by some programming style guides but let's follow the style of CodeIgniter which says:
  53. "variables should contain only lowercase letters, use underscore separators, and be reasonably named to indicate their purpose and contents. Very short, non-word variables should only be used as iterators in for() loops."
  54. ### 3.2 Loosely Typed Language
  55. PHP is loosely typed language like Javascript meaning that PHP tries to make a correct conversion. For example the code
  56. ```php
  57. <?php
  58. $text = "20.5testing";
  59. $number = 0;
  60. $f_number = 3.14;
  61. $number = $number + $text;
  62. $f_number = $f_number + $text;
  63. echo "Values ". $number . " and " . $f_number;
  64. ?>
  65. ```
  66. will print the result:
  67. ```
  68. Values 20.5 and 23.64
  69. ```
  70. You can use PHP function gettype to check a type. The function returns the type as a string. Or you can use is_string, is_float, is_int functions which return true or false. For example
  71. ```
  72. is_string("hello")
  73. ```
  74. returns true.
  75. ### 3.3 Strings
  76. As you saw in the preceeding examples strings in PHP are enclosed "-marks (quotation) or '-marks (apostrophe).
  77. Examples:
  78. ```php
  79. $str = "Writing PHP is cool";
  80. $printed = "Values $number and $f_number";
  81. $str2 = 'This is also a string';
  82. ```
  83. The first and the second are examples of interpreted strings, meaning you can write variable names inside a string and the values of variables will be inserted into a string.
  84. The third example is not interpreted so writing a variable name into this string have no special meaning.
  85. The + operator is always a numeric operator in PHP. String concatenation is done by using . (dot-operator).
  86. Strings in PHP are an array of characters so accessing an individual character is similar to many other languages: writing $str[0] returns "W" from the upper example.
  87. ## Test Your Understanding
  88. 1. Write the code snippet in 3.2 in a PHP file and put a breakpoint in it and 1) run it as a web application and 2) straight form the command line.
  89. 2. Write a PHP program where you define an array of strings. Make a loop going through the array and echo the values in the array.
  90. 3. Write a PHP program that calculates an area of a circle when the radius is known. You may use a hardcoded radius value.
  91. ## 4 PHP Ajax
  92. If you don't remember the use of XMLHttpRequest go through labs 08 and 09 explaining the use of AJAX.
  93. In the order.html file we have
  94. ```javascript
  95. <script language="javascript" type="text/javascript">
  96. //Browser Support Code
  97. function ajaxFunction(){
  98. var ajaxRequest; // The variable that makes Ajax possible!
  99. try{
  100. // Opera 8.0+, Firefox, Safari
  101. ajaxRequest = new XMLHttpRequest();
  102. } catch (e){
  103. // Internet Explorer Browsers
  104. try{
  105. ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
  106. } catch (e) {
  107. try{
  108. ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
  109. } catch (e){
  110. // Something went wrong
  111. alert("Your browser broke!");
  112. return false;
  113. }
  114. }
  115. }
  116. // Create a function that will receive data sent from the server
  117. ajaxRequest.onreadystatechange = function(){
  118. if(ajaxRequest.readyState == 4){
  119. document.myForm.time.value = ajaxRequest.responseText;
  120. }
  121. }
  122. ajaxRequest.open("GET", "php/serverTime.php", true);
  123. ajaxRequest.send(null);
  124. }
  125. </script>
  126. ```
  127. The lines
  128. ```javascript
  129. ajaxRequest = new XMLHttpRequest();
  130. ajaxRequest.open("GET", "php/serverTime.php", true);
  131. ajaxRequest.send(null);
  132. ```
  133. make an asynchronous request to the server. In the between after creating an XMLHttpRequest object, we attach to it a callback function which is called automatically when the status of the request changes (onreadystatechange method).
  134. ```javascript
  135. ajaxRequest.onreadystatechange = function(){
  136. if(ajaxRequest.readyState == 4){
  137. document.myForm.time.value = ajaxRequest.responseText;
  138. }
  139. }
  140. ```
  141. The response text received from the server is then put in the input field called time.
  142. ### 4.1 Superglobals
  143. There are several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
  144. One of these superglobals is $_REQUEST which is used to collect data after submitting an HTML form.
  145. For example we can ask
  146. ```php
  147. // get the q parameter from URL
  148. $q = $_REQUEST["q"];
  149. ```
  150. if our XMLHttpRequest has been
  151. ```javascript
  152. xmlhttp.open("GET", "gethint.php?q=" + str, true);
  153. ```
  154. and we get the value of the string which is sent by Javascript with the request. We have this kind of example in suggestions.html, where the Javascript code
  155. ```javascript
  156. <script>
  157. function showHint(str) {
  158. if (str.length == 0) {
  159. document.getElementById("txtHint").innerHTML = "";
  160. return;
  161. } else {
  162. var xmlhttp = new XMLHttpRequest();
  163. xmlhttp.onreadystatechange = function() {
  164. if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
  165. document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
  166. }
  167. };
  168. xmlhttp.open("GET", "php/gethint.php?q=" + str, true);
  169. xmlhttp.send();
  170. }
  171. }
  172. </script>
  173. ```
  174. is making an XMLHttpRequest to be sent to gethint.php.
  175. ## Test your understanding
  176. 1. Change the order.html and serverTime.php files in the following way: put a button on the page, when it's clicked, the php is requested for a random number, which is the shown by the javascript callback function.
  177. 2. Change the suggestions.html and gethint.php in the following way: change the php program to return the first name of the hints in a JSON format and show it by the javascript callback function.
  178. Hint. Use an array in PHP like
  179. ```javascript
  180. $vihjeet = [
  181. "firstName":"Erkki"
  182. ];
  183. ```
  184. Change it to JSON format and return JSON to Javascript callback.