Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1.

Similar presentations


Presentation on theme: "PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1."— Presentation transcript:

1 PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1

2 2 PhpDoc Functions User-defined functions Function arguments Returning values Built-in functions Dealing with HTML Forms Data Validation Filesystem Functions Uploading files 2 Outline

3 3 PhpDoc Good documentation is essential to any software project. NetBeans 7 supports phpDocumentor that is designed to generate separate sets of documentation from the same source! http://manual.phpdoc.org/HTMLSmartyConverter/Han dS/phpDocumentor/tutorial_phpDocumentor.howto.p kg.html 3

4 4 PhpDoc Installation on Windows 7 phpDocumentor (known as PhpDoc) can be used to create professional documentation from PHP source code. 1. Install jdk-6u26-windows-i586.exe 2. Install netbeans-7.0-ml-php-windows.exe 3. Install xampp-win32-1.7.4-VC6-installer.exe

5 5 PhpDoc (cont’d) 4. Unzip PhpDocumentor-1.4.3.zip to C:\xampp 5. Edit C:\xampp\PhpDocumentor\phpdoc.bat on lines 17-18 SET phpCli=C:\xampp\php\php.exe cd C:\xampp\PhpDocumentor 6. Edit C:\xampp\php\php.ini on line 1001 date.timezone = Asia/Bangkok

6 6 PhpDoc (cont’d) 7. Go to NetBeans > Tools > Options > PHP 8. Set PHP 5 Interpreter to C:\xampp\php\php.exe

7 7 PhpDoc (cont’d) 9. Set PhpDoc script to C:\xampp\PhpDocumentor\phpdoc.bat -o HTML:frames:default

8 8 PhpDoc (cont’d) 10. Important! You need to change the Path manually at least once when you create a PhpDoc target directory. Go to Project Properties and look for PhpDoc. In Target Directory, the path to a directory should be a slash (/) rather than a backslash (\). Use phpdoc as your PhpDoc target directory

9 9 PhpDoc (cont’d) 11. Run Generate PhpDoc.

10 10 PhpDoc (cont’d) 12. PhpDoc is generated

11 11 PhpDoc (cont’d) /* Here are the tags: * @abstract * @access public or private * @author author name * @copyright name date * @deprecated description * @deprec alias for deprecated * @example /path/to/example * @exception Javadoc-compatible, use as needed 11

12 12 PhpDoc (cont’d) * @global type $globalvarname or * @global type description of global variable usage in a function * @ignore * @internal private information for advanced developers only * @param type [$varname] description * @return type description * @link URL * @name procpagealias or * @name $globalvaralias 12

13 13 PhpDoc (cont’d) * @magic phpdoc.de compatibility * @package package name * @see name of another element that can be documented, produces a link to it in the documentation * @since a version or a date * @static * @staticvar type description of static variable usage in a function * @subpackage sub package name, groupings inside of a project * @throws Javadoc-compatible, use as needed 13

14 14 PhpDoc (cont’d) * @todo phpdoc.de compatibility * @var type a data type for a class variable * @version version */ 14

15 15 PhpDoc (cont’d) <?php /* * @author Ken * @version 1.0 * example of a user defined square function * * @param int $num * @returns int */ function square($num) { return $num * $num; } echo square(4); ?> phpdoc_1.php

16 16 <?php phpinfo(); ?> 16 Function

17 17 User Defined Function <?php /* * example of a user defined square function * * @param int $num * @returns int */ function square($num) { return $num * $num; } echo square(4); ?> 17

18 18 Information may be passed to functions via the argument list, which is a comma-delimited (,) list of expressions. 18 Function Arguments

19 19 Function Arguments (cont’d) <?php // Example Use of return() function square($num){ return $num * $num; } echo square(4); // 16 ?> 19

20 20 <?php /* Example Use of default parameters in functions */ function makecoffee($type = "cappuccino"){ return "Making a cup of $type.\n"; } echo makecoffee(); echo makecoffee(null); echo makecoffee("espresso"); ?> Function Arguments (cont’d)

21 21 Function Arguments (cont’d) <?php // Passing function parameters by reference function add_some_extra(&$string){ $string.= "and something extra."; } $str = "This is a string, "; add_some_extra($str); echo $str; ?>

22 22 <?php /* Example Returning an array to get multiple values */ function small_numbers(){ return array (0, 1, 2); } print_r(list ($zero, $one, $two) = small_numbers()); ?> Returning Values – by an array

23 23 Returning Value – by a reference <?php //Returning a reference from a function function &square($number) { return $number * $number; } echo $val =& square(12); ?>

24 24 Date Time Mail Filesystem $_GET $_POST Header Exit Built-in Functions

25 25 <?php $d = date('l jS \of F Y h:i:s A'); echo $d; ?> Date Function date.php

26 26 <?php $t = time(); echo $t; ?> Time Function date.php

27 27 crypt — One-way string hashing explode — Split a string by string strlen — Get string length strtolower — Make a string lowercase strtoupper — Make a string uppercase trim — Strip whitespace (or other characters) from the beginning and end of a string wordwrap — Wraps a string to a given number of characters String Functions

28 28 One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. basic_form.html action.php HTML Forms

29 29 Text Boxes Text Areas Checkboxes Radio Buttons Hidden Fields Select The submit button HTML Forms (cont’d)

30 30 Your name: Your age: When the user fills in this form and hits the submit button, the action.php page is called. basic_form.html

31 31 Hi. You are years old. Above we just introduced the $_POST superglobal which contains all POST data. That is, the $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Notice the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead. action.php

32 32 Information sent from a form with the POST method is invisible in the browser's address bar, and has no limits on the amount of information to send. $_POST method

33 33 Information sent from a form with the GET method is visible in the browser's address bar, and has limits up to 100 characters. The $_GET should not be used when sending passwords or other sensitive information! $_GET method

34 34 <?php … // list.php 10 … ?> <?php // display.php echo $_GET[ ' id ' ]; // 10 ?> $_GET for passing information

35 35 Very Important! Without it, your site can be hacked! PHP makes it easier Do both client side and server side validations Client side validation is not secure because some browser like Firefox and Opera can disable JavaScript Server side validation cannot be disabled by a user Data Validation

36 36 Age, should be less than 100, and numeric. Otherwise, you should reject anything else if(strlen($_POST[ ' age ' ]) > 3) { // error message } if(!is_int($_POST[ ' age ' ])) { // error message } if(($_POST[ ' age ' ] > 100) || ($_POST[ ' age ' ] < 18)) { // error message } Data Validation - Server-side

37 37 header(string,replace,http_response_code) <?php // in action.php if ($is_hacked > 250) { /* returns a REDIRECT (302) status code to the browser */ header("location: error.php"); exit(); } ?> Header Function

38 38 Using other built-in functions, these files covers more examples of HTML forms data validation Anti-Hacking tips adv_form.html & action_2.php

39 39 One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address. In this part, I will show you how to send e-mail messages using PHP. Syntax bool mail ( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ]] ) Mail

40 40  To send an email <?php $to = 'nobody@example.com'; $subject = 'the subject'; $message = 'hello'; $headers = 'From: webmaster@example.com'. "\r\n". 'Reply-To: webmaster@example.com'. "\r\n". 'X-Mailer: PHP/'. phpversion(); mail($to, $subject, $message, $headers); ?> Mail (cont’d)

41 41 file_get_contents - Reads entire file into a string file_put_contents - Write a string to a file <?php // simple page hit counter $hits = file_get_contents('hits.txt'); echo $hits += 1; file_put_contents('hits.txt', $hits); ?> Filesystem Functions

42 42 Allow users to upload files from a form Allow users to upload both text and binary files With PHP's file manipulation functions ($_FILES), you have full control over what is to be done with the file once it has been uploaded. 42 action_3.php file_form.html File Upload

43 43 File Upload (cont’d) <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <form enctype="multipart/form-data" action="action_4.php" method="POST"> Send this file: 43 file_form.html

44 44 File Upload (cont’d) The contents of $_FILES from the example form is as follows. Note that this assumes the use of the file upload name userfile.$_FILES $_FILES['userfile']['name'] The original name of the file on the client machine. $_FILES['userfile']['type'] The mime type of the file, if the browser provided this information. An example would be "image/gif". $_FILES['userfile']['size'] The size, in bytes, of the uploaded file. $_FILES['userfile']['tmp_name'] The temporary filename of the file in which the uploaded file was stored on the server. $_FILES['userfile']['error'] The error code associated with this file upload. 44

45 45 File Upload (cont’d) <?php // action_3.php $uploaddir = './uploads/'; $uploadfile = $uploaddir. basename($_FILES['userfile']['name']); echo ' '; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "File is valid, and was successfully uploaded.\n"; } else { echo "Possible file upload attack!\n"; } echo 'Here is some more debugging info:'; print_r($_FILES); print " "; ?> 45 action_3.php

46 46 File Upload (cont’d) Restrictions on Upload <?php if ((($_FILES["userfile"]["type"] == "image/gif") || ($_FILES["userfile"]["type"] == "image/jpg") || ($_FILES["userfile"]["type"] == "image/jpeg") || ($_FILES["userfile"]["type"] == "image/png")) && ($_FILES["userfile"]["size"] < 512000)){ // < 500 KB // upload a file upload_file(); } else { echo "Invalid file or too big file! "; echo "Here is some more debugging info: "; print_r($_FILES); } … // upload_file() ?> 46 action_4.php The user may only upload.gif or.jpeg or.png files. The file size must be under 0.5 MB:

47 47 File Upload (cont’d) What If the file already exits? <?php … if (file_exists("./uploads/". $_FILES["userfile"]["name"])){ echo $_FILES["file"]["name"]. " already exists. "; } else { // upload a file upload_file(); } ?> 47

48 48 References Gregory Beaver (2009) phpDocumentor Guide to Creating Fantastic Documentation http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDo cumentor/tutorial_phpDocumentor.pkg.html Accessed: 25/04/2011.


Download ppt "PHP Basics 2 ICS213, 1 / 2011 Dr. Seung Hwan Kang 1."

Similar presentations


Ads by Google